Why rolling the clock back won't extend your grace period
A normally-online app has to keep working through a license-server outage without becoming a permanent offline bypass. This post builds Keyright's bounded offline grace period over a signed last-known-good entitlement: a signed confirmation timestamp, a wall-clock high-water mark plus a within-boot monotonic floor that together defeat a rolled-back clock, a hard offline ceiling, re-sync on reconnect, and a countdown warning that tells the user exactly how long they have.
A normally-online application has to survive a license-server outage. If a DNS blip or a routine deploy of your self-hosted Keyright instance gates every paying customer at once, you have turned a thirty-second infrastructure event into a support incident. So you cache the last good validation and keep working. Fine — but now you have built a bypass. Pull the network cable, keep the cached entitlement, and the app runs forever. The whole problem is drawing a hard line between “briefly offline” and “offline on purpose, indefinitely,” using a clock the user is free to lie about.
The real question
An offline grace window is a countdown: keep working for up to 72 hours since the last successful check, then lock. To run that countdown you need to answer one question on every launch — how long has it been since the service last confirmed this license? — and the only timepiece on the machine is DateTimeOffset.UtcNow, which the user owns. Wind it backwards and “how long has it been?” answers negative, and the window never elapses.
So the mechanism is not really “cache the result.” It is: measure elapsed offline time in a way a dishonest local clock cannot shrink, and fail closed when you genuinely cannot tell. Everything below is in service of that.
The cached last-known-good entitlement
Start with what we cache. On every successful online check the service returns not just valid/invalid but a signed snapshot of the entitlement, stamped with the instant it was confirmed. That stamp is inside the signed payload, so it is not something the client can edit.
public sealed record CachedEntitlement
{
public required string LicenseId { get; init; }
public required IReadOnlyList<string> Entitlements { get; init; }
public required DateTimeOffset ConfirmedAtUtc { get; init; } // signed by the service at last contact
public required DateTimeOffset NotAfter { get; init; } // the license's own expiry
public required byte[] CanonicalBytes { get; init; } // exact bytes the signature covers
public required byte[] Signature { get; init; }
}
ConfirmedAtUtc is the anchor the countdown runs from, and it is trustworthy precisely because it came from the server and is signed. A user can change their machine clock; they cannot move a timestamp inside a signed payload without invalidating the signature, and an invalid signature fails closed immediately. Loading the cache always re-verifies the signature against the pinned public key before anything else looks at a single field.
Bounding grace against a clock you don’t trust
Here is the core. Grace is measured from the signed ConfirmedAtUtc, not from a local “last seen offline” marker. But UtcNow is still what tells us where now is, so we guard it with two cheap, persisted pieces of state.
public sealed record ClockFloor
{
public required DateTimeOffset HighWaterUtc { get; init; } // newest wall-clock instant ever observed
public required long MonotonicAnchor { get; init; } // Environment.TickCount64 at that moment
public required byte[] Mac { get; init; } // machine-bound HMAC over both fields
}
HighWaterUtc is a monotonic high-water mark of the wall clock: the latest instant the SDK has ever seen. It only ever rises. MonotonicAnchor is a sample of Environment.TickCount64 — milliseconds since the machine booted — taken at the same instant. The monotonic clock cannot be set by the user and cannot run backwards within a single boot, which is exactly the property the wall clock lacks.
public GraceDecision Evaluate(CachedEntitlement cached, ClockFloor? prior)
{
DateTimeOffset now = DateTimeOffset.UtcNow;
long tick = Environment.TickCount64;
// 1. Backward wall clock is tamper. The clock now reads earlier than the newest
// instant we have ever trusted — a deliberate rollback (allowing a little skew).
if (prior is not null && now < prior.HighWaterUtc - _options.ClockSkew)
return GraceDecision.Tampered; // fail closed; never extend grace on a rewound clock
// 2. Elapsed offline, measured from the SERVICE-SIGNED confirmation instant.
TimeSpan offline = now - cached.ConfirmedAtUtc;
if (offline < TimeSpan.Zero) offline = TimeSpan.Zero; // future-dated clock can never read as "less offline"
// 3. Within one boot the monotonic clock is a FLOOR on real elapsed time that a
// frozen or rewound wall clock cannot undercut.
if (prior is not null && tick >= prior.MonotonicAnchor)
{
var monotonic = TimeSpan.FromMilliseconds(tick - prior.MonotonicAnchor);
if (monotonic > offline) offline = monotonic;
}
if (offline > _options.MaxOfflineDuration) return GraceDecision.Locked; // hard ceiling
if (offline > _options.GracePeriod) return GraceDecision.Locked; // ordinary window
return GraceDecision.Granted with { Remaining = _options.GracePeriod - offline };
}
Walk the attacks. Winding the clock back past HighWaterUtc trips check 1 and fails closed. Winding it forward only makes offline larger, so it hurts the attacker, not you. Freezing the clock is defeated within a boot by check 3: Environment.TickCount64 keeps climbing, so monotonic grows past offline and the window still elapses in real time. The one case the client alone cannot catch is a reboot — TickCount64 resets to near zero — but a reboot also loses the in-flight session, and the persisted HighWaterUtc still refuses any clock earlier than the newest moment ever seen. MaxOfflineDuration is the backstop over all of it: no cached entitlement is honoured past ConfirmedAtUtc + MaxOfflineDuration no matter how clean the clock looks.
After the decision, advance the floor forward only — never backward — and re-MAC it so an edited store is rejected rather than trusted.
public void Persist(DateTimeOffset now, long tick, ClockFloor? prior)
{
var high = prior is null ? now : (now > prior.HighWaterUtc ? now : prior.HighWaterUtc);
var next = new ClockFloor { HighWaterUtc = high, MonotonicAnchor = tick, Mac = Array.Empty<byte>() };
AtomicWrite(next with { Mac = Mac(next) }); // temp + File.Move(overwrite): a crash cannot corrupt it
}
The MAC is keyed to the machine, so a value the SDK did not write on this machine recomputes to a different tag and Read treats it as “never seen” — or, in fail-closed mode, refuses outright. The best a local attacker can do is delete the floor; they cannot forge an earlier valid one.
Configuring and re-syncing
Grace is configured once, where you initialise the client. GracePeriod rides out a realistic transient event; MaxOfflineDuration is the coarse ceiling tied to your billing cadence.
static readonly KeyrightClient License = KeyrightClient.Initialize(new KeyrightOptions
{
Product = "acme-suite",
PublicKeyBase64 = "MIIBIjANBgkq...", // ships in your binary; not a secret
ServiceUrl = "https://keyright.example.com", // your self-hosted instance
GracePeriod = TimeSpan.FromHours(72), // keep working this long after last contact
MaxOfflineDuration = TimeSpan.FromDays(14), // absolute ceiling on cached operation
ClockSkew = TimeSpan.FromMinutes(5), // tolerance before a backward clock is tamper
});
Validate() is the pure, offline, never-throwing check that every gate decision calls; it reads the cached entitlement and runs the grace evaluation above. The network work lives in RefreshAsync, which you run on a timer or on app-resume — never on the hot path. A confirmed refresh renews ConfirmedAtUtc, which resets the countdown; an unreachable service is the only result that keeps you on cache.
RefreshResult r = await License.RefreshAsync(ct);
if (r.Status == RefreshStatus.Confirmed)
_log.LogInformation("License re-confirmed; grace window reset.");
else if (r.Status is RefreshStatus.Revoked or RefreshStatus.Expired)
GateApplication(r.Reason); // the service reached us and said no — definitive, fail closed now
// RefreshStatus.ServiceUnreachable: learned nothing; the cached entitlement still stands within its window
The countdown the user actually sees
A silent grace window that locks on a Monday morning is a worse experience than the outage it was meant to hide. Surface GraceRemaining so the user can act while they still can.
LicenseInfo info = License.Validate();
if (info.ValidationSource == ValidationSource.Cache)
{
TimeSpan left = info.GraceRemaining;
if (left < TimeSpan.FromHours(24))
ShowBanner($"License server unreachable. Reconnect within {left:hh\\:mm} to stay licensed.");
}
if (info.Edition == LicenseEdition.Community)
DisablePaidFeatures(); // grace exhausted or clock tamper: narrow to the free surface, cleanly
Escalate the banner as the window shrinks — informational at 24 hours, prominent under 6, a blocking dialog at the end — and make every message name the action (“reconnect”), never a stack trace. Because the locked state is just Community Edition, there is no separate “we locked you out” code path to write and no reinstall to recover from: one successful refresh and the paid surface returns.
When it breaks, honestly
The within-boot monotonic floor is defeated by a reboot, which resets TickCount64. That is deliberate — across reboots the defence falls back to the persisted HighWaterUtc and to MaxOfflineDuration, and a determined local-admin attacker who deletes the floor store and reboots and has an unexpired cached entitlement is the one combination the client alone cannot stop. The architectural answer, not a cryptographic one, is to pair grace with a short NotAfter: a cached entitlement that expires in days dies on its own timetable even if every clock check is subverted, and the online re-sync closes the gap the moment the machine reconnects. Also note that ClockSkew is a real tolerance you tune against machines with legitimately bad clocks — set it too tight and NTP corrections look like attacks; too loose and you hand back a usable rollback margin.
Takeaway
Caching the last good check is the easy half; the hard half is bounding it against a clock the user controls. Anchor the countdown to a service-signed ConfirmedAtUtc, refuse any wall clock earlier than the newest you have ever seen, floor elapsed time with a within-boot monotonic clock, and cap the whole thing with MaxOfflineDuration. Do that and a brief outage costs your customer nothing, while unplugging the cable and winding the clock back buys minutes — never forever. Keyright’s Community Edition is the fail-closed target, and the Keyright docs cover tuning GracePeriod, MaxOfflineDuration, and clock-tamper handling.
Try Nebula.NET
Harden your .NET code in minutes — start with the free edition.