diff --git a/cmd/cryptship-loader/main.go b/cmd/cryptship-loader/main.go index eb8faf5..4e4277b 100644 --- a/cmd/cryptship-loader/main.go +++ b/cmd/cryptship-loader/main.go @@ -8,8 +8,13 @@ package main import ( + "bytes" "context" + "crypto/ed25519" + "crypto/rand" + "encoding/hex" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -26,6 +31,7 @@ import ( "github.com/AI2TH/cryptship/pkg/crypto" "github.com/AI2TH/cryptship/pkg/keyprovider" "github.com/AI2TH/cryptship/pkg/license" + "github.com/AI2TH/cryptship/pkg/online" ) type config struct { @@ -97,7 +103,7 @@ func run(cfg config) error { if lic.Claims.Expired(time.Now().Unix()) { return fmt.Errorf("license outside validity window (expires %d)", lic.Claims.NotAfter) } - if err := enforceRevocation(lic); err != nil { + if err := enforceRevocation(lic, ring); err != nil { return err } @@ -263,28 +269,36 @@ func escapeID(licenseID string) string { return url.PathEscape(licenseID) } // operator's failure policy (CRYPTSHIP_REVOCATION): "open" (default, run on // error), "closed" (refuse on error), "grace:" (run if a prior successful // check is younger than ). Only "closed" is a hard guarantee. -func enforceRevocation(lic *license.License) error { +// +// A cryptship-server signs the check response; the loader verifies it against +// the vendor key ring, so an on-path attacker or captive portal cannot forge +// "not revoked". In "closed" mode an UNSIGNED "active" answer is rejected. +func enforceRevocation(lic *license.License, ring license.KeyRing) error { if lic.Claims.RevocationURL == "" { return nil } mode := env("CRYPTSHIP_REVOCATION", "open") - stateFile := stateFile("revocation", lic.Claims.LicenseID) + sf := stateFile("revocation", lic.Claims.LicenseID) - revoked, err := checkRevocation(lic) - if err == nil { - if revoked { - return fmt.Errorf("license %s has been revoked", lic.Claims.LicenseID) - } - _ = os.MkdirAll(filepath.Dir(stateFile), 0o700) - _ = os.WriteFile(stateFile, []byte(strconv.FormatInt(time.Now().Unix(), 10)), 0o600) + revoked, signed, err := checkRevocation(lic, ring) + if err == nil && revoked { + return fmt.Errorf("license %s has been revoked", lic.Claims.LicenseID) + } + if err == nil && (signed || mode != "closed") { + _ = os.MkdirAll(filepath.Dir(sf), 0o700) + _ = os.WriteFile(sf, []byte(strconv.FormatInt(time.Now().Unix(), 10)), 0o600) return nil } + if err == nil && !signed && mode == "closed" { + err = errors.New("revocation response was unsigned; CRYPTSHIP_REVOCATION=closed requires a signing cryptship-server") + } + switch { case mode == "closed": return fmt.Errorf("revocation check failed and CRYPTSHIP_REVOCATION=closed: %w", err) case strings.HasPrefix(mode, "grace:"): if d, perr := time.ParseDuration(strings.TrimPrefix(mode, "grace:")); perr == nil { - if b, rerr := os.ReadFile(stateFile); rerr == nil { + if b, rerr := os.ReadFile(sf); rerr == nil { // A last-success time in the future (clock set back, or a // hand-edited file) does not count as within grace. if last, lerr := strconv.ParseInt(strings.TrimSpace(string(b)), 10, 64); lerr == nil && @@ -302,35 +316,62 @@ func enforceRevocation(lic *license.License) error { } } -// checkRevocation returns (revoked, err). 200 = active, 410 = revoked, anything -// else is an error so the operator's policy decides. -func checkRevocation(lic *license.License) (bool, error) { +// checkRevocation returns (revoked, signed, err). It sends a nonce and, if the +// server returns a signed online.CheckResponse that verifies against the ring +// and echoes the nonce, trusts its Revoked flag (signed=true). Otherwise it +// falls back to the legacy status-code reading (200 active / 410 revoked), +// reported as unsigned. +func checkRevocation(lic *license.License, ring license.KeyRing) (revoked bool, signed bool, err error) { u, err := url.Parse(lic.Claims.RevocationURL) if err != nil { - return false, err + return false, false, err + } + nonce := make([]byte, 16) + if _, err := rand.Read(nonce); err != nil { + return false, false, err } q := u.Query() q.Set("license_id", lic.Claims.LicenseID) + q.Set("nonce", hex.EncodeToString(nonce)) u.RawQuery = q.Encode() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) if err != nil { - return false, err + return false, false, err } resp, err := http.DefaultClient.Do(req) if err != nil { - return false, err + return false, false, err } defer resp.Body.Close() - _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096)) + body, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10)) + + // Signed path: a valid, nonce-matching CheckResponse is authoritative. + var cr online.CheckResponse + if json.Unmarshal(body, &cr) == nil && len(cr.Sig) > 0 && + cr.LicenseID == lic.Claims.LicenseID && bytes.Equal(cr.Nonce, nonce) { + pub, ok := ring[cr.SigningKeyID] + if !ok { + pub, ok = ring["*"] + } + if !ok || len(pub) != ed25519.PublicKeySize || !ed25519.Verify(pub, online.CheckSigningInput(cr), cr.Sig) { + return false, false, errors.New("revocation check: bad response signature") + } + if cr.NotAfter != 0 && time.Now().Unix() > cr.NotAfter { + return false, false, errors.New("revocation check: response expired") + } + return cr.Revoked, true, nil + } + + // Legacy unsigned path. switch resp.StatusCode { case http.StatusOK: - return false, nil + return false, false, nil case http.StatusGone: - return true, nil + return true, false, nil default: - return false, fmt.Errorf("unexpected status %s", resp.Status) + return false, false, fmt.Errorf("unexpected status %s", resp.Status) } } diff --git a/cmd/cryptship-loader/main_test.go b/cmd/cryptship-loader/main_test.go index 18805ec..69b8ffe 100644 --- a/cmd/cryptship-loader/main_test.go +++ b/cmd/cryptship-loader/main_test.go @@ -108,15 +108,15 @@ func TestRevocationGraceIgnoresFutureTimestamp(t *testing.T) { } write(time.Now().Add(-10 * time.Minute).Unix()) - if err := enforceRevocation(lic); err != nil { + if err := enforceRevocation(lic, license.KeyRing{}); err != nil { t.Fatalf("recent success should be within grace: %v", err) } write(time.Now().Add(-2 * time.Hour).Unix()) - if err := enforceRevocation(lic); err == nil { + if err := enforceRevocation(lic, license.KeyRing{}); err == nil { t.Fatal("old success accepted as within grace") } write(time.Now().Add(365 * 24 * time.Hour).Unix()) - if err := enforceRevocation(lic); err == nil { + if err := enforceRevocation(lic, license.KeyRing{}); err == nil { t.Fatal("future success timestamp accepted as within grace") } } diff --git a/cmd/cryptship-loader/providers.go b/cmd/cryptship-loader/providers.go index 309a7c4..c3707e0 100644 --- a/cmd/cryptship-loader/providers.go +++ b/cmd/cryptship-loader/providers.go @@ -2,6 +2,7 @@ package main import ( "net/http" + "os" "time" "github.com/AI2TH/cryptship/pkg/keyprovider" @@ -10,11 +11,25 @@ import ( // buildProviders returns the key providers the loader will try, in order. The // vendor key ring verifies signed server responses (online / attested). +// +// Online outage grace is opt-in: set CRYPTSHIP_ONLINE_GRACE to a duration (e.g. +// "12h") to let a cached, machine-sealed secret ride out a server outage for +// that long. It is off by default (every start needs the server). func buildProviders(ring license.KeyRing) []keyprovider.Provider { httpClient := &http.Client{Timeout: 10 * time.Second} + + var grace time.Duration + if v := os.Getenv("CRYPTSHIP_ONLINE_GRACE"); v != "" { + if d, err := time.ParseDuration(v); err == nil { + grace = d + } else { + os.Stderr.WriteString("cryptship-loader: WARNING: bad CRYPTSHIP_ONLINE_GRACE, grace disabled: " + err.Error() + "\n") + } + } + return []keyprovider.Provider{ keyprovider.Offline{}, - keyprovider.Online{Keys: ring, Client: httpClient}, + keyprovider.Online{Keys: ring, Client: httpClient, CacheDir: stateDir(), Grace: grace}, keyprovider.Attested{Keys: ring, Client: httpClient, Attester: keyprovider.DefaultAttester()}, } } diff --git a/cmd/cryptship-server/main.go b/cmd/cryptship-server/main.go index 2164997..ae7b055 100644 --- a/cmd/cryptship-server/main.go +++ b/cmd/cryptship-server/main.go @@ -31,7 +31,8 @@ func main() { keyID := flag.String("key-id", "v1", "signing key id advertised in responses") addr := flag.String("addr", ":8080", "listen address") ttl := flag.Duration("ttl", 24*time.Hour, "validity of each key answer") - revoke := flag.String("revoke", "", "comma-separated license ids to deny") + revoke := flag.String("revoke", "", "comma-separated license ids to deny (static)") + revokeFile := flag.String("revoke-file", "", "path to a live denylist (one license id per line); edit it to revoke without restarting") requireAtt := flag.Bool("require-attestation", false, "require verified TEE attestation (fails to start: no verifier is built in yet)") flag.Parse() @@ -51,11 +52,12 @@ func main() { } srv := &licenseserver.Server{ - Master: master, - SignKey: ed25519.PrivateKey(priv), - KeyID: *keyID, - TTL: *ttl, - Revoked: revoked, + Master: master, + SignKey: ed25519.PrivateKey(priv), + KeyID: *keyID, + TTL: *ttl, + Revoked: revoked, + RevokedFile: *revokeFile, } verifier, err := attestationVerifier(*requireAtt, builtinVerifier()) must(err, "--require-attestation") diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index d806d8f..9ef02a2 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -225,18 +225,26 @@ remote execution. - **Offline:** by expiry. Issue short-lived licenses and renew. A distributed denylist only helps for clients that check in. - **Online:** the key server refuses to return the binding secret for a revoked - license, so its next start fails (revoke with `cryptship-server --revoke`; - running instances keep running). An online-bound app does not start while the - server is unreachable. + license, so its next start fails. Revoke with `cryptship-server --revoke` + (static) or `--revoke-file` (a live denylist re-read per request — no restart); + running instances keep running. By default an online-bound app does not start + while the server is unreachable; `CRYPTSHIP_ONLINE_GRACE=` lets it ride out + an outage using a machine-sealed cached secret for that long (a reachable + server that says revoked still wins). +- **Signed `revocation_url` check:** the loader sends a nonce and verifies the + server's signed answer against the key ring, so an on-path attacker or captive + portal cannot forge "not revoked"; `CRYPTSHIP_REVOCATION=closed` also rejects + an unsigned "active" answer. ## Roadmap 1. **TPM provider** — seal the content key to the TPM so a copied license is useless off the physical machine, even to root. 2. **Online provider + reference license server** — IMPLEMENTED (signed, - nonce-bound replies; revocation by denylist). Still open: seat management - (the `machine` field is sent but not enforced), machine (re)activation API, - and offline grace caching of the online key. + nonce-bound replies; live `--revoke-file` denylist; signed `revocation_url` + check; `CRYPTSHIP_ONLINE_GRACE` outage caching). Still open: seat management + (the `machine` field is sent but not enforced) and a machine (re)activation + API. 3. **Cloud KMS provider** — wrap the content key with AWS/GCP/Azure KMS; unwrap gated by cloud IAM + signed instance identity. 4. **Confidential-compute provider** — SEV-SNP/TDX with remote attestation; the diff --git a/docs/HOWTO.md b/docs/HOWTO.md index 5bca8fa..34aab3a 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -205,8 +205,10 @@ cryptship-server \ --master master.key --sign vendor.key --key-id v1 \ --addr :8080 --ttl 24h ``` -- Revoke a license immediately: add `--revoke lic_abc,lic_def` (restart) — bound - apps then refuse to start. +- Revoke a license immediately: add `--revoke lic_abc,lic_def` (static, applied + at start), or `--revoke-file deny.txt` for a **live denylist** — one license id + per line; edit the file and the next request sees it, **no restart needed**. + Bound apps then refuse to start. - `--require-attestation` makes the server refuse to start: no SEV-SNP/TDX verifier is built in yet, and accepting evidence it cannot verify would give no protection. To use `attested` today, implement `attest.Verifier` (signature @@ -218,9 +220,19 @@ cryptship-server \ asks, so give the attestation server its own master key and never run a non-verifying server with that key. -The loader's revocation behaviour on a *network failure* is the operator's -choice via `CRYPTSHIP_REVOCATION`: `open` (default — run), `closed` (refuse), -`grace:` (run if the last good check is younger than ``). +A separate revocation check (`revocation_url` in the license) is **signed**: the +loader sends a nonce and verifies the server's signed answer against the key +ring, so a captive portal or on-path attacker cannot forge "not revoked". +`CRYPTSHIP_REVOCATION=closed` additionally rejects any *unsigned* "active" answer. +The loader's behaviour on a *network failure* is the operator's choice: +`open` (default — run), `closed` (refuse), `grace:` (run if the last good +check is younger than ``). + +For the **online** binding itself, set `CRYPTSHIP_ONLINE_GRACE=` (e.g. `12h`) +to let a cached, machine-sealed secret ride out a license-server **outage** for +that long. It is off by default (every start needs the server); it never bypasses +revocation (a reachable server that says revoked still wins) and never applies to +`attested` (which must always re-attest). --- @@ -257,8 +269,9 @@ accepts both versions. | `CRYPTSHIP_PUBKEY` | `/cryptship/vendor.pub` | public key / ring | | `CRYPTSHIP_EXTRACT` | `/run/cryptship/app` | decrypt dir (put on tmpfs) | | `CRYPTSHIP_REQUIRE_TMPFS` | unset | `1` = refuse if not tmpfs | -| `CRYPTSHIP_REVOCATION` | `open` | `open` / `closed` / `grace:` | -| `CRYPTSHIP_STATE_DIR` | `/var/lib/cryptship` | revocation-grace and clock-rollback state (best effort: if it is not writable the clock check is skipped with a warning) | +| `CRYPTSHIP_REVOCATION` | `open` | `open` / `closed` / `grace:` (revocation-URL failure policy) | +| `CRYPTSHIP_ONLINE_GRACE` | unset | `` (e.g. `12h`): ride out an online license-server outage using a machine-sealed cached secret; off by default | +| `CRYPTSHIP_STATE_DIR` | `/var/lib/cryptship` | revocation-grace, online-grace, and clock-rollback state (best effort: if it is not writable those checks degrade with a warning) | ### CLI commands | Command | Purpose | diff --git a/pkg/keyprovider/attested.go b/pkg/keyprovider/attested.go index a954ade..7632a64 100644 --- a/pkg/keyprovider/attested.go +++ b/pkg/keyprovider/attested.go @@ -49,7 +49,7 @@ func (a Attested) ContentKey(ctx context.Context, lic *license.License) ([]byte, } return fetchAndUnwrap(ctx, a.Keys, a.Client, lic, func(nonce []byte) ([]byte, error) { return a.Attester.Evidence(ctx, online.AttestationNonce(lic.Claims.LicenseID, nonce)) - }) + }, nil) // attested never uses the outage grace cache — it must always re-attest } // noTEE is the default attester on hosts without confidential-compute hardware. diff --git a/pkg/keyprovider/grace_test.go b/pkg/keyprovider/grace_test.go new file mode 100644 index 0000000..b9a23a3 --- /dev/null +++ b/pkg/keyprovider/grace_test.go @@ -0,0 +1,84 @@ +package keyprovider + +import ( + "bytes" + "context" + "crypto/ed25519" + "crypto/rand" + "net/http/httptest" + "testing" + "time" + + "github.com/AI2TH/cryptship/pkg/crypto" + "github.com/AI2TH/cryptship/pkg/license" + "github.com/AI2TH/cryptship/pkg/licenseserver" +) + +// TestOnlineGraceRidesOutOutage: after one successful fetch, an unreachable +// server is survived within the grace window; without grace it fails. +func TestOnlineGraceRidesOutOutage(t *testing.T) { + pub, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + master := make([]byte, 32) + if _, err := rand.Read(master); err != nil { + t.Fatal(err) + } + contentKey, _ := crypto.RandomKey() + srv := &licenseserver.Server{Master: master, SignKey: priv, KeyID: "v1", Revoked: map[string]bool{}} + ts := httptest.NewServer(srv.Handler()) + lic := serverBoundLicense(t, priv, master, contentKey, license.BindOnline, ts.URL) + ring := license.KeyRing{"v1": pub} + dir := t.TempDir() + + o := Online{Keys: ring, Client: ts.Client(), CacheDir: dir, Grace: time.Hour} + got, err := o.ContentKey(context.Background(), lic) + if err != nil || !bytes.Equal(got, contentKey) { + t.Fatalf("first fetch: err=%v", err) + } + + ts.Close() // server now unreachable + + got2, err := o.ContentKey(context.Background(), lic) + if err != nil { + t.Fatalf("grace should ride out the outage: %v", err) + } + if !bytes.Equal(got2, contentKey) { + t.Fatalf("grace content key mismatch") + } + + // Without grace configured, the same outage is fatal. + if _, err := (Online{Keys: ring, Client: ts.Client()}).ContentKey(context.Background(), lic); err == nil { + t.Fatal("no grace: outage should fail") + } +} + +// TestOnlineGraceExpires: a cache older than the window is not used. +func TestOnlineGraceExpires(t *testing.T) { + pub, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + master := make([]byte, 32) + if _, err := rand.Read(master); err != nil { + t.Fatal(err) + } + contentKey, _ := crypto.RandomKey() + srv := &licenseserver.Server{Master: master, SignKey: priv, KeyID: "v1", Revoked: map[string]bool{}} + ts := httptest.NewServer(srv.Handler()) + lic := serverBoundLicense(t, priv, master, contentKey, license.BindOnline, ts.URL) + ring := license.KeyRing{"v1": pub} + dir := t.TempDir() + + // Prime the cache with a 1ns window, then let it lapse. + o := Online{Keys: ring, Client: ts.Client(), CacheDir: dir, Grace: time.Nanosecond} + if _, err := o.ContentKey(context.Background(), lic); err != nil { + t.Fatalf("prime: %v", err) + } + ts.Close() + time.Sleep(2 * time.Millisecond) + if _, err := o.ContentKey(context.Background(), lic); err == nil { + t.Fatal("stale cache should not satisfy an outage") + } +} diff --git a/pkg/keyprovider/online.go b/pkg/keyprovider/online.go index 3ab6f89..7e1eb1b 100644 --- a/pkg/keyprovider/online.go +++ b/pkg/keyprovider/online.go @@ -10,6 +10,9 @@ import ( "fmt" "io" "net/http" + "net/url" + "os" + "path/filepath" "strings" "time" @@ -29,9 +32,16 @@ type HTTPClient interface { // unwraps exactly like Offline. The license carries no secret: revocation is // the server declining; the response is signed and echoes a nonce so a proxy // cannot forge or replay it. +// +// If CacheDir and Grace are both set, a successful fetch is cached — the secret +// sealed under a machine-bound key — so a later server OUTAGE can be ridden out +// for up to Grace. Grace applies to online binding only; attested never uses it +// (it must always re-attest). type Online struct { - Keys license.KeyRing - Client HTTPClient + Keys license.KeyRing + Client HTTPClient + CacheDir string // where to seal the grace cache (empty = disabled) + Grace time.Duration // how long a cached secret may ride out an outage } // Name implements Provider. @@ -42,13 +52,23 @@ func (Online) Handles(p license.BindingPolicy) bool { return p == license.BindOn // ContentKey implements Provider. func (o Online) ContentKey(ctx context.Context, lic *license.License) ([]byte, error) { - return fetchAndUnwrap(ctx, o.Keys, o.Client, lic, nil) + var g *graceConfig + if o.CacheDir != "" && o.Grace > 0 { + g = &graceConfig{dir: o.CacheDir, window: o.Grace} + } + return fetchAndUnwrap(ctx, o.Keys, o.Client, lic, nil, g) +} + +// graceConfig configures the outage cache (online only). +type graceConfig struct { + dir string + window time.Duration } // fetchAndUnwrap runs the request / verify / unwrap flow shared by the online // and attested providers. evidence is nil for online; for attested it returns -// evidence bound to the request nonce. -func fetchAndUnwrap(ctx context.Context, keys license.KeyRing, client HTTPClient, lic *license.License, evidence func(nonce []byte) ([]byte, error)) ([]byte, error) { +// evidence bound to the request nonce. grace is non-nil only for online. +func fetchAndUnwrap(ctx context.Context, keys license.KeyRing, client HTTPClient, lic *license.License, evidence func(nonce []byte) ([]byte, error), grace *graceConfig) ([]byte, error) { c := lic.Claims if c.Binding.Server == "" { return nil, errors.New("online: license has no binding.server") @@ -80,6 +100,13 @@ func fetchAndUnwrap(ctx context.Context, keys license.KeyRing, client HTTPClient resp, err := client.Do(req) if err != nil { + // Server unreachable: ride out the outage with a cached secret, if any. + if grace != nil { + if key, gerr := graceUnwrap(grace, c); gerr == nil { + fmt.Fprintln(os.Stderr, "cryptship: license server unreachable, using grace cache:", err) + return key, nil + } + } return nil, fmt.Errorf("online: %w", err) } defer resp.Body.Close() @@ -113,6 +140,104 @@ func fetchAndUnwrap(ctx context.Context, keys license.KeyRing, client HTTPClient if len(pub) != ed25519.PublicKeySize || !ed25519.Verify(pub, online.ResponseSigningInput(kr), kr.Sig) { return nil, errors.New("online: bad response signature") } + if grace != nil { + graceStore(grace, c, kr.Secret, kr.NotAfter) // best effort + } defer crypto.Wipe(kr.Secret) return Unwrap(c, kr.Secret) } + +// --- outage grace cache --- + +const graceAAD = "cryptship/online-grace/v1" + +type graceRecord struct { + Sealed []byte `json:"sealed"` // AES-256-GCM(secret) under the machine KEK + CachedAt int64 `json:"cached_at"` // unix seconds + NotAfter int64 `json:"not_after"` // server-stated validity (informational) +} + +// graceKEK derives the key that seals the cached secret. It binds to the machine +// fingerprint when one is readable (so the cache cannot be copied to another +// machine); otherwise it falls back to a random key stored in the state dir, so +// grace still works (bound to this install rather than the machine). Best effort. +func graceKEK(dir, licenseID string) ([]byte, error) { + material, err := graceMaterial(dir) + if err != nil { + return nil, err + } + return crypto.DeriveKEK(material, []byte("online-grace|"+licenseID), []byte(graceAAD)) +} + +func graceMaterial(dir string) ([]byte, error) { + if id, err := machine.ID(); err == nil && id != "" { + return []byte("machine:" + id), nil + } + keyPath := filepath.Join(dir, "online-grace.key") + if b, err := os.ReadFile(keyPath); err == nil && len(b) >= 32 { + return b, nil + } + k := make([]byte, 32) + if _, err := rand.Read(k); err != nil { + return nil, err + } + if err := os.MkdirAll(dir, 0o700); err != nil { + return nil, err + } + if err := os.WriteFile(keyPath, k, 0o600); err != nil { + return nil, err + } + return k, nil +} + +func gracePath(dir, licenseID string) string { + return filepath.Join(dir, "online-grace-"+url.PathEscape(licenseID)) +} + +func graceStore(g *graceConfig, c license.Claims, secret []byte, serverNotAfter int64) { + kek, err := graceKEK(g.dir, c.LicenseID) + if err != nil { + return + } + defer crypto.Wipe(kek) + sealed, err := crypto.Seal(kek, secret, []byte(graceAAD+"|"+c.LicenseID)) + if err != nil { + return + } + rec, err := json.Marshal(graceRecord{Sealed: sealed, CachedAt: time.Now().Unix(), NotAfter: serverNotAfter}) + if err != nil { + return + } + if err := os.MkdirAll(g.dir, 0o700); err != nil { + return + } + _ = os.WriteFile(gracePath(g.dir, c.LicenseID), rec, 0o600) +} + +func graceUnwrap(g *graceConfig, c license.Claims) ([]byte, error) { + b, err := os.ReadFile(gracePath(g.dir, c.LicenseID)) + if err != nil { + return nil, err + } + var rec graceRecord + if err := json.Unmarshal(b, &rec); err != nil { + return nil, err + } + if rec.CachedAt > time.Now().Unix()+license.ClockSkew { + return nil, errors.New("grace cache: cached in the future (clock rollback)") + } + if time.Since(time.Unix(rec.CachedAt, 0)) > g.window { + return nil, errors.New("grace cache: older than the grace window") + } + kek, err := graceKEK(g.dir, c.LicenseID) + if err != nil { + return nil, err + } + defer crypto.Wipe(kek) + secret, err := crypto.Open(kek, rec.Sealed, []byte(graceAAD+"|"+c.LicenseID)) + if err != nil { + return nil, err + } + defer crypto.Wipe(secret) + return Unwrap(c, secret) +} diff --git a/pkg/licenseserver/revocation_test.go b/pkg/licenseserver/revocation_test.go new file mode 100644 index 0000000..845b4c6 --- /dev/null +++ b/pkg/licenseserver/revocation_test.go @@ -0,0 +1,104 @@ +package licenseserver + +import ( + "bytes" + "crypto/ed25519" + "crypto/rand" + "encoding/hex" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/AI2TH/cryptship/pkg/online" +) + +func newTestServer(t *testing.T) (*Server, ed25519.PublicKey) { + t.Helper() + pub, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + master := make([]byte, 32) + if _, err := rand.Read(master); err != nil { + t.Fatal(err) + } + return &Server{Master: master, SignKey: priv, KeyID: "v1", Revoked: map[string]bool{}}, pub +} + +// TestRevokedFileLiveReload: editing the denylist file revokes/restores a +// license without restarting the server. +func TestRevokedFileLiveReload(t *testing.T) { + srv, _ := newTestServer(t) + srv.RevokedFile = filepath.Join(t.TempDir(), "deny.txt") + ts := httptest.NewServer(srv.Handler()) + defer ts.Close() + + keyStatus := func(id string) int { + resp, err := http.Post(ts.URL+"/v1/key", "application/json", + strings.NewReader(`{"license_id":"`+id+`","nonce":"AAAAAAAAAAAAAAAAAAAAAA=="}`)) + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + return resp.StatusCode + } + + if code := keyStatus("lic_x"); code != http.StatusOK { + t.Fatalf("before revoke: got %d, want 200", code) + } + if err := os.WriteFile(srv.RevokedFile, []byte("lic_x\n"), 0o600); err != nil { + t.Fatal(err) + } + if code := keyStatus("lic_x"); code != http.StatusGone { + t.Fatalf("after revoke-file write: got %d, want 410", code) + } + if err := os.WriteFile(srv.RevokedFile, []byte("# cleared\n"), 0o600); err != nil { + t.Fatal(err) + } + if code := keyStatus("lic_x"); code != http.StatusOK { + t.Fatalf("after revoke-file clear: got %d, want 200", code) + } +} + +// TestSignedCheckResponse: /v1/check with a nonce returns a signed answer whose +// Revoked flag the loader can trust. +func TestSignedCheckResponse(t *testing.T) { + srv, pub := newTestServer(t) + srv.Revoked["lic_bad"] = true + ts := httptest.NewServer(srv.Handler()) + defer ts.Close() + + check := func(id string) online.CheckResponse { + nonce := make([]byte, 16) + if _, err := rand.Read(nonce); err != nil { + t.Fatal(err) + } + resp, err := http.Get(ts.URL + "/v1/check?license_id=" + id + "&nonce=" + hex.EncodeToString(nonce)) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + var cr online.CheckResponse + if err := json.NewDecoder(resp.Body).Decode(&cr); err != nil { + t.Fatal(err) + } + if !bytes.Equal(cr.Nonce, nonce) { + t.Fatalf("%s: nonce not echoed", id) + } + if !ed25519.Verify(pub, online.CheckSigningInput(cr), cr.Sig) { + t.Fatalf("%s: bad signature", id) + } + return cr + } + + if check("lic_ok").Revoked { + t.Fatal("lic_ok reported revoked") + } + if !check("lic_bad").Revoked { + t.Fatal("lic_bad not reported revoked") + } +} diff --git a/pkg/licenseserver/server.go b/pkg/licenseserver/server.go index ab37564..369145e 100644 --- a/pkg/licenseserver/server.go +++ b/pkg/licenseserver/server.go @@ -5,9 +5,14 @@ package licenseserver import ( + "bufio" "crypto/ed25519" + "encoding/hex" "encoding/json" "net/http" + "os" + "strings" + "sync" "time" "github.com/AI2TH/cryptship/pkg/attest" @@ -21,13 +26,22 @@ type Server struct { SignKey ed25519.PrivateKey // signs responses KeyID string // recorded as signing_key_id TTL time.Duration // validity of each answer (default 24h) - Revoked map[string]bool // license_id -> revoked + Revoked map[string]bool // static denylist: license_id -> revoked + // RevokedFile, when set, is an additional denylist re-read on each request + // (one license id per line; blank lines and # comments ignored). Editing it + // revokes or restores a license WITHOUT restarting the server. + RevokedFile string // Verifier, when set, must accept the request's attestation evidence for // online.AttestationNonce(license_id, nonce) before a secret is released. - // Nil means attestation is not required: the server cannot tell an - // attested license from an online one, so a server without a Verifier - // releases attested-license secrets to anyone who asks. + // Nil means attestation is not required: the server cannot tell an attested + // license from an online one, so a server without a Verifier releases + // attested-license secrets to anyone who asks. Verifier attest.Verifier + + mu sync.Mutex + fileSet map[string]bool + fileMod time.Time + fileSize int64 } func (s *Server) ttl() time.Duration { @@ -37,6 +51,40 @@ func (s *Server) ttl() time.Duration { return s.TTL } +// isRevoked reports whether a license id is denied, by the static map or the +// live-reloaded RevokedFile. The file is re-read only when its mtime or size +// changes. +func (s *Server) isRevoked(id string) bool { + if s.Revoked[id] { + return true + } + if s.RevokedFile == "" { + return false + } + s.mu.Lock() + defer s.mu.Unlock() + fi, err := os.Stat(s.RevokedFile) + if err != nil { + s.fileSet = nil // missing/unreadable: only the static map applies + return false + } + if s.fileSet == nil || !fi.ModTime().Equal(s.fileMod) || fi.Size() != s.fileSize { + set := map[string]bool{} + if f, err := os.Open(s.RevokedFile); err == nil { + sc := bufio.NewScanner(f) + for sc.Scan() { + line := strings.TrimSpace(sc.Text()) + if line != "" && !strings.HasPrefix(line, "#") { + set[line] = true + } + } + f.Close() + } + s.fileSet, s.fileMod, s.fileSize = set, fi.ModTime(), fi.Size() + } + return s.fileSet[id] +} + // Handler exposes POST /v1/key and GET /v1/check. func (s *Server) Handler() http.Handler { mux := http.NewServeMux() @@ -55,7 +103,7 @@ func (s *Server) handleKey(w http.ResponseWriter, r *http.Request) { http.Error(w, "bad request", http.StatusBadRequest) return } - if s.Revoked[req.LicenseID] { + if s.isRevoked(req.LicenseID) { http.Error(w, "revoked", http.StatusGone) return } @@ -82,10 +130,36 @@ func (s *Server) handleKey(w http.ResponseWriter, r *http.Request) { _ = json.NewEncoder(w).Encode(resp) } +// handleCheck answers a revocation check. With a ?nonce= it returns a SIGNED +// online.CheckResponse (200) that the loader verifies, so a captive portal or +// on-path attacker cannot forge "not revoked". Without a nonce it keeps the +// legacy unsigned behaviour (410 revoked / 200 active) for generic clients. func (s *Server) handleCheck(w http.ResponseWriter, r *http.Request) { - if s.Revoked[r.URL.Query().Get("license_id")] { - http.Error(w, "revoked", http.StatusGone) + id := r.URL.Query().Get("license_id") + revoked := s.isRevoked(id) + + nonceHex := r.URL.Query().Get("nonce") + if nonceHex == "" { + if revoked { + http.Error(w, "revoked", http.StatusGone) + return + } + w.WriteHeader(http.StatusOK) + return + } + nonce, err := hex.DecodeString(nonceHex) + if err != nil { + http.Error(w, "bad nonce", http.StatusBadRequest) return } - w.WriteHeader(http.StatusOK) + resp := online.CheckResponse{ + LicenseID: id, + Nonce: nonce, + Revoked: revoked, + NotAfter: time.Now().Add(s.ttl()).Unix(), + SigningKeyID: s.KeyID, + } + resp.Sig = ed25519.Sign(s.SignKey, online.CheckSigningInput(resp)) + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(resp) } diff --git a/pkg/online/protocol.go b/pkg/online/protocol.go index 6bb822f..0db50e7 100644 --- a/pkg/online/protocol.go +++ b/pkg/online/protocol.go @@ -52,6 +52,34 @@ func AttestationNonce(licenseID string, nonce []byte) []byte { return h.Sum(nil) } +// CheckResponse is the signed answer to a revocation check (GET /v1/check with a +// nonce). Signing the answer stops an on-path attacker or captive portal from +// forging "not revoked": the loader verifies Sig against the vendor key ring and +// that Nonce echoes the one it sent. +type CheckResponse struct { + LicenseID string `json:"license_id"` + Nonce []byte `json:"nonce"` + Revoked bool `json:"revoked"` + NotAfter int64 `json:"not_after"` // how long this answer may be trusted + SigningKeyID string `json:"signing_key_id"` + Sig []byte `json:"sig"` +} + +// CheckSigningInput is the fixed byte layout the server signs and the loader +// verifies for a revocation check. +func CheckSigningInput(r CheckResponse) []byte { + b := []byte("cryptship/revocation-check/v1\x00") + b = append(b, r.LicenseID...) + b = append(b, 0) + b = append(b, r.Nonce...) + if r.Revoked { + b = append(b, 1) + } else { + b = append(b, 0) + } + return binary.BigEndian.AppendUint64(b, uint64(r.NotAfter)) +} + // ResponseSigningInput is the fixed byte layout the server signs and the loader // verifies. func ResponseSigningInput(r KeyResponse) []byte {