From f8c298e2886e73a6f784961eb733c26ed728b2d5 Mon Sep 17 00:00:00 2001 From: Kalvin Nathan <73115920+skalvinnathan@users.noreply.github.com> Date: Sun, 15 Nov 2026 23:43:11 +0530 Subject: [PATCH] fix: harden online grace cache, live revocation freshness, and review nits From a full end-to-end code review (three independent reviewers): Security / correctness: - grace cache: store the content key (not the per-license secret); authenticate cached_at/not_after in the AEAD AAD and enforce both plus the window. - cryptship-server re-reads --revoke-file every request (no mtime/size cache that could miss a same-length edit); warns once if it becomes unreadable; wipes the per-license secret after signing. - revocation grace timer refreshes only on a signed answer. - bind signing_key_id into the signed response/check inputs. - loader: drop the extract-marker file (recognise the dir by the manifest) to avoid an O_EXCL collision with payload contents. - cryptship: propagate crypto/rand errors when generating ids. Docs / hygiene: - add SECURITY.md, CONTRIBUTING.md, CHANGELOG.md; link from README. - README: go install targets cryptship + cryptship-server only; roadmap fixed. - HOWTO: fingerprint is Linux-only; document the cryptship_devfp dev hatch and the "-- " default. - ARCHITECTURE: honest grace trade-off. Tests: grace timestamp-tamper rejection, same-length revoke-file swap. --- CHANGELOG.md | 49 ++++++++++++++++++++++ CONTRIBUTING.md | 52 +++++++++++++++++++++++ README.md | 29 ++++++++----- SECURITY.md | 45 ++++++++++++++++++++ cmd/cryptship-loader/main.go | 25 ++++++----- cmd/cryptship-loader/main_test.go | 20 +++------ cmd/cryptship/main.go | 19 ++++++--- docs/ARCHITECTURE.md | 10 ++++- docs/HOWTO.md | 13 +++++- pkg/keyprovider/grace_tamper_test.go | 63 ++++++++++++++++++++++++++++ pkg/keyprovider/online.go | 54 +++++++++++++++++------- pkg/licenseserver/revocation_test.go | 34 +++++++++++++++ pkg/licenseserver/server.go | 54 +++++++++++++----------- pkg/online/protocol.go | 4 ++ 14 files changed, 387 insertions(+), 84 deletions(-) create mode 100644 CHANGELOG.md create mode 100644 CONTRIBUTING.md create mode 100644 SECURITY.md create mode 100644 pkg/keyprovider/grace_tamper_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..568c011 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,49 @@ +# Changelog + +All notable changes to cryptship. Format loosely follows +[Keep a Changelog](https://keepachangelog.com/); versions are git tags / +GitHub releases. + +## [Unreleased] + +### Security / fixed (from a full code review) +- **Online grace cache reworked.** It now caches the **content key** instead of + the per-license binding secret (no portable license-wide credential), and the + `cached_at` / `not_after` timestamps are **authenticated via the AEAD** and + both enforced — editing them to widen the window now fails the open. +- **Live revocation freshness.** `cryptship-server` re-reads `--revoke-file` on + every request (was an mtime/size cache that could miss a same-length edit and + keep honouring a just-revoked license). +- **Grace timer only refreshes on a signed answer**, so an unsigned (captive + portal / on-path) "active" response can't extend `CRYPTSHIP_REVOCATION=grace`. +- Server wipes the per-license secret after signing; the signing-key id is bound + into the signed response/check inputs. +- Loader no longer writes a separate extract-marker file (removes an `O_EXCL` + collision with a payload that ships that name); it recognises its own extract + dir by the manifest instead. +- `cryptship` propagates `crypto/rand` errors when generating ids. + +### Docs / project hygiene +- Added `SECURITY.md` (private disclosure + honest scope), `CONTRIBUTING.md`, + this `CHANGELOG.md`. +- README: `go install` now targets `cryptship` + `cryptship-server` only (not the + loader); roadmap corrected (online grace is shipped). +- HOWTO: documented the Linux-only `fingerprint`, the `cryptship_devfp` / + `CRYPTSHIP_FINGERPRINT` dev hatch, and the `-- ` default. + +## [0.2.0] + +- Code-review hardening: context-bound KEK (format **v2** binds every claim; + editing any claim breaks the unwrap), archive symlink-escape fix, clock-rollback + guard, non-root example images, a layer-opacity scan that unpacks every layer. +- Online/revocation: live `--revoke-file`, **signed** `/v1/check` revocation, + `CRYPTSHIP_ONLINE_GRACE` outage caching, attestation fails closed + (`--require-attestation` without a verifier refuses to start). +- `go.mod` module path corrected to `github.com/AI2TH/cryptship`. + +## [0.1.0] + +- Initial release: AES-256-GCM payload encryption, Ed25519-signed licenses, + offline key provider (none / strict / pool machine binding), the loader, the + `cryptship` CLI, the `cryptship-server` reference broker, compile/transform + seam, container hardening, per-license watermarking, three demos, and docs. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..0eec8a9 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,52 @@ +# Contributing to cryptship + +Thanks for your interest! cryptship is an open-source (GPLv3) toolkit for +shipping encrypted, license-gated application code in container images. + +## Build and test + +The module is **Go 1.24+** and standard-library only (no third-party +dependencies). You don't need Go on your host — everything can run in a +container: + +```bash +# build + vet + race tests, exactly as CI runs them +docker run --rm -v "$PWD":/src -w /src golang:1.24 sh -c ' + gofmt -l . # must print nothing + go vet ./... + go build ./... + go build -tags cryptship_devfp ./cmd/cryptship-loader + go test -race ./...' +``` + +End-to-end demos (need Docker, e.g. colima): + +```bash +bash scripts/demo.sh # baseline +bash scripts/demo-compiled.sh # ships bytecode, not source +bash scripts/demo-online.sh # server-gated key + revocation +bash scripts/check-mermaid.sh # validates the diagrams in docs/ +``` + +The `cryptship_devfp` build tag enables the `CRYPTSHIP_FINGERPRINT` override so +you can exercise `strict`/`pool` binding without real machine ids; it is compiled +out of production builds. + +## Pull requests + +- Keep the tree **gofmt-clean** and `go vet` / `go test -race` green — CI gates on all three plus mermaid rendering. +- Add tests for behavior changes (the suite leans heavily on table/round-trip tests). +- Touching crypto, the license format, or the online/attested protocol? Say so + in the PR description and keep changes minimal and reviewable — these are + security-sensitive. Note any on-disk or wire-format change. +- One logical change per PR where practical. + +## Security + +Please report vulnerabilities privately — see [SECURITY.md](SECURITY.md). Do not +open a public issue for a security problem. + +## License + +By contributing, you agree your contributions are licensed under the project's +GPLv3 license. diff --git a/README.md b/README.md index afba1df..5ab145e 100644 --- a/README.md +++ b/README.md @@ -77,12 +77,16 @@ tamper step also run in containers. bash scripts/demo.sh ``` -To install the tools directly (Go 1.24 or later): +To install the vendor-side tools directly (Go 1.24 or later): ```bash -go install github.com/AI2TH/cryptship/cmd/...@latest +go install github.com/AI2TH/cryptship/cmd/cryptship@latest +go install github.com/AI2TH/cryptship/cmd/cryptship-server@latest ``` +(The loader, `cmd/cryptship-loader`, is built *into your image* from source — see the +Dockerfiles — so there's no need to install it on your host.) + The demo packs a tiny Python app, issues a license, builds the image, then **`docker save`s it, unpacks every layer and greps for a marker planted in the app's source** to show the source isn't there, runs it to show it decrypts and @@ -97,6 +101,7 @@ works, and finally tampers with the license to show the loader refuses it. - **[docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)** — design, threat model, license format, roadmap. - **[deploy/README.md](deploy/README.md)** — hardened docker / Kubernetes deployment. +- **[SECURITY.md](SECURITY.md)** — reporting vulnerabilities + what's in scope. **[CONTRIBUTING.md](CONTRIBUTING.md)** · **[CHANGELOG.md](CHANGELOG.md)** ## Deployment modes = key providers @@ -159,14 +164,18 @@ for the full schema and the threat model. signature over the stored bytes); context-bound KEK (format v2: editing any claim breaks the unwrap); machine binding (none / strict / pool); online key provider + reference `cryptship-server`; signing-key rotation (key ring); configurable revocation -(open / closed / grace); the compile/transform seam; loader + container -hardening; per-license watermarking; and the attested (confidential-compute) -provider behind `Attester` / `attest.Verifier` interfaces with test-only -implementations (no production verifier yet). - -**Roadmap:** a real SEV-SNP/TDX `Attester` + Trustee-style KBS integration, -TPM-sealed binding, cloud-KMS wrapping, offline grace caching for `online`, and -chunked AEAD for very large payloads. +(open / closed / grace) with **signed** revocation checks; **live `--revoke-file` +revocation** (no restart); **online outage grace** (`CRYPTSHIP_ONLINE_GRACE`, a +machine-sealed cached content key with authenticated validity); the +compile/transform seam; loader + container hardening; per-license watermarking; +and the attested (confidential-compute) provider behind `Attester` / +`attest.Verifier` interfaces with test-only implementations (no production +verifier yet). + +**Roadmap:** a real SEV-SNP/TDX `Attester` + Trustee-style KBS integration (and +the attested replay fix: server-issued challenge + ephemeral TEE key), TPM-sealed +binding, cloud-KMS wrapping, seat management, and chunked AEAD for very large +payloads. ## Crypto diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..f0b8397 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,45 @@ +# Security policy + +## Reporting a vulnerability + +Please report security issues **privately**, not as a public issue or PR. + +- Preferred: GitHub → the repository's **Security** tab → **Report a vulnerability** + (private vulnerability reporting / security advisory). +- Include: affected version or commit, a description, and ideally a minimal + reproduction (a crafted license, a sequence of commands, or a short test). + +We aim to acknowledge a report within a few days and to agree on a disclosure +timeline with you. Please give us reasonable time to fix before any public +disclosure. + +## Supported versions + +cryptship is pre-1.0 and moves fast. Fixes land on `main` and in the latest +tagged release; please verify against the latest release before reporting. + +## Scope — what is and isn't a vulnerability + +cryptship's threat model is stated plainly in the [README](README.md) and +[docs/ARCHITECTURE.md](docs/ARCHITECTURE.md). In particular, these are **known, +documented limitations, not vulnerabilities**: + +- **Host/container root extracting the running plaintext** (dumping tmpfs or + `/proc//mem`). Code that runs on hardware the attacker controls can always + be extracted; only a confidential-compute key provider (SEV-SNP/TDX, the + `attested` roadmap) or remote execution prevents this. +- **A patched loader** skipping loader-enforced policy (expiry comparison, + revocation). The crypto design makes license *forgery* and claim *tampering* + fail the unwrap; it does not stop someone from modifying the open-source loader + they run. +- **`attested` mode without a real verifier.** It ships with test-only + attestation; `cryptship-server --require-attestation` fails closed precisely so + this isn't mistaken for protection. +- **Enabling `CRYPTSHIP_ONLINE_GRACE` on an untrusted host** (documented + trade-off), and **software machine fingerprints being spoofable by root**. + +In scope and very welcome: key/secret handling bugs, signature or AEAD +verification that can be bypassed, nonce/replay/downgrade flaws, path-traversal +or extraction escapes, anything that lets an **unprivileged** in-container +attacker read the decrypted app, or any way to unwrap the content key without +legitimate license material. diff --git a/cmd/cryptship-loader/main.go b/cmd/cryptship-loader/main.go index 4e4277b..aa88fa4 100644 --- a/cmd/cryptship-loader/main.go +++ b/cmd/cryptship-loader/main.go @@ -152,11 +152,9 @@ func run(cfg config) error { return execApp(cfg, lic.Claims) } -// extractMarker is created in the extract dir before anything is extracted, -// so a later run knows the directory is cryptship's to empty. -const extractMarker = ".cryptship-extract-dir" - -// manifestName is the per-license watermark written after extraction. +// manifestName is the per-license watermark written after extraction. Its +// presence also marks the extract dir as cryptship's to empty on a later run, +// so there is no separate marker file to collide with payload contents. const manifestName = ".cryptship-manifest.json" // prepareDir empties the extract dir for a fresh extraction. It only deletes @@ -178,8 +176,8 @@ func prepareDir(dir string) error { if err != nil { return err } - if len(entries) > 0 && !hasEntry(entries, extractMarker) && !hasEntry(entries, manifestName) { - return fmt.Errorf("refusing to empty extract dir %s: it is not empty and was not created by cryptship-loader (no %s); point CRYPTSHIP_EXTRACT at an empty directory", abs, extractMarker) + if len(entries) > 0 && !hasEntry(entries, manifestName) { + return fmt.Errorf("refusing to empty extract dir %s: it is not empty and has no %s from a previous cryptship run; point CRYPTSHIP_EXTRACT at an empty directory", abs, manifestName) } // Empty the dir without removing it — it may be the tmpfs mount point. for _, e := range entries { @@ -187,10 +185,7 @@ func prepareDir(dir string) error { return fmt.Errorf("clean extract dir: %w", err) } } - if err := os.Chmod(abs, 0o700); err != nil { - return err - } - return os.WriteFile(filepath.Join(abs, extractMarker), nil, 0o400) + return os.Chmod(abs, 0o700) } func hasEntry(entries []os.DirEntry, name string) bool { @@ -285,8 +280,12 @@ func enforceRevocation(lic *license.License, ring license.KeyRing) error { 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) + // Only a SIGNED "active" answer refreshes the grace clock; an unsigned + // answer (captive portal / on-path) must not be able to extend grace. + if signed { + _ = 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" { diff --git a/cmd/cryptship-loader/main_test.go b/cmd/cryptship-loader/main_test.go index 69b8ffe..70ebde6 100644 --- a/cmd/cryptship-loader/main_test.go +++ b/cmd/cryptship-loader/main_test.go @@ -35,29 +35,21 @@ func TestPrepareDirReusesItsOwnDir(t *testing.T) { if err := prepareDir(dir); err != nil { t.Fatal(err) } + // Simulate a completed prior run: extracted files plus the manifest that + // marks the dir as cryptship's. if err := os.WriteFile(filepath.Join(dir, "old.py"), []byte("x"), 0o600); err != nil { t.Fatal(err) } - // Second run over the first run's tree: emptied and re-marked. + if err := os.WriteFile(filepath.Join(dir, manifestName), []byte("{}"), 0o400); err != nil { + t.Fatal(err) + } + // Second run over that tree: emptied because the manifest marks it as ours. if err := prepareDir(dir); err != nil { t.Fatalf("second prepareDir: %v", err) } if _, err := os.Stat(filepath.Join(dir, "old.py")); !os.IsNotExist(err) { t.Fatal("old extraction not removed") } - if _, err := os.Stat(filepath.Join(dir, extractMarker)); err != nil { - t.Fatalf("marker missing: %v", err) - } - // A dir left by an older loader (manifest, no marker) is accepted too. - if err := os.Remove(filepath.Join(dir, extractMarker)); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(dir, manifestName), []byte("{}"), 0o400); err != nil { - t.Fatal(err) - } - if err := prepareDir(dir); err != nil { - t.Fatalf("prepareDir over an older loader's dir: %v", err) - } } func TestWriteManifestDoesNotFollowSymlink(t *testing.T) { diff --git a/cmd/cryptship/main.go b/cmd/cryptship/main.go index 2b91168..6fd8723 100644 --- a/cmd/cryptship/main.go +++ b/cmd/cryptship/main.go @@ -190,7 +190,10 @@ func cmdPack(args []string) error { if err != nil { return err } - payloadID := randHex(16) + payloadID, err := randHex(16) + if err != nil { + return err + } blob, err := crypto.SealPayload(contentKey, tarBytes, payloadID) if err != nil { return err @@ -273,7 +276,11 @@ func cmdIssue(args []string) error { lid := *licID if lid == "" { - lid = "lic_" + randHex(8) + h, err := randHex(8) + if err != nil { + return err + } + lid = "lic_" + h } notAfter, err := resolveExpiry(*expires, *days) if err != nil { @@ -490,10 +497,12 @@ func tsStr(u int64) string { return time.Unix(u, 0).UTC().Format(time.RFC3339) } -func randHex(n int) string { +func randHex(n int) (string, error) { b := make([]byte, n) - _, _ = rand.Read(b) - return hex.EncodeToString(b) + if _, err := rand.Read(b); err != nil { + return "", err + } + return hex.EncodeToString(b), nil } func writeB64(path string, data []byte, mode os.FileMode) error { diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 9ef02a2..7d020c8 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -229,8 +229,14 @@ remote execution. (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). + an outage for that long. The cache holds the **content key** (not the + per-license secret), sealed to a machine/state-dir key, with `cached_at` and + the server's `not_after` **authenticated** (editing them to widen the window + fails the open) and both enforced; a reachable server that says revoked still + wins. **Trade-off (honest):** on a host the licensee controls, enabling grace + writes a sealed content key to disk, so for the window it is extractable much + like the running process already is — use it where availability matters more + than instant offline revocation, or on hosts you trust. Off by default. - **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 diff --git a/docs/HOWTO.md b/docs/HOWTO.md index 34aab3a..2e80fa4 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -78,7 +78,10 @@ ENTRYPOINT ["/cryptship-loader", "--", "python", "app.py"] ``` Everything after `--` is the command to run after decryption (the loader `cd`s -into the extracted app dir first). Run it with the decrypt dir on tmpfs: +into the extracted app dir first). If you omit `-- `, the loader runs +`./entrypoint` from the extracted tree and, if there is none, exits with +`locate command "./entrypoint": ... not found` — so always pass your command. +Run it with the decrypt dir on tmpfs: ```bash docker run --rm --tmpfs /run/cryptship your-image @@ -114,6 +117,14 @@ cryptship issue ... --binding strict --fingerprint 8af75d... ... In a container, bind-mount a stable id so the fingerprint is readable and constant: `-v /etc/machine-id:/etc/machine-id:ro`. +> **Note:** `cryptship fingerprint` reads **Linux** identifiers (`/etc/machine-id`, +> DMI) — it is meant to run on the (Linux) deploy host, and returns an error on +> macOS/Windows. To exercise strict/pool **locally without real machine ids**, +> build the loader with the dev tag and set `CRYPTSHIP_FINGERPRINT`: +> `go build -tags cryptship_devfp ./cmd/cryptship-loader` then run it with +> `-e CRYPTSHIP_FINGERPRINT=machineA`. This override is **compiled out of +> production builds**, so it can't be used to defeat binding on a real deployment. + ### pool — a set of machines Wrap to several fingerprints; any one of them decrypts. For clusters with known nodes. diff --git a/pkg/keyprovider/grace_tamper_test.go b/pkg/keyprovider/grace_tamper_test.go new file mode 100644 index 0000000..30fd403 --- /dev/null +++ b/pkg/keyprovider/grace_tamper_test.go @@ -0,0 +1,63 @@ +package keyprovider + +import ( + "context" + "crypto/ed25519" + "crypto/rand" + "encoding/json" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "testing" + "time" + + "github.com/AI2TH/cryptship/pkg/crypto" + "github.com/AI2TH/cryptship/pkg/license" + "github.com/AI2TH/cryptship/pkg/licenseserver" +) + +// TestOnlineGraceTimestampTamperRejected: the cached_at/not_after timestamps are +// authenticated via the AEAD AAD, so editing them on disk (to widen the window) +// makes the cache fail to open rather than extend grace. +func TestOnlineGraceTimestampTamperRejected(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} + if _, err := o.ContentKey(context.Background(), lic); err != nil { + t.Fatalf("prime: %v", err) + } + ts.Close() + + p := filepath.Join(dir, "online-grace-"+url.PathEscape(lic.Claims.LicenseID)) + b, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + var m map[string]any + if err := json.Unmarshal(b, &m); err != nil { + t.Fatal(err) + } + m["cached_at"] = float64(time.Now().Unix() + 5) // different from the sealed value + nb, _ := json.Marshal(m) + if err := os.WriteFile(p, nb, 0o600); err != nil { + t.Fatal(err) + } + + if _, err := o.ContentKey(context.Background(), lic); err == nil { + t.Fatal("tampered grace cached_at was accepted") + } +} diff --git a/pkg/keyprovider/online.go b/pkg/keyprovider/online.go index 7e1eb1b..7024acf 100644 --- a/pkg/keyprovider/online.go +++ b/pkg/keyprovider/online.go @@ -100,11 +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. + // Server unreachable: ride out the outage with the cached content key, 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 + } else if !errors.Is(gerr, os.ErrNotExist) { + fmt.Fprintln(os.Stderr, "cryptship: grace cache present but unusable:", gerr) } } return nil, fmt.Errorf("online: %w", err) @@ -140,11 +142,18 @@ 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") } + defer crypto.Wipe(kr.Secret) + key, err := Unwrap(c, kr.Secret) + if err != nil { + return nil, err + } if grace != nil { - graceStore(grace, c, kr.Secret, kr.NotAfter) // best effort + // Cache the content key, not the per-license secret: the content key is + // per build and already lives in the running app's memory, so caching it + // adds no portable license-wide credential. + graceStore(grace, c, key, kr.NotAfter) // best effort } - defer crypto.Wipe(kr.Secret) - return Unwrap(c, kr.Secret) + return key, nil } // --- outage grace cache --- @@ -152,9 +161,15 @@ func fetchAndUnwrap(ctx context.Context, keys license.KeyRing, client HTTPClient 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) + Sealed []byte `json:"sealed"` // AES-256-GCM(content key); AAD binds cached_at+not_after + CachedAt int64 `json:"cached_at"` // unix seconds (authenticated via AAD) + NotAfter int64 `json:"not_after"` // server-stated validity (authenticated and enforced) +} + +// graceAD binds the timestamps into the AEAD, so editing cached_at/not_after in +// the on-disk JSON (to extend the window) makes the open fail. +func graceAD(licenseID string, cachedAt, notAfter int64) []byte { + return []byte(fmt.Sprintf("%s|%s|%d|%d", graceAAD, licenseID, cachedAt, notAfter)) } // graceKEK derives the key that seals the cached secret. It binds to the machine @@ -194,17 +209,18 @@ 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) { +func graceStore(g *graceConfig, c license.Claims, contentKey []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)) + cachedAt := time.Now().Unix() + sealed, err := crypto.Seal(kek, contentKey, graceAD(c.LicenseID, cachedAt, serverNotAfter)) if err != nil { return } - rec, err := json.Marshal(graceRecord{Sealed: sealed, CachedAt: time.Now().Unix(), NotAfter: serverNotAfter}) + rec, err := json.Marshal(graceRecord{Sealed: sealed, CachedAt: cachedAt, NotAfter: serverNotAfter}) if err != nil { return } @@ -214,6 +230,9 @@ func graceStore(g *graceConfig, c license.Claims, secret []byte, serverNotAfter _ = os.WriteFile(gracePath(g.dir, c.LicenseID), rec, 0o600) } +// graceUnwrap returns the cached content key if the cache is present, within the +// local window AND the server-stated NotAfter, not clock-rolled-back, and its +// authenticated timestamps are intact. func graceUnwrap(g *graceConfig, c license.Claims) ([]byte, error) { b, err := os.ReadFile(gracePath(g.dir, c.LicenseID)) if err != nil { @@ -223,21 +242,26 @@ func graceUnwrap(g *graceConfig, c license.Claims) ([]byte, error) { if err := json.Unmarshal(b, &rec); err != nil { return nil, err } - if rec.CachedAt > time.Now().Unix()+license.ClockSkew { + now := time.Now().Unix() + if rec.CachedAt > now+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") } + if rec.NotAfter != 0 && now > rec.NotAfter { + return nil, errors.New("grace cache: past the server-stated validity") + } 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)) + // Open also authenticates CachedAt/NotAfter via the AAD: editing them to + // widen the window makes this fail. + contentKey, err := crypto.Open(kek, rec.Sealed, graceAD(c.LicenseID, rec.CachedAt, rec.NotAfter)) if err != nil { - return nil, err + return nil, fmt.Errorf("grace cache: %w (tampered, or a different machine)", err) } - defer crypto.Wipe(secret) - return Unwrap(c, secret) + return contentKey, nil } diff --git a/pkg/licenseserver/revocation_test.go b/pkg/licenseserver/revocation_test.go index 845b4c6..c229a5a 100644 --- a/pkg/licenseserver/revocation_test.go +++ b/pkg/licenseserver/revocation_test.go @@ -64,6 +64,40 @@ func TestRevokedFileLiveReload(t *testing.T) { } } +// TestRevokedFileSameLengthSwap: a same-byte-length edit to the denylist is seen +// (the file is re-read every request, so no mtime/size staleness). +func TestRevokedFileSameLengthSwap(t *testing.T) { + srv, _ := newTestServer(t) + srv.RevokedFile = filepath.Join(t.TempDir(), "deny.txt") + ts := httptest.NewServer(srv.Handler()) + defer ts.Close() + post := 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 err := os.WriteFile(srv.RevokedFile, []byte("lic_aaaaaaaa\n"), 0o600); err != nil { + t.Fatal(err) + } + if post("lic_aaaaaaaa") != http.StatusGone { + t.Fatal("A should be revoked") + } + // Same byte length (13 bytes) — must still be observed. + if err := os.WriteFile(srv.RevokedFile, []byte("lic_bbbbbbbb\n"), 0o600); err != nil { + t.Fatal(err) + } + if post("lic_aaaaaaaa") != http.StatusOK { + t.Fatal("A should be active after the swap") + } + if post("lic_bbbbbbbb") != http.StatusGone { + t.Fatal("B should be revoked after the swap") + } +} + // TestSignedCheckResponse: /v1/check with a nonce returns a signed answer whose // Revoked flag the loader can trust. func TestSignedCheckResponse(t *testing.T) { diff --git a/pkg/licenseserver/server.go b/pkg/licenseserver/server.go index 369145e..cb81ba3 100644 --- a/pkg/licenseserver/server.go +++ b/pkg/licenseserver/server.go @@ -9,6 +9,7 @@ import ( "crypto/ed25519" "encoding/hex" "encoding/json" + "fmt" "net/http" "os" "strings" @@ -16,6 +17,7 @@ import ( "time" "github.com/AI2TH/cryptship/pkg/attest" + "github.com/AI2TH/cryptship/pkg/crypto" "github.com/AI2TH/cryptship/pkg/online" ) @@ -38,10 +40,8 @@ type Server struct { // attested-license secrets to anyone who asks. Verifier attest.Verifier - mu sync.Mutex - fileSet map[string]bool - fileMod time.Time - fileSize int64 + mu sync.Mutex + denyWarned bool // warn once if RevokedFile becomes unreadable } func (s *Server) ttl() time.Duration { @@ -52,8 +52,9 @@ func (s *Server) ttl() time.Duration { } // 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. +// live RevokedFile. The file is re-read on EVERY call (it is tiny): this is a +// security control, so freshness beats caching — a stale cache could keep +// honouring a just-revoked license (e.g. on a coarse-mtime filesystem). func (s *Server) isRevoked(id string) bool { if s.Revoked[id] { return true @@ -61,28 +62,32 @@ func (s *Server) isRevoked(id string) bool { if s.RevokedFile == "" { return false } - s.mu.Lock() - defer s.mu.Unlock() - fi, err := os.Stat(s.RevokedFile) + f, err := os.Open(s.RevokedFile) if err != nil { - s.fileSet = nil // missing/unreadable: only the static map applies - return false + s.warnDenyUnreadable(err) + return false // file-based revocation unavailable; the static map still applies } - 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() + defer f.Close() + sc := bufio.NewScanner(f) + for sc.Scan() { + line := strings.TrimSpace(sc.Text()) + if line == "" || strings.HasPrefix(line, "#") { + continue } - s.fileSet, s.fileMod, s.fileSize = set, fi.ModTime(), fi.Size() + if line == id { + return true + } + } + return false +} + +func (s *Server) warnDenyUnreadable(err error) { + s.mu.Lock() + defer s.mu.Unlock() + if !s.denyWarned { + fmt.Fprintf(os.Stderr, "cryptship-server: WARNING: revoke-file unreadable, file-based revocation disabled: %v\n", err) + s.denyWarned = true } - return s.fileSet[id] } // Handler exposes POST /v1/key and GET /v1/check. @@ -118,6 +123,7 @@ func (s *Server) handleKey(w http.ResponseWriter, r *http.Request) { http.Error(w, "server error", http.StatusInternalServerError) return } + defer crypto.Wipe(secret) resp := online.KeyResponse{ LicenseID: req.LicenseID, Nonce: req.Nonce, diff --git a/pkg/online/protocol.go b/pkg/online/protocol.go index 0db50e7..892efe6 100644 --- a/pkg/online/protocol.go +++ b/pkg/online/protocol.go @@ -71,6 +71,8 @@ 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.SigningKeyID...) + b = append(b, 0) b = append(b, r.Nonce...) if r.Revoked { b = append(b, 1) @@ -86,6 +88,8 @@ func ResponseSigningInput(r KeyResponse) []byte { b := []byte("cryptship/online-resp/v1\x00") b = append(b, r.LicenseID...) b = append(b, 0) + b = append(b, r.SigningKeyID...) + b = append(b, 0) b = append(b, r.Nonce...) b = append(b, r.Secret...) return binary.BigEndian.AppendUint64(b, uint64(r.NotAfter))