diff --git a/README.md b/README.md index 347e8e0..afba1df 100644 --- a/README.md +++ b/README.md @@ -49,29 +49,44 @@ content_key = unwrap(license.wrapped_key, KEK) plaintext = aead_open(payload.enc, content_key) # wrong key => AEAD tag fails ``` -Run on an unbound machine, or edit a bound claim (license and customer id, -product, payload id, binding policy, issue and expiry dates), and the unwrap -fails. Two checks remain ordinary code in the loader: the **signature** and the -**expiry** check. Patch those out and an *unedited* expired license still unwraps -on its own machine, so for enforced expiry use the `online` provider. Claims -outside the KEK context (edition, entitlements, `revocation_url`) are protected -only by the signature. With binding `none`, the license itself carries the key -material: treat it like a secret. +Run on an unbound machine, or edit a bound claim, and the unwrap fails. +Licenses issued now are format v2, which binds a hash of **every** claim into +the KEK (everything except the wrapped keys themselves and, for binding `none`, +the unbound secret), so removing `revocation_url` or adding an entitlement +breaks the unwrap even in a loader with the signature check patched out. Older +v1 licenses still load; their KEK covers only license and customer id, product, +payload id, binding policy, issue and expiry dates, and their other claims are +protected only by the signature. + +Two checks remain ordinary code in the loader: the **signature** and the +**expiry** check. Patch those out and an *unedited* expired license still +unwraps on its own machine, so for enforced expiry use the `online` provider. +The loader also refuses to start when the clock is more than 24 hours behind +the latest start it recorded for an expiring license (sealed in +`CRYPTSHIP_STATE_DIR`), but deleting that state resets the check: it stops a +casual clock rollback, not a determined one. With binding `none`, the license +itself carries the key material: treat it like a secret. ## Quickstart -Requires a working `docker` (e.g. [colima](https://github.com/abiosoft/colima) -on macOS) and `python3` (used by the demo's tamper step). The tools compile in a -Go container. +Requires only a working `docker` (e.g. [colima](https://github.com/abiosoft/colima) +on macOS). The tools compile in a Go container, and the layer scan and the +tamper step also run in containers. ```bash bash scripts/demo.sh ``` +To install the tools directly (Go 1.24 or later): + +```bash +go install github.com/AI2TH/cryptship/cmd/...@latest +``` + The demo packs a tiny Python app, issues a license, builds the image, then -**`docker save`s it, unpacks it and greps the result** to show the source isn't there, -runs it to show it decrypts and works, and finally tampers with the license to -show the loader refuses it. +**`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 +works, and finally tampers with the license to show the loader refuses it. ## Documentation @@ -92,13 +107,16 @@ acquired**. That is a single pluggable interface (`pkg/keyprovider`): |---|---|---|---| | **Air-gapped** | `offline` | machine fingerprint, or none | expiry only | | **On-prem / cloud** | `online` | per-license secret held by your server | **real** — the server declines | -| **Confidential** | `attested` | SEV-SNP/TDX attestation gates the key | planned: interface + mock only today | +| **Confidential** | `attested` | SEV-SNP/TDX attestation gates the key | planned: interfaces + test-only verifier today | The loader, license format, crypto, and app are identical across all modes — only the key provider differs. `offline` (none/strict/pool) and `online` are built and tested; `online` uses the reference `cryptship-server` (a stateless key broker). -`attested` is built behind an `Attester` interface with a mock for tests — real -SEV-SNP/TDX quote generation needs confidential-compute hardware (see +`attested` is built behind an `Attester` interface (loader) and an +`attest.Verifier` interface (server), each with a test-only implementation. There +is no production verifier yet, so `cryptship-server --require-attestation` +refuses to start rather than accept evidence it cannot check. Real SEV-SNP/TDX +quote generation needs confidential-compute hardware (see [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md)). ## Hardening & anti-extraction @@ -138,12 +156,13 @@ for the full schema and the threat model. ## Status **Built & tested:** AES-256-GCM payload encryption; Ed25519 licenses (detached -signature over the stored bytes); context-bound KEK (editing a bound claim breaks +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 an `Attester` interface with a mock key broker. +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 diff --git a/cmd/cryptship-loader/clock.go b/cmd/cryptship-loader/clock.go new file mode 100644 index 0000000..452051d --- /dev/null +++ b/cmd/cryptship-loader/clock.go @@ -0,0 +1,105 @@ +package main + +import ( + "crypto/hkdf" + "crypto/sha256" + "encoding/binary" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "time" + + "github.com/AI2TH/cryptship/pkg/crypto" + "github.com/AI2TH/cryptship/pkg/license" +) + +// clockTolerance is how far the system clock may fall behind the latest time +// the loader has recorded for a license before it refuses to start. It is +// generous so an NTP correction or a restored VM snapshot does not lock a +// customer out. +const clockTolerance = 24 * time.Hour + +const clockStateInfo = "cryptship/clock-state/v1" + +// checkClock is a best-effort clock-rollback check for licenses that expire. +// It keeps the latest start time seen for the license in the state dir, +// sealed (AES-GCM) under a key derived from the content key, so the file +// cannot be edited to an earlier time without the key. If the clock is now +// more than clockTolerance behind that time, the loader refuses to start. +// +// Limits, by design: deleting the state file (or running with a fresh state +// dir) resets the check, and a state dir that cannot be written disables it +// with a warning. It raises the bar against casually setting the clock back +// to keep an expired license running; for enforced expiry use the online +// provider. +func checkClock(dir string, c license.Claims, contentKey []byte, now time.Time) error { + if c.NotAfter == 0 { + return nil // nothing expires, nothing to protect + } + key, err := hkdf.Key(sha256.New, contentKey, []byte(c.LicenseID), clockStateInfo, crypto.KeySize) + if err != nil { + return err + } + defer crypto.Wipe(key) + aad := []byte(clockStateInfo + "\x00" + c.LicenseID) + path := filepath.Join(dir, "clock-"+escapeID(c.LicenseID)) + + latest := now.Unix() + switch blob, err := os.ReadFile(path); { + case err == nil: + pt, oerr := crypto.Open(key, blob, aad) + if oerr != nil || len(pt) != 8 { + warnf("clock state %s is not valid for this license and build; starting it again", path) + break + } + last := int64(binary.BigEndian.Uint64(pt)) + if now.Unix() < last-int64(clockTolerance/time.Second) { + return fmt.Errorf("system clock (%s) is more than %s behind the latest start recorded for license %s (%s); refusing to start. Correct the clock; the record is %s", + now.UTC().Format(time.RFC3339), clockTolerance, c.LicenseID, time.Unix(last, 0).UTC().Format(time.RFC3339), path) + } + if last > latest { + latest = last + } + case errors.Is(err, fs.ErrNotExist): + default: + warnf("clock-rollback check: cannot read %s: %v", path, err) + } + + var b [8]byte + binary.BigEndian.PutUint64(b[:], uint64(latest)) + sealed, err := crypto.Seal(key, b[:], aad) + if err != nil { + return err + } + if err := writeFileAtomic(path, sealed); err != nil { + warnf("clock-rollback check disabled: cannot write %s: %v", path, err) + } + return nil +} + +// writeFileAtomic writes via a temp file and rename, so a crash never leaves +// a truncated state file. +func writeFileAtomic(path string, data []byte) error { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err + } + tmp, err := os.CreateTemp(filepath.Dir(path), ".tmp-"+filepath.Base(path)+"-*") + if err != nil { + return err + } + defer os.Remove(tmp.Name()) + if _, err := tmp.Write(data); err != nil { + tmp.Close() + return err + } + if err := tmp.Close(); err != nil { + return err + } + return os.Rename(tmp.Name(), path) +} + +func warnf(format string, args ...any) { + fmt.Fprintf(os.Stderr, "cryptship-loader: WARNING: "+format+"\n", args...) +} diff --git a/cmd/cryptship-loader/clock_test.go b/cmd/cryptship-loader/clock_test.go new file mode 100644 index 0000000..105fa4f --- /dev/null +++ b/cmd/cryptship-loader/clock_test.go @@ -0,0 +1,87 @@ +package main + +import ( + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "github.com/AI2TH/cryptship/pkg/crypto" + "github.com/AI2TH/cryptship/pkg/license" +) + +func TestCheckClockDetectsRollback(t *testing.T) { + dir := t.TempDir() + key, _ := crypto.RandomKey() + now := time.Now() + c := license.Claims{LicenseID: "lic_clock", NotAfter: now.Add(30 * 24 * time.Hour).Unix()} + + if err := checkClock(dir, c, key, now); err != nil { + t.Fatalf("first start: %v", err) + } + // Small step back (NTP correction): allowed. + if err := checkClock(dir, c, key, now.Add(-time.Hour)); err != nil { + t.Fatalf("1h back: %v", err) + } + // The record keeps the latest time, not the last one. + if err := checkClock(dir, c, key, now.Add(-clockTolerance-time.Hour)); err == nil || !strings.Contains(err.Error(), "behind") { + t.Fatalf("rollback past tolerance: err = %v", err) + } + // Moving forward is fine and raises the record. + later := now.Add(10 * 24 * time.Hour) + if err := checkClock(dir, c, key, later); err != nil { + t.Fatal(err) + } + if err := checkClock(dir, c, key, now); err == nil { + t.Fatal("rollback below the raised record accepted") + } +} + +func TestCheckClockStateIsSealed(t *testing.T) { + dir := t.TempDir() + key, _ := crypto.RandomKey() + now := time.Now() + c := license.Claims{LicenseID: "lic_seal", NotAfter: now.Add(time.Hour).Unix()} + if err := checkClock(dir, c, key, now.Add(48*time.Hour)); err != nil { + t.Fatal(err) + } + path := filepath.Join(dir, "clock-lic_seal") + blob, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(blob), strconv.FormatInt(now.Add(48*time.Hour).Unix(), 10)) { + t.Fatal("state stored in clear") + } + // Another license (or build) cannot read or reuse the record. + other := license.Claims{LicenseID: "lic_other", NotAfter: c.NotAfter} + if err := os.WriteFile(filepath.Join(dir, "clock-lic_other"), blob, 0o600); err != nil { + t.Fatal(err) + } + if err := checkClock(dir, other, key, now); err != nil { + t.Fatalf("a record copied from another license must be ignored, got %v", err) + } + // Licenses without expiry are not checked and leave no state. + if err := checkClock(dir, license.Claims{LicenseID: "lic_forever"}, key, now); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(dir, "clock-lic_forever")); !os.IsNotExist(err) { + t.Fatal("state written for a license without expiry") + } +} + +func TestCheckClockUnwritableStateDirDoesNotBlock(t *testing.T) { + // A state dir under a regular file cannot be created, even by root. + file := filepath.Join(t.TempDir(), "not-a-dir") + if err := os.WriteFile(file, nil, 0o600); err != nil { + t.Fatal(err) + } + key, _ := crypto.RandomKey() + now := time.Now() + c := license.Claims{LicenseID: "lic_ro", NotAfter: now.Add(time.Hour).Unix()} + if err := checkClock(filepath.Join(file, "state"), c, key, now); err != nil { + t.Fatalf("unwritable state dir must not stop the loader: %v", err) + } +} diff --git a/cmd/cryptship-loader/main.go b/cmd/cryptship-loader/main.go index 5979dbd..eb8faf5 100644 --- a/cmd/cryptship-loader/main.go +++ b/cmd/cryptship-loader/main.go @@ -9,6 +9,7 @@ package main import ( "context" + "encoding/json" "fmt" "io" "net/http" @@ -21,10 +22,10 @@ import ( "syscall" "time" - "github.com/cryptship/cryptship/pkg/archive" - "github.com/cryptship/cryptship/pkg/crypto" - "github.com/cryptship/cryptship/pkg/keyprovider" - "github.com/cryptship/cryptship/pkg/license" + "github.com/AI2TH/cryptship/pkg/archive" + "github.com/AI2TH/cryptship/pkg/crypto" + "github.com/AI2TH/cryptship/pkg/keyprovider" + "github.com/AI2TH/cryptship/pkg/license" ) type config struct { @@ -111,6 +112,11 @@ func run(cfg config) error { } defer crypto.Wipe(contentKey) + // 3b. Refuse a clock set back to keep an expiring license alive. + if err := checkClock(stateDir(), lic.Claims, contentKey, time.Now()); err != nil { + return err + } + // 4. Decrypt the payload (AEAD bound to the signed payload id). blob, err := os.ReadFile(cfg.payloadPath) if err != nil { @@ -132,12 +138,25 @@ func run(cfg config) error { return fmt.Errorf("extract payload: %w", err) } crypto.Wipe(tarBytes) - writeManifest(cfg.extractDir, lic.Claims) + if err := writeManifest(cfg.extractDir, lic.Claims); err != nil { + fmt.Fprintln(os.Stderr, "cryptship-loader: WARNING: manifest not written:", err) + } // 6. Hand off to the real application. 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. +const manifestName = ".cryptship-manifest.json" + +// prepareDir empties the extract dir for a fresh extraction. It only deletes +// the contents of a directory that is empty or that an earlier run marked as +// an extract dir, so a mistyped CRYPTSHIP_EXTRACT (say, a home directory) +// fails instead of being wiped. func prepareDir(dir string) error { abs, err := filepath.Abs(dir) if err != nil { @@ -153,13 +172,28 @@ 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) + } // Empty the dir without removing it — it may be the tmpfs mount point. for _, e := range entries { if err := os.RemoveAll(filepath.Join(abs, e.Name())); err != nil { return fmt.Errorf("clean extract dir: %w", err) } } - return os.Chmod(abs, 0o700) + if err := os.Chmod(abs, 0o700); err != nil { + return err + } + return os.WriteFile(filepath.Join(abs, extractMarker), nil, 0o400) +} + +func hasEntry(entries []os.DirEntry, name string) bool { + for _, e := range entries { + if e.Name() == name { + return true + } + } + return false } func execApp(cfg config, c license.Claims) error { @@ -188,13 +222,43 @@ func execApp(cfg config, c license.Claims) error { } // writeManifest drops a per-license marker into the extracted tree so a leaked -// running instance names its licensee. Traceability aid, not prevention. -func writeManifest(dir string, c license.Claims) { - m := fmt.Sprintf(`{"license_id":%q,"customer":%q,"product":%q,"payload_id":%q,"started_at":%d}`+"\n", - c.LicenseID, c.CustomerID, c.Product, c.PayloadID, time.Now().Unix()) - _ = os.WriteFile(filepath.Join(dir, ".cryptship-manifest.json"), []byte(m), 0o400) +// running instance names its licensee. Traceability aid, not prevention. It +// is created with O_EXCL, so it never follows or overwrites a path the +// payload put there. +func writeManifest(dir string, c license.Claims) error { + m, err := json.Marshal(struct { + LicenseID string `json:"license_id"` + Customer string `json:"customer"` + Product string `json:"product"` + PayloadID string `json:"payload_id"` + StartedAt int64 `json:"started_at"` + }{c.LicenseID, c.CustomerID, c.Product, c.PayloadID, time.Now().Unix()}) + if err != nil { + return err + } + f, err := os.OpenFile(filepath.Join(dir, manifestName), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o400) + if err != nil { + return err + } + _, err = f.Write(append(m, '\n')) + if cerr := f.Close(); err == nil { + err = cerr + } + return err +} + +// stateDir is where the loader keeps revocation-grace and clock state. +func stateDir() string { return env("CRYPTSHIP_STATE_DIR", "/var/lib/cryptship") } + +// stateFile names a per-license state file in the state dir. +func stateFile(kind, licenseID string) string { + return filepath.Join(stateDir(), kind+"-"+escapeID(licenseID)) } +// escapeID makes a license id safe as one path component: "/" is escaped, so +// an id cannot point a state file outside the state dir. +func escapeID(licenseID string) string { return url.PathEscape(licenseID) } + // enforceRevocation performs the optional revocation check and applies the // operator's failure policy (CRYPTSHIP_REVOCATION): "open" (default, run on // error), "closed" (refuse on error), "grace:" (run if a prior successful @@ -204,7 +268,7 @@ func enforceRevocation(lic *license.License) error { return nil } mode := env("CRYPTSHIP_REVOCATION", "open") - stateFile := filepath.Join(env("CRYPTSHIP_STATE_DIR", "/var/lib/cryptship"), "revocation-"+lic.Claims.LicenseID) + stateFile := stateFile("revocation", lic.Claims.LicenseID) revoked, err := checkRevocation(lic) if err == nil { @@ -221,7 +285,10 @@ func enforceRevocation(lic *license.License) error { case strings.HasPrefix(mode, "grace:"): if d, perr := time.ParseDuration(strings.TrimPrefix(mode, "grace:")); perr == nil { if b, rerr := os.ReadFile(stateFile); 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 && + last <= time.Now().Unix()+license.ClockSkew && time.Since(time.Unix(last, 0)) <= d { fmt.Fprintln(os.Stderr, "cryptship-loader: revocation check failed, within grace:", err) return nil diff --git a/cmd/cryptship-loader/main_test.go b/cmd/cryptship-loader/main_test.go new file mode 100644 index 0000000..18805ec --- /dev/null +++ b/cmd/cryptship-loader/main_test.go @@ -0,0 +1,122 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strconv" + "testing" + "time" + + "github.com/AI2TH/cryptship/pkg/license" +) + +func TestPrepareDirRefusesForeignNonEmptyDir(t *testing.T) { + dir := filepath.Join(t.TempDir(), "home", "user") + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } + precious := filepath.Join(dir, "thesis.tex") + if err := os.WriteFile(precious, []byte("x"), 0o600); err != nil { + t.Fatal(err) + } + if err := prepareDir(dir); err == nil { + t.Fatal("prepareDir emptied a directory it did not create") + } + if _, err := os.Stat(precious); err != nil { + t.Fatalf("file deleted: %v", err) + } +} + +func TestPrepareDirReusesItsOwnDir(t *testing.T) { + dir := filepath.Join(t.TempDir(), "run", "app") + // Fresh (missing) dir. + if err := prepareDir(dir); err != nil { + t.Fatal(err) + } + 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 := 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) { + dir := t.TempDir() + target := filepath.Join(dir, "victim") + if err := os.WriteFile(target, []byte("keep"), 0o600); err != nil { + t.Fatal(err) + } + if err := os.Symlink("victim", filepath.Join(dir, manifestName)); err != nil { + t.Fatal(err) + } + if err := writeManifest(dir, license.Claims{LicenseID: "l"}); err == nil { + t.Fatal("writeManifest wrote through a pre-existing symlink") + } + if b, _ := os.ReadFile(target); string(b) != "keep" { + t.Fatalf("symlink target overwritten: %q", b) + } +} + +func TestStateFileStaysInStateDir(t *testing.T) { + dir := t.TempDir() + t.Setenv("CRYPTSHIP_STATE_DIR", dir) + for _, id := range []string{"lic_1", "../../etc/x", "a/../../b", "..", "/abs"} { + p := stateFile("revocation", id) + if filepath.Dir(p) != dir { + t.Errorf("license id %q: state file %s is outside %s", id, p, dir) + } + } + if got := stateFile("revocation", "lic_abc"); got != filepath.Join(dir, "revocation-lic_abc") { + t.Errorf("plain id renamed: %s", got) + } +} + +// grace: a last-success time in the future is not "within grace". +func TestRevocationGraceIgnoresFutureTimestamp(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusServiceUnavailable) + })) + defer ts.Close() + dir := t.TempDir() + t.Setenv("CRYPTSHIP_STATE_DIR", dir) + t.Setenv("CRYPTSHIP_REVOCATION", "grace:1h") + lic := &license.License{Claims: license.Claims{LicenseID: "lic_g", RevocationURL: ts.URL}} + write := func(ts int64) { + if err := os.WriteFile(stateFile("revocation", "lic_g"), []byte(strconv.FormatInt(ts, 10)), 0o600); err != nil { + t.Fatal(err) + } + } + + write(time.Now().Add(-10 * time.Minute).Unix()) + if err := enforceRevocation(lic); 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 { + t.Fatal("old success accepted as within grace") + } + write(time.Now().Add(365 * 24 * time.Hour).Unix()) + if err := enforceRevocation(lic); 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 ed4bfbf..309a7c4 100644 --- a/cmd/cryptship-loader/providers.go +++ b/cmd/cryptship-loader/providers.go @@ -4,8 +4,8 @@ import ( "net/http" "time" - "github.com/cryptship/cryptship/pkg/keyprovider" - "github.com/cryptship/cryptship/pkg/license" + "github.com/AI2TH/cryptship/pkg/keyprovider" + "github.com/AI2TH/cryptship/pkg/license" ) // buildProviders returns the key providers the loader will try, in order. The diff --git a/cmd/cryptship-server/main.go b/cmd/cryptship-server/main.go index 732d68e..2164997 100644 --- a/cmd/cryptship-server/main.go +++ b/cmd/cryptship-server/main.go @@ -2,10 +2,12 @@ // online and attested binding modes. It derives each per-license secret from a // master secret and signs responses with the vendor key. // -// For attested mode, --require-attestation currently accepts any non-empty -// evidence — a PLACEHOLDER for real SEV-SNP/TDX quote verification, which an -// integrator plugs in (e.g. by fronting this with Confidential Containers -// Trustee or calling a verifier such as Veraison/MAA). +// For attested mode, --require-attestation fails closed: this build has no +// attestation verifier (SEV-SNP and TDX verification are not implemented yet), +// so the server refuses to start with the flag rather than release secrets +// against unverified evidence. An integrator who has a verifier implements +// attest.Verifier and sets licenseserver.Server.Verifier, or fronts the +// key broker with one (e.g. Confidential Containers Trustee). package main import ( @@ -19,7 +21,8 @@ import ( "strings" "time" - "github.com/cryptship/cryptship/pkg/licenseserver" + "github.com/AI2TH/cryptship/pkg/attest" + "github.com/AI2TH/cryptship/pkg/licenseserver" ) func main() { @@ -29,7 +32,7 @@ func main() { 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") - requireAtt := flag.Bool("require-attestation", false, "require (placeholder) attestation evidence") + requireAtt := flag.Bool("require-attestation", false, "require verified TEE attestation (fails to start: no verifier is built in yet)") flag.Parse() master, err := readB64(*masterPath) @@ -54,15 +57,9 @@ func main() { TTL: *ttl, Revoked: revoked, } - if *requireAtt { - srv.Verify = func(evidence []byte) error { - if len(evidence) == 0 { - return errors.New("missing attestation evidence") - } - // PLACEHOLDER: verify a real SEV-SNP/TDX quote here. - return nil - } - } + verifier, err := attestationVerifier(*requireAtt, builtinVerifier()) + must(err, "--require-attestation") + srv.Verifier = verifier fmt.Fprintf(os.Stderr, "cryptship-server listening on %s (attestation required: %v)\n", *addr, *requireAtt) if err := http.ListenAndServe(*addr, srv.Handler()); err != nil { @@ -70,6 +67,23 @@ func main() { } } +// builtinVerifier returns the attestation verifier compiled into this server. +// There is none yet: SEV-SNP and TDX verifiers are planned. +func builtinVerifier() attest.Verifier { return nil } + +// attestationVerifier fails closed: when attestation is required and no +// verifier is available it returns an error, never a verifier that accepts +// unverified evidence. +func attestationVerifier(require bool, v attest.Verifier) (attest.Verifier, error) { + if !require { + return nil, nil + } + if v == nil { + return nil, fmt.Errorf("%w: this build cannot verify SEV-SNP or TDX evidence, so it refuses to start rather than release secrets to unverified clients", attest.ErrNoVerifier) + } + return v, nil +} + func readB64(path string) ([]byte, error) { b, err := os.ReadFile(path) if err != nil { diff --git a/cmd/cryptship-server/main_test.go b/cmd/cryptship-server/main_test.go new file mode 100644 index 0000000..a1ebf6a --- /dev/null +++ b/cmd/cryptship-server/main_test.go @@ -0,0 +1,24 @@ +package main + +import ( + "errors" + "testing" + + "github.com/AI2TH/cryptship/pkg/attest" + "github.com/AI2TH/cryptship/pkg/attest/attesttest" +) + +func TestRequireAttestationFailsClosed(t *testing.T) { + // This build has no verifier, so --require-attestation must refuse. + if v, err := attestationVerifier(true, builtinVerifier()); !errors.Is(err, attest.ErrNoVerifier) || v != nil { + t.Fatalf("require with no verifier: v=%v err=%v, want ErrNoVerifier", v, err) + } + // Not required: no verifier, no error. + if v, err := attestationVerifier(false, nil); err != nil || v != nil { + t.Fatalf("not required: v=%v err=%v", v, err) + } + // Required with a verifier: that verifier is used. + if v, err := attestationVerifier(true, attesttest.Verifier{}); err != nil || v == nil { + t.Fatalf("require with verifier: v=%v err=%v", v, err) + } +} diff --git a/cmd/cryptship/main.go b/cmd/cryptship/main.go index ab1e4fe..2b91168 100644 --- a/cmd/cryptship/main.go +++ b/cmd/cryptship/main.go @@ -19,11 +19,11 @@ import ( "strings" "time" - "github.com/cryptship/cryptship/pkg/archive" - "github.com/cryptship/cryptship/pkg/crypto" - "github.com/cryptship/cryptship/pkg/license" - "github.com/cryptship/cryptship/pkg/machine" - "github.com/cryptship/cryptship/pkg/online" + "github.com/AI2TH/cryptship/pkg/archive" + "github.com/AI2TH/cryptship/pkg/crypto" + "github.com/AI2TH/cryptship/pkg/license" + "github.com/AI2TH/cryptship/pkg/machine" + "github.com/AI2TH/cryptship/pkg/online" ) func main() { @@ -64,7 +64,7 @@ func usage() { usage: cryptship keygen --out-priv vendor.key --out-pub vendor.pub [--key-id v1] [--force] - cryptship master-key --out master.key + cryptship master-key --out master.key [--force] cryptship fingerprint [--all] cryptship pack --in APPDIR --out payload.enc [--key-out content.key] [--transform-cmd CMD] cryptship issue --priv vendor.key --content-key content.key --meta payload.json \ @@ -109,7 +109,15 @@ func cmdKeygen(args []string) error { func cmdMasterKey(args []string) error { fs := flag.NewFlagSet("master-key", flag.ExitOnError) out := fs.String("out", "master.key", "output path for the server master secret") + force := fs.Bool("force", false, "overwrite an existing master key (every online/attested license issued under it stops working)") fs.Parse(args) + // Overwriting the master secret silently strands every license issued + // under it, so require --force as keygen does. + if !*force { + if _, err := os.Stat(*out); err == nil { + return fmt.Errorf("master-key: %s already exists; replacing it breaks every online/attested license issued with it (use --force to overwrite)", *out) + } + } k, err := crypto.RandomKey() if err != nil { return err @@ -225,6 +233,7 @@ func cmdIssue(args []string) error { masterPath := fs.String("server-master-key", "", "server master secret (online/attested), from `cryptship master-key`") revURL := fs.String("revocation-url", "", "optional revocation check URL") out := fs.String("out", "license.json", "output license path") + licVersion := fs.Int("license-version", license.FormatVersion, "license format version: 2 binds every claim into the KEK; 1 only for loaders older than v2 support") var fps stringList fs.Var(&fps, "fingerprint", "bound machine fingerprint (repeatable; strict=1, pool>=1)") var ents stringList @@ -237,6 +246,9 @@ func cmdIssue(args []string) error { if *binding == "" { return errors.New("issue: --binding is required (none|strict|pool|online|attested)") } + if *licVersion != license.FormatVersion1 && *licVersion != license.FormatVersion2 { + return fmt.Errorf("issue: --license-version must be %d or %d", license.FormatVersion1, license.FormatVersion2) + } priv, err := readB64(*privPath) if err != nil { @@ -278,8 +290,10 @@ func cmdIssue(args []string) error { } } + // Every claim must be final before wrapInto: with v2 the KEK context hashes + // all of them, so anything set after wrapping would break the unwrap. claims := license.Claims{ - Version: license.FormatVersion, + Version: *licVersion, LicenseID: lid, CustomerID: *customer, Product: *product, @@ -359,12 +373,17 @@ func wrapInto(c *license.Claims, policy license.BindingPolicy, contentKey []byte } // wrapWith derives the KEK (binding material + claims context) and appends one -// wrapped content key. +// wrapped content key. All claims covered by the context must already be set. func wrapWith(c *license.Claims, material, contentKey []byte) error { - kek, err := crypto.DeriveKEK(material, []byte(c.LicenseID), c.BindingContext()) + bctx, err := c.BindingContext() if err != nil { return err } + kek, err := crypto.DeriveKEK(material, []byte(c.LicenseID), bctx) + if err != nil { + return err + } + defer crypto.Wipe(kek) wk, err := crypto.WrapKey(kek, contentKey) if err != nil { return err @@ -373,20 +392,19 @@ func wrapWith(c *license.Claims, material, contentKey []byte) error { return nil } +// wrapPerFingerprint records every fingerprint hash first and only then wraps: +// the v2 context covers binding.fingerprint_hashes, so wrapping inside the +// same loop would give each key a different (and wrong) context. func wrapPerFingerprint(c *license.Claims, contentKey []byte, fps []string) error { for _, fp := range fps { - kek, err := crypto.DeriveKEK([]byte(fp), []byte(c.LicenseID), c.BindingContext()) - if err != nil { - return err - } - wk, err := crypto.WrapKey(kek, contentKey) - if err != nil { - return err - } - c.WrappedKeys = append(c.WrappedKeys, wk) h := sha256.Sum256([]byte(fp)) c.Binding.FingerprintHashes = append(c.Binding.FingerprintHashes, hex.EncodeToString(h[:])) } + for _, fp := range fps { + if err := wrapWith(c, []byte(fp), contentKey); err != nil { + return err + } + } return nil } @@ -408,7 +426,7 @@ func cmdInspect(args []string) error { return err } c := lic.Claims - fmt.Printf("license id: %s\n", c.LicenseID) + fmt.Printf("license id: %s (format v%d)\n", c.LicenseID, c.Version) fmt.Printf("customer: %s\n", c.CustomerID) fmt.Printf("product: %s edition=%s\n", c.Product, c.Edition) fmt.Printf("payload id: %s\n", c.PayloadID) diff --git a/cmd/cryptship/main_test.go b/cmd/cryptship/main_test.go new file mode 100644 index 0000000..5403c21 --- /dev/null +++ b/cmd/cryptship/main_test.go @@ -0,0 +1,90 @@ +package main + +import ( + "bytes" + "crypto/ed25519" + "crypto/rand" + "os" + "path/filepath" + "testing" + + "github.com/AI2TH/cryptship/pkg/crypto" + "github.com/AI2TH/cryptship/pkg/keyprovider" + "github.com/AI2TH/cryptship/pkg/license" +) + +// Each fingerprint of a pool license must unwrap the content key after a +// sign / marshal / parse round trip, for both format versions. Under v2 the +// context covers binding.fingerprint_hashes, so all hashes must be recorded +// before the first wrap. +func TestWrapIntoPoolEveryFingerprintUnwraps(t *testing.T) { + _, priv, _ := ed25519.GenerateKey(rand.Reader) + contentKey, _ := crypto.RandomKey() + fps := []string{"fp-one", "fp-two", "fp-three"} + + for _, v := range []int{license.FormatVersion1, license.FormatVersion2} { + c := license.Claims{Version: v, LicenseID: "lic_pool", CustomerID: "acme", Product: "w", PayloadID: "p", SigningKeyID: "v1"} + if err := wrapInto(&c, license.BindPool, contentKey, fps, "", nil); err != nil { + t.Fatal(err) + } + if err := c.Validate(); err != nil { + t.Fatal(err) + } + lic, err := license.Sign(priv, c) + if err != nil { + t.Fatal(err) + } + b, _ := lic.Marshal() + parsed, err := license.Parse(b) + if err != nil { + t.Fatal(err) + } + for _, fp := range fps { + got, err := keyprovider.Unwrap(parsed.Claims, []byte(fp)) + if err != nil || !bytes.Equal(got, contentKey) { + t.Fatalf("v%d fingerprint %s: err = %v", v, fp, err) + } + } + if _, err := keyprovider.Unwrap(parsed.Claims, []byte("fp-other")); err == nil { + t.Fatalf("v%d: an unlisted fingerprint unwrapped", v) + } + } +} + +func TestWrapIntoNoneAndOnline(t *testing.T) { + contentKey, _ := crypto.RandomKey() + master, _ := crypto.RandomKey() + + c := license.Claims{Version: license.FormatVersion, LicenseID: "lic_none", PayloadID: "p"} + if err := wrapInto(&c, license.BindNone, contentKey, nil, "", nil); err != nil { + t.Fatal(err) + } + if got, err := keyprovider.Unwrap(c, c.UnboundSecret); err != nil || !bytes.Equal(got, contentKey) { + t.Fatalf("none: err = %v", err) + } + + c = license.Claims{Version: license.FormatVersion, LicenseID: "lic_online", PayloadID: "p"} + if err := wrapInto(&c, license.BindOnline, contentKey, nil, "https://keys.example", master); err != nil { + t.Fatal(err) + } + if err := c.Validate(); err != nil { + t.Fatal(err) + } +} + +func TestMasterKeyRefusesOverwrite(t *testing.T) { + path := filepath.Join(t.TempDir(), "master.key") + if err := cmdMasterKey([]string{"--out", path}); err != nil { + t.Fatal(err) + } + first, _ := os.ReadFile(path) + if err := cmdMasterKey([]string{"--out", path}); err == nil { + t.Fatal("master-key overwrote an existing key without --force") + } + if again, _ := os.ReadFile(path); !bytes.Equal(first, again) { + t.Fatal("existing master key changed") + } + if err := cmdMasterKey([]string{"--out", path, "--force"}); err != nil { + t.Fatalf("--force: %v", err) + } +} diff --git a/deploy/README.md b/deploy/README.md index c100a47..f1c54d3 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -10,8 +10,9 @@ provider or remote execution does.** ```bash docker run --rm \ + --user 65532:65532 \ --read-only \ - --tmpfs /run/cryptship:rw,mode=0700 \ + --tmpfs /run/cryptship:rw,mode=0700,uid=65532,gid=65532 \ --cap-drop=ALL \ --security-opt=no-new-privileges \ --security-opt seccomp=deploy/seccomp.json \ @@ -19,16 +20,23 @@ docker run --rm \ your-cryptship-image ``` +- `--user 65532:65532` — run the loader and the app as an unprivileged user, + never root (the example Dockerfiles also set `USER 65532:65532`). - `--read-only` — root filesystem is immutable; the app may only write to the tmpfs. -- `--tmpfs /run/cryptship` — decrypted code lives in RAM, never on disk. +- `--tmpfs /run/cryptship:...,uid=65532,gid=65532` — decrypted code lives in RAM, + never on disk, in a directory only that user can enter. - `CRYPTSHIP_REQUIRE_TMPFS=1` — the loader refuses to run if the extract dir is not tmpfs. - `--cap-drop=ALL` — removes `CAP_SYS_PTRACE` etc. - `--security-opt=no-new-privileges` — no privilege escalation via setuid. - `seccomp=deploy/seccomp.json` — denies `ptrace`/`process_vm_readv`/`process_vm_writev`/`kcmp` for every process in the container. -Run as a non-root user as well (set `USER` in your image, and mount the tmpfs -writable by that uid), so a compromised app user cannot read another user's -memory. +Run as a non-root user (set `USER` in your image, pass `--user`, and mount the +tmpfs writable by that uid), so a compromised app user cannot read another +user's memory. With `--read-only`, the loader cannot persist revocation-grace or +clock-rollback state in `/var/lib/cryptship`: it warns that the clock check is +disabled, and `CRYPTSHIP_REVOCATION=grace:...` has no record to fall back on. To +keep them, mount a small writable volume owned by that uid at +`CRYPTSHIP_STATE_DIR` (e.g. `-v cryptship-state:/var/lib/cryptship`). ## Kubernetes diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index d73d5ec..d806d8f 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -32,7 +32,8 @@ pkg/crypto AES-256-GCM (Seal/Open), HKDF-SHA256 KEK derivation, key wrap pkg/license signed claims + Ed25519 sign/verify, canonical encoding pkg/machine software machine fingerprint (stable host identifiers -> hash) pkg/archive tar pack + traversal-safe untar -pkg/keyprovider Provider interface; `offline`, `online` and `attested` (mock attester) providers +pkg/keyprovider Provider interface; `offline`, `online` and `attested` providers +pkg/attest attestation Verifier interface; attesttest = test-only attester/verifier pkg/online, pkg/licenseserver online key protocol and the reference key server cmd/cryptship vendor CLI: keygen, master-key, fingerprint, pack, issue, inspect cmd/cryptship-loader image ENTRYPOINT: verify -> get key -> decrypt -> exec @@ -44,7 +45,8 @@ cmd/cryptship-server reference key server for the `online` provider ``` vendor Ed25519 signing key (secret, vendor-only) -> signs licenses content key (random, per build) -> encrypts payload.enc -KEK = HKDF(binding_material, salt = license_id) -> wraps the content key +KEK = HKDF(binding_material, salt = license_id, + info = SHA-256(binding context)) -> wraps the content key binding_material = machine fingerprint (strict / pool) = per-license secret (none) ``` @@ -58,6 +60,29 @@ KEK = HKDF(binding_material, salt = license_id) -> wraps the content key or an edited bound claim ⇒ AEAD tag failure ⇒ no plaintext. The signature and expiry are separate loader checks; `online` enforces expiry server-side. +### Binding context (`claims.v`) + +The license version selects which claims the KEK is bound to. Any other value +of `v` is refused; there is no fallback. + +| `v` | Context | Bound claims | +|---|---|---| +| 1 | `cryptship/kek-ctx/v1` NUL, then version, license id, customer id, product, payload id and policy (each NUL-terminated), issued_at and not_after (big-endian uint64) | that subset only; the rest is protected by the signature alone | +| 2 (default) | `cryptship/kek-ctx/v2` NUL, then SHA-256 of the canonical claims | every claim except `wrapped_keys` and `unbound_secret` | + +The canonical claims for v2 are the Go `encoding/json` encoding of +`license.Claims` (fields in declaration order) with `wrapped_keys` set to `null` +and `unbound_secret` omitted. The loader recomputes it from the parsed claims, +so editing `edition`, `entitlements`, `revocation_url`, `binding.server`, +`binding.max`, `binding.fingerprint_hashes`, `signing_key_id`, or `v` itself +breaks the unwrap. A golden vector in `pkg/license/context_test.go` locks the +encoding. Because `v` is inside both contexts, rewriting a v2 license as v1 +(a downgrade to the weaker context) also fails the unwrap. + +`cryptship issue` writes v2 unless `--license-version 1` is given. Loaders built +before v2 reject v2 licenses (`unsupported version`), so keep issuing v1 until +every deployed loader is updated. + ## License format Signed claims (`pkg/license.Claims`), canonically JSON-encoded, plus a detached @@ -66,7 +91,7 @@ Ed25519 signature: ```jsonc { "claims": { - "v": 1, + "v": 2, // selects the KEK binding context "license_id": "lic_ab12cd34", "customer_id": "acme-corp", "product": "widget-server", @@ -86,7 +111,9 @@ Ed25519 signature: } ``` -Field order in `Claims` is the canonical signing order and is append-only. +Field order in `Claims` is the canonical signing order and is append-only. A +field added later must be `omitempty`, or the v2 context of every existing +license changes and none of them unwrap. ## Build-time flow (vendor) @@ -111,15 +138,22 @@ image ──> loader + payload.enc + license.json + vendor.pub (no source, no unwrap one of wrapped_keys -> fail closed on no match online: fetch the per-license binding secret from the key server (signed, nonce-bound reply) -> fail closed if unreachable - attested: attester evidence gates the key (mock only today) -6. OpenPayload(content_key, payload.enc, payload_id) -> AEAD; fail closed -7. untar into CRYPTSHIP_EXTRACT (should be tmpfs) -8. exec the app (args after `--`), app becomes PID 1 + attested: verified attester evidence gates the key (no production + verifier yet; the server refuses --require-attestation) +6. clock-rollback check (licenses with not_after): refuse if now is more than + 24h behind the latest start recorded in CRYPTSHIP_STATE_DIR. The record is + sealed under a key derived from the content key; deleting it resets the + check, so it is best effort +7. OpenPayload(content_key, payload.enc, payload_id) -> AEAD; fail closed +8. untar into CRYPTSHIP_EXTRACT (should be tmpfs; only an empty dir or one an + earlier run marked is emptied first) +9. exec the app (args after `--`), app becomes PID 1 ``` Runtime config (env): `CRYPTSHIP_LICENSE`, `CRYPTSHIP_PAYLOAD`, `CRYPTSHIP_PUBKEY`, `CRYPTSHIP_EXTRACT`, `CRYPTSHIP_REVOCATION` -(open | closed | grace:), `CRYPTSHIP_STATE_DIR` (revocation state) and +(open | closed | grace:), `CRYPTSHIP_STATE_DIR` (revocation and clock +state) and `CRYPTSHIP_REQUIRE_TMPFS` (refuse to run if the extract dir is not tmpfs). Put the extract dir on tmpfs: `docker run --tmpfs /run/cryptship` or k8s `emptyDir { medium: Memory }`. @@ -135,13 +169,21 @@ Runtime config (env): `CRYPTSHIP_LICENSE`, `CRYPTSHIP_PAYLOAD`, the loader POSTs a nonce; the server returns the per-license secret (derived from a master secret via HKDF) signed with the vendor key and echoing the nonce. The loader verifies and unwraps. Revocation is immediate — the server - declines (410/403). Reference server: `cmd/cryptship-server`; demo: + declines (410 revoked; 403 attestation rejected). Reference server: `cmd/cryptship-server`; demo: `scripts/demo-online.sh`. - **attested** — like online, but the key broker releases the secret only after verifying TEE attestation evidence the loader attaches (via an `Attester`). Defends against host root **when the guest is vendor-controlled**; needs - confidential-compute hardware. Built behind an interface with a mock; a real - SEV-SNP/TDX attester + verifying KBS is the roadmap item. + confidential-compute hardware. The evidence must commit to + `online.AttestationNonce(license_id, nonce)`, so it cannot be reused for another + request nonce or license. Built behind the `Attester` (loader) and + `attest.Verifier` (server) interfaces, with test-only implementations; a real + SEV-SNP/TDX attester and verifier are the roadmap item. Until then + `cryptship-server --require-attestation` refuses to start. Known gap: the nonce + is chosen by the loader, not the server, and the secret is not encrypted to a + key held in the TEE, so a captured request with genuine evidence can be + replayed. A real deployment needs a server challenge and an ephemeral TEE key + in REPORT_DATA (as Trustee does). The software fingerprint (`pkg/machine`) derives one independent fingerprint per readable host identifier (`/etc/machine-id`, DMI UUID/serial); the loader tries diff --git a/docs/DIAGRAMS.md b/docs/DIAGRAMS.md index 37fdaf0..b70fc27 100644 --- a/docs/DIAGRAMS.md +++ b/docs/DIAGRAMS.md @@ -141,12 +141,14 @@ flowchart TD VK["vendor signing key"] -->|"signs"| LIC["license claims"] CK["content key (random, per build)"] -->|"AES-256-GCM"| ENC["payload.enc"] BM["binding material
fingerprint / server secret / unbound"] --> KEK - CTX["claims context
(license id, payload id, expiry, policy)"] --> KEK["KEK = HKDF-SHA256"] + CTX["claims context
(v2: hash of every claim)"] --> KEK["KEK = HKDF-SHA256"] KEK -->|"wraps"| WK["wrapped content key
(inside the signed license)"] ``` The content key encrypts the payload **once per build**; each license wraps that same key under a KEK that only reconstitutes with the right binding material. The -claims context in the KEK (license and customer id, product, payload id, binding -policy, issue and expiry dates) means editing any of those breaks the unwrap, even -against a patched loader. Other claims are protected by the signature alone. +claims context in the KEK means editing a claim breaks the unwrap, even against a +patched loader. For format v2 (the default) that is every claim except the +wrapped keys and the unbound secret; for v1 licenses it is only license and +customer id, product, payload id, binding policy, issue and expiry dates, and the +other claims are protected by the signature alone. diff --git a/docs/HOWTO.md b/docs/HOWTO.md index 6fffb4d..5bca8fa 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -136,8 +136,10 @@ cryptship issue ... --binding online \ Like online, but the key broker releases the secret only after verifying TEE attestation (AMD SEV-SNP / Intel TDX). This is the only mode where host root can't read the memory — **and only when you control the guest** (a locked image -it can't root into). Needs CC hardware; built behind an `Attester` interface with -a mock for testing (see ARCHITECTURE.md → roadmap). +it can't root into). Needs CC hardware and a verifier on the server; today the +loader side is an `Attester` interface and the server side an `attest.Verifier` +interface, with test-only implementations in `pkg/attest/attesttest` (see +ARCHITECTURE.md → roadmap). ```bash cryptship issue ... --binding attested \ --server https://kbs.example.com --server-master-key master.key ... @@ -205,9 +207,16 @@ cryptship-server \ ``` - Revoke a license immediately: add `--revoke lic_abc,lic_def` (restart) — bound apps then refuse to start. -- `--require-attestation` turns on the (placeholder) attestation check for the - `attested` mode; plug a real SEV-SNP/TDX verifier in here (e.g. front it with - Confidential Containers Trustee). +- `--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 + chain, `online.AttestationNonce` in REPORT_DATA, measurement allow-list) and set + `licenseserver.Server.Verifier`, or front the key broker with a verifier such as + Confidential Containers Trustee. +- The server cannot tell an `attested` license from an `online` one. A server + without a verifier releases the secret of an attested license to anyone who + 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), @@ -229,6 +238,13 @@ Issue new licenses with `--key-id v2`; the loader verifies each license with the key named by its `signing_key_id`. A single plain base64 key still works (matches any license). +### License format version + +`cryptship issue` writes format v2 licenses, which bind every claim into the +KEK. Loaders from before v2 refuse them with `unsupported version 2`. Until all +deployed loaders are updated, issue with `--license-version 1`; the new loader +accepts both versions. + --- ## 7. Reference @@ -242,7 +258,7 @@ any license). | `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` | where grace state is cached | +| `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) | ### CLI commands | Command | Purpose | diff --git a/examples/demo-python/Dockerfile b/examples/demo-python/Dockerfile index db9ecf4..5e0e28a 100644 --- a/examples/demo-python/Dockerfile +++ b/examples/demo-python/Dockerfile @@ -18,5 +18,11 @@ COPY --from=build /loader /cryptship-loader COPY examples/demo-python/_work/payload.enc /cryptship/payload.enc COPY examples/demo-python/_work/license.json /cryptship/license.json COPY examples/demo-python/_work/vendor.pub /cryptship/vendor.pub +# Run as an unprivileged user, never root. The loader decrypts into +# /run/cryptship, so mount the tmpfs writable by this uid (docker's default +# --tmpfs mode 1777 is; see deploy/README.md for a 0700 mount owned by 65532). +# /var/lib/cryptship holds revocation-grace and clock state. +RUN mkdir -p /var/lib/cryptship && chown 65532:65532 /var/lib/cryptship +USER 65532:65532 # Decrypt into tmpfs at runtime: docker run --tmpfs /run/cryptship ... ENTRYPOINT ["/cryptship-loader", "--", "python", "app.py"] diff --git a/examples/demo-python/Dockerfile.compiled b/examples/demo-python/Dockerfile.compiled index d8a2bbc..2635403 100644 --- a/examples/demo-python/Dockerfile.compiled +++ b/examples/demo-python/Dockerfile.compiled @@ -17,5 +17,11 @@ COPY --from=build /loader /cryptship-loader COPY examples/demo-python/_work_compiled/payload.enc /cryptship/payload.enc COPY examples/demo-python/_work_compiled/license.json /cryptship/license.json COPY examples/demo-python/_work_compiled/vendor.pub /cryptship/vendor.pub +# Run as an unprivileged user, never root. The loader decrypts into +# /run/cryptship, so mount the tmpfs writable by this uid (docker's default +# --tmpfs mode 1777 is; see deploy/README.md for a 0700 mount owned by 65532). +# /var/lib/cryptship holds revocation-grace and clock state. +RUN mkdir -p /var/lib/cryptship && chown 65532:65532 /var/lib/cryptship +USER 65532:65532 ENTRYPOINT ["/cryptship-loader"] CMD ["--", "python", "app.pyc"] diff --git a/examples/demo-python/Dockerfile.online b/examples/demo-python/Dockerfile.online index 7d00817..222a7bd 100644 --- a/examples/demo-python/Dockerfile.online +++ b/examples/demo-python/Dockerfile.online @@ -15,4 +15,10 @@ COPY --from=build /loader /cryptship-loader COPY examples/demo-python/_work_online/payload.enc /cryptship/payload.enc COPY examples/demo-python/_work_online/license.json /cryptship/license.json COPY examples/demo-python/_work_online/vendor.pub /cryptship/vendor.pub +# Run as an unprivileged user, never root. The loader decrypts into +# /run/cryptship, so mount the tmpfs writable by this uid (docker's default +# --tmpfs mode 1777 is; see deploy/README.md for a 0700 mount owned by 65532). +# /var/lib/cryptship holds revocation-grace and clock state. +RUN mkdir -p /var/lib/cryptship && chown 65532:65532 /var/lib/cryptship +USER 65532:65532 ENTRYPOINT ["/cryptship-loader", "--", "python", "app.py"] diff --git a/examples/demo-python/app/app.py b/examples/demo-python/app/app.py index e19c62c..665931b 100644 --- a/examples/demo-python/app/app.py +++ b/examples/demo-python/app/app.py @@ -9,6 +9,10 @@ SECRET_SAUCE = "the-answer-is-42-do-not-leak" +# A unique string scripts/demo.sh searches every image layer for. If it shows +# up anywhere in the shipped image, the source leaked. +SOURCE_MARKER = "CRYPTSHIP-DEMO-SOURCE-MARKER-6f1c9a2e" + def proprietary_algorithm(x: int) -> int: # Pretend this is valuable IP worth protecting. diff --git a/go.mod b/go.mod index 859d6ad..4582d57 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,3 @@ -module github.com/cryptship/cryptship +module github.com/AI2TH/cryptship go 1.24 diff --git a/pkg/archive/tar.go b/pkg/archive/tar.go index 79c8454..c05bffc 100644 --- a/pkg/archive/tar.go +++ b/pkg/archive/tar.go @@ -24,7 +24,9 @@ const DefaultMaxExtractBytes int64 = 2 << 30 // TarDir walks root and returns a tar archive of its contents. Regular files, // directories, and symlinks are included; modes are preserved. Paths in the -// archive are relative to root. +// archive are relative to root. Anything Untar would refuse (other file types, +// symlinks that leave root) is an error here, at pack time, rather than a +// loader failure on every customer's machine. func TarDir(root string) ([]byte, error) { var buf bytes.Buffer tw := tar.NewWriter(&buf) @@ -40,29 +42,40 @@ func TarDir(root string) ([]byte, error) { if rel == "." { return nil } + name := filepath.ToSlash(rel) var link string - if fi.Mode()&os.ModeSymlink != 0 { + switch { + case fi.Mode().IsRegular(), fi.IsDir(): + case fi.Mode()&os.ModeSymlink != 0: if link, err = os.Readlink(p); err != nil { return err } + if err := checkLinkTarget(name, link); err != nil { + return err + } + default: + return fmt.Errorf("archive: %s: unsupported file type %s (only regular files, directories and symlinks)", name, fi.Mode().Type()) } hdr, err := tar.FileInfoHeader(fi, link) if err != nil { return err } - hdr.Name = filepath.ToSlash(rel) + hdr.Name = name if err := tw.WriteHeader(hdr); err != nil { return err } if fi.Mode().IsRegular() { + // Close each file before the next: a deferred Close inside the + // walk callback would hold every file open until the walk ends. f, err := os.Open(p) if err != nil { return err } - defer f.Close() - if _, err := io.Copy(tw, f); err != nil { - return err + _, err = io.Copy(tw, f) + if cerr := f.Close(); err == nil { + err = cerr } + return err } return nil }) @@ -180,17 +193,16 @@ func mkdirAll(root *os.Root, dir string, perm os.FileMode) error { return nil } -// checkLink verifies a symlink entry stays within dest: the target must be -// relative and lexically contained, and no ancestor of the link may itself be a -// symlink (so the link cannot be redirected outside the root when created). +// checkLink verifies a symlink entry stays within dest. The target must be +// relative, and its ".." components may only come first: they climb through +// the link's own ancestors, which must be real directories (not symlinks), and +// may not climb above dest. After the first ordinary component no ".." is +// allowed, because ".." after a symlink resolves against the symlink's target, +// not lexically: with s -> ".", "s/.." is the parent of dest. Every link that +// passes this rule resolves inside dest whatever order the entries come in. func checkLink(root *os.Root, name, linkname string) error { - ln := filepath.ToSlash(linkname) - if ln == "" || path.IsAbs(ln) || filepath.IsAbs(linkname) { - return fmt.Errorf("archive: refusing absolute or empty symlink %s -> %q", name, linkname) - } - resolved := path.Clean(path.Join(path.Dir(name), ln)) - if resolved == ".." || strings.HasPrefix(resolved, "../") { - return fmt.Errorf("archive: refusing symlink escaping dest: %s -> %s", name, linkname) + if err := checkLinkTarget(name, linkname); err != nil { + return err } for d := path.Dir(name); d != "." && d != "/"; d = path.Dir(d) { fi, err := root.Lstat(d) @@ -206,3 +218,31 @@ func checkLink(root *os.Root, name, linkname string) error { } return nil } + +// checkLinkTarget is the lexical half of checkLink (see there). +func checkLinkTarget(name, linkname string) error { + ln := filepath.ToSlash(linkname) + if ln == "" || path.IsAbs(ln) || filepath.IsAbs(linkname) || strings.ContainsRune(ln, 0) { + return fmt.Errorf("archive: refusing absolute or empty symlink %s -> %q", name, linkname) + } + depth := 0 + if d := path.Dir(name); d != "." { + depth = strings.Count(d, "/") + 1 + } + up, descended := 0, false + for _, part := range strings.Split(ln, "/") { + switch part { + case "", ".": + case "..": + if descended { + return fmt.Errorf("archive: refusing symlink with \"..\" after a path component: %s -> %s", name, linkname) + } + if up++; up > depth { + return fmt.Errorf("archive: refusing symlink escaping dest: %s -> %s", name, linkname) + } + default: + descended = true + } + } + return nil +} diff --git a/pkg/archive/tar_test.go b/pkg/archive/tar_test.go index 6b7e17f..bb80cd1 100644 --- a/pkg/archive/tar_test.go +++ b/pkg/archive/tar_test.go @@ -192,3 +192,89 @@ func isUnder(p, dir string) bool { } return rel != ".." && !bytes.HasPrefix([]byte(rel), []byte(".."+string(os.PathSeparator))) } + +// A symlink target that is lexically inside dest can still resolve outside it +// when it passes through another symlink: s -> "." makes "s/.." the parent of +// dest. Both entry orders are tried, since a check that only looks at links +// that already exist is defeated by creating the inner link last. +func TestUntarRejectsChainedSymlinkEscape(t *testing.T) { + orders := map[string][]entry{ + "inner link first": { + {name: "s", typ: tar.TypeSymlink, link: "."}, + {name: "t", typ: tar.TypeSymlink, link: "s/.."}, + }, + "inner link last": { + {name: "t", typ: tar.TypeSymlink, link: "s/.."}, + {name: "s", typ: tar.TypeSymlink, link: "."}, + }, + "nested": { + {name: "d/s", typ: tar.TypeSymlink, link: ".."}, + {name: "d/t", typ: tar.TypeSymlink, link: "s/../x"}, + }, + } + for name, entries := range orders { + t.Run(name, func(t *testing.T) { + parent := t.TempDir() + dest := filepath.Join(parent, "dest") + err := Untar(buildTar(t, entries), dest) + for _, e := range entries { + p := filepath.Join(dest, filepath.FromSlash(e.name)) + if _, lerr := os.Lstat(p); lerr != nil { + continue + } + real, rerr := filepath.EvalSymlinks(p) + if rerr != nil { + continue // dangling: fine + } + destReal, _ := filepath.EvalSymlinks(dest) + if !isUnder(real, destReal) && real != destReal { + t.Errorf("SECURITY: %s resolves outside dest to %s (Untar err=%v)", e.name, real, err) + } + } + if err == nil { + t.Errorf("Untar accepted a chained-symlink escape without error") + } + }) + } +} + +// Ordinary relative links, including ones that climb out of their own +// directory, keep working. +func TestUntarAllowsContainedSymlinks(t *testing.T) { + dest := filepath.Join(t.TempDir(), "dest") + data := buildTar(t, []entry{ + {name: "lib/real.so", typ: tar.TypeReg, body: []byte("so")}, + {name: "lib/alias.so", typ: tar.TypeSymlink, link: "real.so"}, + {name: "bin/tool", typ: tar.TypeSymlink, link: "../lib/real.so"}, + {name: "bin/here", typ: tar.TypeSymlink, link: "./tool"}, + {name: "a/b/c/deep", typ: tar.TypeSymlink, link: "../../../lib/alias.so"}, + {name: "self", typ: tar.TypeSymlink, link: "."}, + }) + if err := Untar(data, dest); err != nil { + t.Fatalf("Untar: %v", err) + } + for _, p := range []string{"lib/alias.so", "bin/tool", "bin/here", "a/b/c/deep"} { + if b, err := os.ReadFile(filepath.Join(dest, p)); err != nil || string(b) != "so" { + t.Errorf("%s: %q, %v", p, b, err) + } + } +} + +// TarDir refuses, at pack time, what Untar would refuse at load time. +func TestTarDirRejectsWhatUntarRefuses(t *testing.T) { + for name, link := range map[string]string{ + "absolute": "/etc/passwd", + "escaping": "../outside", + "chained": "x/../..", + } { + t.Run(name, func(t *testing.T) { + src := t.TempDir() + if err := os.Symlink(link, filepath.Join(src, "l")); err != nil { + t.Fatal(err) + } + if _, err := TarDir(src); err == nil { + t.Fatalf("TarDir accepted symlink -> %s", link) + } + }) + } +} diff --git a/pkg/attest/attest.go b/pkg/attest/attest.go new file mode 100644 index 0000000..05b6518 --- /dev/null +++ b/pkg/attest/attest.go @@ -0,0 +1,31 @@ +// Package attest defines how a key broker checks TEE attestation evidence +// before it releases a binding secret for the attested binding mode. +// +// Only the interface lives here. cryptship does not ship a production +// verifier yet: SEV-SNP and TDX verifiers (signature chain, nonce in +// REPORT_DATA, measurement allow-list) are planned. attesttest has a +// verifier for tests that proves nothing about the runtime environment. +package attest + +import "errors" + +// Measurement is what a verifier extracted from evidence it accepted. +type Measurement struct { + // Platform names the TEE, e.g. "sev-snp" or "tdx". + Platform string + // Digest is the launch measurement that was matched against the + // verifier's allow-list. + Digest []byte +} + +// Verifier checks attestation evidence. nonce is the value the evidence must +// commit to (online.AttestationNonce of the request), so evidence made for a +// different request or license is rejected. Verify returns an error for any +// evidence it cannot fully verify; it never accepts by default. +type Verifier interface { + Verify(evidence, nonce []byte) (Measurement, error) +} + +// ErrNoVerifier is returned where attestation is required but no verifier is +// configured. +var ErrNoVerifier = errors.New("attest: no attestation verifier is configured") diff --git a/pkg/attest/attesttest/attesttest.go b/pkg/attest/attesttest/attesttest.go new file mode 100644 index 0000000..c115e70 --- /dev/null +++ b/pkg/attest/attesttest/attesttest.go @@ -0,0 +1,41 @@ +// Package attesttest provides an attester and verifier pair for tests and +// local demos. The evidence is a fixed prefix followed by the nonce: it is +// bound to the request but proves NOTHING about the runtime environment. +// Never wire these into a production server or loader. +package attesttest + +import ( + "bytes" + "context" + "errors" + + "github.com/AI2TH/cryptship/pkg/attest" +) + +const prefix = "cryptship-attesttest-evidence/v1\x00" + +// Attester produces test evidence that commits to bindData. It satisfies +// keyprovider.Attester. +type Attester struct{} + +// Name implements keyprovider.Attester. +func (Attester) Name() string { return "attesttest" } + +// Evidence implements keyprovider.Attester. +func (Attester) Evidence(_ context.Context, bindData []byte) ([]byte, error) { + return append([]byte(prefix), bindData...), nil +} + +// Verifier accepts only evidence produced by Attester for the same nonce. +type Verifier struct{} + +// Verify implements attest.Verifier. +func (Verifier) Verify(evidence, nonce []byte) (attest.Measurement, error) { + if len(nonce) == 0 { + return attest.Measurement{}, errors.New("attesttest: empty nonce") + } + if !bytes.Equal(evidence, append([]byte(prefix), nonce...)) { + return attest.Measurement{}, errors.New("attesttest: evidence does not match the nonce") + } + return attest.Measurement{Platform: "attesttest"}, nil +} diff --git a/pkg/keyprovider/attested.go b/pkg/keyprovider/attested.go index 8e74cc6..a954ade 100644 --- a/pkg/keyprovider/attested.go +++ b/pkg/keyprovider/attested.go @@ -4,13 +4,15 @@ import ( "context" "errors" - "github.com/cryptship/cryptship/pkg/license" + "github.com/AI2TH/cryptship/pkg/license" + "github.com/AI2TH/cryptship/pkg/online" ) // Attester produces TEE attestation evidence (e.g. an AMD SEV-SNP report or an // Intel TDX quote). Real implementations read /dev/sev-guest or /dev/tdx_guest -// and commit bindData (e.g. license id + an ephemeral key) into the report's -// REPORT_DATA field. ErrNoTEE is returned where no TEE is available. +// and commit bindData (online.AttestationNonce of the license id and request +// nonce) into the report's REPORT_DATA field. ErrNoTEE is returned where no +// TEE is available. pkg/attest/attesttest has a test-only implementation. type Attester interface { Name() string Evidence(ctx context.Context, bindData []byte) ([]byte, error) @@ -45,11 +47,9 @@ func (a Attested) ContentKey(ctx context.Context, lic *license.License) ([]byte, if a.Attester == nil { return nil, ErrNoTEE } - evidence, err := a.Attester.Evidence(ctx, []byte(lic.Claims.LicenseID)) - if err != nil { - return nil, err - } - return fetchAndUnwrap(ctx, a.Keys, a.Client, lic, evidence) + return fetchAndUnwrap(ctx, a.Keys, a.Client, lic, func(nonce []byte) ([]byte, error) { + return a.Attester.Evidence(ctx, online.AttestationNonce(lic.Claims.LicenseID, nonce)) + }) } // noTEE is the default attester on hosts without confidential-compute hardware. @@ -61,18 +61,3 @@ func (noTEE) Evidence(context.Context, []byte) ([]byte, error) { return nil, Err // DefaultAttester returns the attester for the current host. On non-CC hardware // it reports ErrNoTEE; swap in an SEV-SNP/TDX attester to enable attested mode. func DefaultAttester() Attester { return noTEE{} } - -// MockAttester returns fixed evidence. For tests and local demos only — it -// proves nothing about the runtime environment. -type MockAttester struct{ Token []byte } - -// Name implements Attester. -func (MockAttester) Name() string { return "mock" } - -// Evidence implements Attester. -func (m MockAttester) Evidence(context.Context, []byte) ([]byte, error) { - if len(m.Token) == 0 { - return []byte("mock-evidence"), nil - } - return m.Token, nil -} diff --git a/pkg/keyprovider/binding_test.go b/pkg/keyprovider/binding_test.go new file mode 100644 index 0000000..6555d1f --- /dev/null +++ b/pkg/keyprovider/binding_test.go @@ -0,0 +1,156 @@ +package keyprovider + +import ( + "bytes" + "context" + "crypto/ed25519" + "crypto/rand" + "encoding/json" + "errors" + "testing" + "time" + + "github.com/AI2TH/cryptship/pkg/crypto" + "github.com/AI2TH/cryptship/pkg/license" +) + +// issueNone builds and serialises a signed binding-"none" license of the given +// format version, with claims that v1 leaves outside the KEK context. +func issueNone(t *testing.T, version int, contentKey []byte) []byte { + t.Helper() + _, priv, _ := ed25519.GenerateKey(rand.Reader) + secret, _ := crypto.RandomKey() + now := time.Now().Unix() + c := license.Claims{ + Version: version, LicenseID: "lic_tamper", CustomerID: "acme", Product: "widget", + Edition: "basic", PayloadID: "build-1", Entitlements: []string{"reports"}, + IssuedAt: now, NotAfter: now + 3600, + Binding: license.Binding{Policy: license.BindNone}, + UnboundSecret: secret, + RevocationURL: "https://vendor.example/v1/check", + SigningKeyID: "v1", + } + c.WrappedKeys = [][]byte{wrapForTest(t, c, secret, contentKey)} + if err := c.Validate(); err != nil { + t.Fatal(err) + } + lic, err := license.Sign(priv, c) + if err != nil { + t.Fatal(err) + } + b, err := lic.Marshal() + if err != nil { + t.Fatal(err) + } + return b +} + +// editClaims edits the claims JSON of a serialised license, keeps the now +// invalid signature, and parses the result: what a loader with the signature +// check patched out would go on to unwrap. +func editClaims(t *testing.T, licBytes []byte, edit func(map[string]any)) *license.License { + t.Helper() + var outer map[string]json.RawMessage + if err := json.Unmarshal(licBytes, &outer); err != nil { + t.Fatal(err) + } + var claims map[string]any + if err := json.Unmarshal(outer["claims"], &claims); err != nil { + t.Fatal(err) + } + edit(claims) + raw, err := json.Marshal(claims) + if err != nil { + t.Fatal(err) + } + outer["claims"] = raw + b, err := json.Marshal(outer) + if err != nil { + t.Fatal(err) + } + lic, err := license.Parse(b) + if err != nil { + t.Fatalf("Parse edited license: %v", err) + } + return lic +} + +var signatureBypassEdits = map[string]func(map[string]any){ + "revocation_url removed": func(c map[string]any) { delete(c, "revocation_url") }, + "revocation_url changed": func(c map[string]any) { c["revocation_url"] = "http://127.0.0.1:1/ok" }, + "entitlement added": func(c map[string]any) { c["entitlements"] = []string{"reports", "admin"} }, + "entitlements removed": func(c map[string]any) { delete(c, "entitlements") }, + "edition changed": func(c map[string]any) { c["edition"] = "enterprise" }, + "signing_key_id changed": func(c map[string]any) { c["signing_key_id"] = "v9" }, + "binding.max added": func(c map[string]any) { + c["binding"].(map[string]any)["max"] = 50 + }, +} + +// Issue #1: with v2, editing a claim outside the v1 subset breaks the unwrap +// even when the signature check is bypassed. +func TestV2EditedClaimsDoNotUnwrap(t *testing.T) { + contentKey, _ := crypto.RandomKey() + b := issueNone(t, license.FormatVersion2, contentKey) + + // Unedited: unwraps. + lic := editClaims(t, b, func(map[string]any) {}) + got, err := Offline{}.ContentKey(context.Background(), lic) + if err != nil || !bytes.Equal(got, contentKey) { + t.Fatalf("unedited v2 license: key=%x err=%v", got, err) + } + + for name, edit := range signatureBypassEdits { + t.Run(name, func(t *testing.T) { + lic := editClaims(t, b, edit) + if _, err := (Offline{}).ContentKey(context.Background(), lic); !errors.Is(err, ErrNotBound) { + t.Fatalf("edited v2 license unwrapped (err = %v)", err) + } + }) + } +} + +// v1 licenses still load. The same edits still unwrap under v1: this is the +// gap v2 closes, recorded here so the behaviour is explicit. +func TestV1StillUnwrapsAndKeepsItsLimits(t *testing.T) { + contentKey, _ := crypto.RandomKey() + b := issueNone(t, license.FormatVersion1, contentKey) + + lic := editClaims(t, b, func(map[string]any) {}) + got, err := Offline{}.ContentKey(context.Background(), lic) + if err != nil || !bytes.Equal(got, contentKey) { + t.Fatalf("unedited v1 license: key=%x err=%v", got, err) + } + for name, edit := range signatureBypassEdits { + lic := editClaims(t, b, edit) + if _, err := (Offline{}).ContentKey(context.Background(), lic); err != nil { + t.Errorf("%s: v1 behaviour changed, edit now breaks the unwrap: %v", name, err) + } + } + // A v1-bound claim still breaks a v1 unwrap. + lic = editClaims(t, b, func(c map[string]any) { c["not_after"] = float64(time.Now().Unix() + 1e8) }) + if _, err := (Offline{}).ContentKey(context.Background(), lic); !errors.Is(err, ErrNotBound) { + t.Fatalf("v1 not_after edit unwrapped (err = %v)", err) + } +} + +// Changing "v" moves the license to the other context: neither a downgrade to +// the weaker v1 nor an upgrade unwraps. +func TestVersionEditDoesNotUnwrap(t *testing.T) { + contentKey, _ := crypto.RandomKey() + for _, tc := range []struct{ from, to int }{{2, 1}, {1, 2}} { + b := issueNone(t, tc.from, contentKey) + lic := editClaims(t, b, func(c map[string]any) { c["v"] = tc.to }) + if _, err := (Offline{}).ContentKey(context.Background(), lic); !errors.Is(err, ErrNotBound) { + t.Fatalf("v%d -> v%d edit unwrapped (err = %v)", tc.from, tc.to, err) + } + } +} + +// An unknown version never reaches a KEK derivation. +func TestUnwrapRejectsUnknownVersion(t *testing.T) { + c := license.Claims{Version: 7, LicenseID: "l", WrappedKeys: [][]byte{{1}}} + if _, err := Unwrap(c, []byte("material")); err == nil || errors.Is(err, ErrNotBound) { + t.Fatalf("Unwrap(v7) err = %v, want a version error", err) + } +} diff --git a/pkg/keyprovider/offline.go b/pkg/keyprovider/offline.go index d06b70c..f8950fd 100644 --- a/pkg/keyprovider/offline.go +++ b/pkg/keyprovider/offline.go @@ -5,8 +5,8 @@ import ( "errors" "fmt" - "github.com/cryptship/cryptship/pkg/license" - "github.com/cryptship/cryptship/pkg/machine" + "github.com/AI2TH/cryptship/pkg/license" + "github.com/AI2TH/cryptship/pkg/machine" ) // Offline resolves the content key with no network access, for none/strict/pool diff --git a/pkg/keyprovider/online.go b/pkg/keyprovider/online.go index c490e40..3ab6f89 100644 --- a/pkg/keyprovider/online.go +++ b/pkg/keyprovider/online.go @@ -13,10 +13,10 @@ import ( "strings" "time" - "github.com/cryptship/cryptship/pkg/crypto" - "github.com/cryptship/cryptship/pkg/license" - "github.com/cryptship/cryptship/pkg/machine" - "github.com/cryptship/cryptship/pkg/online" + "github.com/AI2TH/cryptship/pkg/crypto" + "github.com/AI2TH/cryptship/pkg/license" + "github.com/AI2TH/cryptship/pkg/machine" + "github.com/AI2TH/cryptship/pkg/online" ) // HTTPClient is the minimal client the network providers need (satisfied by @@ -46,8 +46,9 @@ func (o Online) ContentKey(ctx context.Context, lic *license.License) ([]byte, e } // fetchAndUnwrap runs the request / verify / unwrap flow shared by the online -// and attested providers. attestation is nil for online. -func fetchAndUnwrap(ctx context.Context, keys license.KeyRing, client HTTPClient, lic *license.License, attestation []byte) ([]byte, error) { +// 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) { c := lic.Claims if c.Binding.Server == "" { return nil, errors.New("online: license has no binding.server") @@ -59,8 +60,18 @@ func fetchAndUnwrap(ctx context.Context, keys license.KeyRing, client HTTPClient if _, err := rand.Read(nonce); err != nil { return nil, err } + var attestation []byte + if evidence != nil { + var err error + if attestation, err = evidence(nonce); err != nil { + return nil, err + } + } m, _ := machine.ID() - body, _ := json.Marshal(online.KeyRequest{LicenseID: c.LicenseID, Machine: m, Nonce: nonce, Attestation: attestation}) + body, err := json.Marshal(online.KeyRequest{LicenseID: c.LicenseID, Machine: m, Nonce: nonce, Attestation: attestation}) + if err != nil { + return nil, err + } req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(c.Binding.Server, "/")+"/v1/key", bytes.NewReader(body)) if err != nil { return nil, err @@ -74,8 +85,10 @@ func fetchAndUnwrap(ctx context.Context, keys license.KeyRing, client HTTPClient defer resp.Body.Close() switch resp.StatusCode { case http.StatusOK: - case http.StatusGone, http.StatusForbidden: + case http.StatusGone: return nil, ErrRevoked + case http.StatusForbidden: + return nil, ErrDenied default: return nil, fmt.Errorf("online: server returned %s", resp.Status) } diff --git a/pkg/keyprovider/provider.go b/pkg/keyprovider/provider.go index 501e0f9..b9c3806 100644 --- a/pkg/keyprovider/provider.go +++ b/pkg/keyprovider/provider.go @@ -9,8 +9,8 @@ import ( "errors" "fmt" - "github.com/cryptship/cryptship/pkg/crypto" - "github.com/cryptship/cryptship/pkg/license" + "github.com/AI2TH/cryptship/pkg/crypto" + "github.com/AI2TH/cryptship/pkg/license" ) // Provider acquires the content key for a verified license. @@ -23,8 +23,11 @@ type Provider interface { var ( // ErrNotBound means no wrapped key could be unwrapped on this machine. ErrNotBound = errors.New("keyprovider: not bound to the license") - // ErrRevoked means a server declined to release the key. + // ErrRevoked means the server reported the license revoked (410 Gone). ErrRevoked = errors.New("keyprovider: license revoked by server") + // ErrDenied means the server refused to release the key for another + // reason (403 Forbidden), such as rejected attestation evidence. + ErrDenied = errors.New("keyprovider: server refused to release the key (e.g. attestation rejected)") ) // Select returns the first provider that handles the license's binding policy. @@ -41,7 +44,11 @@ func Select(lic *license.License, providers ...Provider) (Provider, error) { // tries every wrapped key until one authenticates. A returned key is genuine // (a wrong KEK fails the AEAD tag). func Unwrap(c license.Claims, material []byte) ([]byte, error) { - kek, err := crypto.DeriveKEK(material, []byte(c.LicenseID), c.BindingContext()) + bctx, err := c.BindingContext() + if err != nil { + return nil, err + } + kek, err := crypto.DeriveKEK(material, []byte(c.LicenseID), bctx) if err != nil { return nil, err } diff --git a/pkg/keyprovider/provider_test.go b/pkg/keyprovider/provider_test.go index 388057f..6659f85 100644 --- a/pkg/keyprovider/provider_test.go +++ b/pkg/keyprovider/provider_test.go @@ -10,12 +10,32 @@ import ( "testing" "time" - "github.com/cryptship/cryptship/pkg/crypto" - "github.com/cryptship/cryptship/pkg/license" - "github.com/cryptship/cryptship/pkg/licenseserver" - "github.com/cryptship/cryptship/pkg/online" + "github.com/AI2TH/cryptship/pkg/attest/attesttest" + "github.com/AI2TH/cryptship/pkg/crypto" + "github.com/AI2TH/cryptship/pkg/license" + "github.com/AI2TH/cryptship/pkg/licenseserver" + "github.com/AI2TH/cryptship/pkg/online" ) +// wrapForTest wraps contentKey under the KEK for claims c (all claims final) +// and binding material, as `cryptship issue` does. +func wrapForTest(t *testing.T, c license.Claims, material, contentKey []byte) []byte { + t.Helper() + bctx, err := c.BindingContext() + if err != nil { + t.Fatal(err) + } + kek, err := crypto.DeriveKEK(material, []byte(c.LicenseID), bctx) + if err != nil { + t.Fatal(err) + } + wk, err := crypto.WrapKey(kek, contentKey) + if err != nil { + t.Fatal(err) + } + return wk +} + // serverBoundLicense builds a license whose content key is wrapped under the KEK // derived from the server-held binding secret (what `cryptship issue --binding // online|attested` does). @@ -37,15 +57,7 @@ func serverBoundLicense(t *testing.T, priv ed25519.PrivateKey, master, contentKe if err != nil { t.Fatal(err) } - kek, err := crypto.DeriveKEK(secret, []byte(c.LicenseID), c.BindingContext()) - if err != nil { - t.Fatal(err) - } - wk, err := crypto.WrapKey(kek, contentKey) - if err != nil { - t.Fatal(err) - } - c.WrappedKeys = [][]byte{wk} + c.WrappedKeys = [][]byte{wrapForTest(t, c, secret, contentKey)} lic, err := license.Sign(priv, c) if err != nil { t.Fatal(err) @@ -62,9 +74,7 @@ func TestOfflineNoneRoundTrip(t *testing.T) { IssuedAt: now, NotAfter: now + 3600, Binding: license.Binding{Policy: license.BindNone}, UnboundSecret: secret, } - kek, _ := crypto.DeriveKEK(secret, []byte(c.LicenseID), c.BindingContext()) - wk, _ := crypto.WrapKey(kek, contentKey) - c.WrappedKeys = [][]byte{wk} + c.WrappedKeys = [][]byte{wrapForTest(t, c, secret, contentKey)} got, err := Offline{}.ContentKey(context.Background(), &license.License{Claims: c}) if err != nil { @@ -115,12 +125,7 @@ func TestAttestedProviderRoundTrip(t *testing.T) { srv := &licenseserver.Server{ Master: master, SignKey: priv, KeyID: "v1", Revoked: map[string]bool{}, - Verify: func(e []byte) error { - if len(e) == 0 { - return errors.New("no evidence") - } - return nil - }, + Verifier: attesttest.Verifier{}, } ts := httptest.NewServer(srv.Handler()) defer ts.Close() @@ -128,8 +133,8 @@ func TestAttestedProviderRoundTrip(t *testing.T) { lic := serverBoundLicense(t, priv, master, contentKey, license.BindAttested, ts.URL) ring := license.KeyRing{"v1": pub} - // Mock attester -> KBS accepts and returns the secret. - got, err := (Attested{Keys: ring, Client: ts.Client(), Attester: MockAttester{}}).ContentKey(context.Background(), lic) + // Test attester -> KBS accepts and returns the secret. + got, err := (Attested{Keys: ring, Client: ts.Client(), Attester: attesttest.Attester{}}).ContentKey(context.Background(), lic) if err != nil { t.Fatalf("attested ContentKey: %v", err) } @@ -141,4 +146,20 @@ func TestAttestedProviderRoundTrip(t *testing.T) { if _, err := (Attested{Keys: ring, Client: ts.Client(), Attester: DefaultAttester()}).ContentKey(context.Background(), lic); !errors.Is(err, ErrNoTEE) { t.Fatalf("no-TEE: err = %v, want ErrNoTEE", err) } + + // Evidence that is not bound to this request's nonce (e.g. replayed from + // an earlier request) is refused by the server. + stale := staleAttester{bindData: online.AttestationNonce(lic.Claims.LicenseID, []byte("an-older-nonce!!"))} + if _, err := (Attested{Keys: ring, Client: ts.Client(), Attester: stale}).ContentKey(context.Background(), lic); !errors.Is(err, ErrDenied) { + t.Fatalf("evidence for another nonce: err = %v, want ErrDenied", err) + } +} + +// staleAttester returns test evidence for a fixed bindData, ignoring the +// request's. +type staleAttester struct{ bindData []byte } + +func (staleAttester) Name() string { return "stale" } +func (s staleAttester) Evidence(ctx context.Context, _ []byte) ([]byte, error) { + return attesttest.Attester{}.Evidence(ctx, s.bindData) } diff --git a/pkg/license/context_test.go b/pkg/license/context_test.go new file mode 100644 index 0000000..a17929d --- /dev/null +++ b/pkg/license/context_test.go @@ -0,0 +1,221 @@ +package license + +import ( + "bytes" + "encoding/hex" + "encoding/json" + "fmt" + "testing" +) + +// goldenClaims sets every field, so the golden vectors below lock the exact +// encoding of both context versions. +func goldenClaims(v int) Claims { + return Claims{ + Version: v, + LicenseID: "lic_golden", + CustomerID: "acme", + Product: "widget", + Edition: "enterprise", + PayloadID: "payload-golden", + Entitlements: []string{"a", "b"}, + IssuedAt: 1700000000, + NotAfter: 1800000000, + Binding: Binding{ + Policy: BindPool, Max: 2, FingerprintHashes: []string{"aa", "bb"}, + Server: "https://x", ProviderData: []byte{1, 2}, + }, + WrappedKeys: [][]byte{{9, 9}}, + UnboundSecret: []byte{7}, + RevocationURL: "https://r/check", + SigningKeyID: "v1", + } +} + +// v1Golden was computed with the BindingContext code before v2 existed. If it +// changes, every v1 license in the field stops unwrapping. +const v1Golden = "6372797074736869702f6b656b2d6374782f76310031006c69635f676f6c64656e0061636d6500776964676574007061796c6f61642d676f6c64656e00706f6f6c00000000006553f100000000006b49d200" + +// v2Golden locks the v2 encoding. If it changes, every v2 license stops +// unwrapping: see the comment on Claims before touching the struct. It is +// "cryptship/kek-ctx/v2" NUL SHA-256(v2GoldenJSON), cross-checked outside Go. +const v2Golden = "6372797074736869702f6b656b2d6374782f763200d0c627c281eee2fa7bdbc06fa202632be67eccfd793e3ce49234c074af04864b" + +const v2GoldenJSON = `{"v":2,"license_id":"lic_golden","customer_id":"acme","product":"widget","edition":"enterprise",` + + `"payload_id":"payload-golden","entitlements":["a","b"],"issued_at":1700000000,"not_after":1800000000,` + + `"binding":{"policy":"pool","max":2,"fingerprint_hashes":["aa","bb"],"server":"https://x","provider_data":"AQI="},` + + `"wrapped_keys":null,"revocation_url":"https://r/check","signing_key_id":"v1"}` + +func mustCtx(t *testing.T, c Claims) []byte { + t.Helper() + b, err := c.BindingContext() + if err != nil { + t.Fatalf("BindingContext(v%d): %v", c.Version, err) + } + return b +} + +func TestBindingContextGoldenV1(t *testing.T) { + if got := hex.EncodeToString(mustCtx(t, goldenClaims(1))); got != v1Golden { + t.Fatalf("v1 context changed:\n got %s\nwant %s", got, v1Golden) + } +} + +func TestBindingContextGoldenV2(t *testing.T) { + raw, err := canonicalClaims(goldenClaims(2)) + if err != nil { + t.Fatal(err) + } + if string(raw) != v2GoldenJSON { + t.Fatalf("canonical claims changed:\n got %s\nwant %s", raw, v2GoldenJSON) + } + if got := hex.EncodeToString(mustCtx(t, goldenClaims(2))); got != v2Golden { + t.Fatalf("v2 context changed:\n got %s\nwant %s", got, v2Golden) + } +} + +func TestBindingContextVersionSelection(t *testing.T) { + if !bytes.HasPrefix(mustCtx(t, goldenClaims(1)), []byte("cryptship/kek-ctx/v1\x00")) { + t.Fatal("v1 claims did not get the v1 context") + } + if !bytes.HasPrefix(mustCtx(t, goldenClaims(2)), []byte("cryptship/kek-ctx/v2\x00")) { + t.Fatal("v2 claims did not get the v2 context") + } + for _, v := range []int{0, -1, 3, 100} { + if _, err := goldenClaims(v).BindingContext(); err == nil { + t.Fatalf("version %d: BindingContext returned no error", v) + } + } +} + +// Every claim except wrapped_keys and unbound_secret must change the v2 +// context. The v1 context, by design, ignores most of them. +func TestBindingContextV2CoversEveryClaim(t *testing.T) { + mutations := map[string]func(*Claims){ + "v": func(c *Claims) { c.Version = 1 }, + "license_id": func(c *Claims) { c.LicenseID += "x" }, + "customer_id": func(c *Claims) { c.CustomerID += "x" }, + "product": func(c *Claims) { c.Product += "x" }, + "edition": func(c *Claims) { c.Edition = "free" }, + "edition removed": func(c *Claims) { c.Edition = "" }, + "payload_id": func(c *Claims) { c.PayloadID += "x" }, + "entitlements added": func(c *Claims) { c.Entitlements = append(c.Entitlements, "root") }, + "entitlements removed": func(c *Claims) { c.Entitlements = nil }, + "entitlements reordered": func(c *Claims) { c.Entitlements = []string{"b", "a"} }, + "issued_at": func(c *Claims) { c.IssuedAt-- }, + "not_after": func(c *Claims) { c.NotAfter++ }, + "binding.policy": func(c *Claims) { c.Binding.Policy = BindStrict }, + "binding.max": func(c *Claims) { c.Binding.Max = 100 }, + "binding.fingerprint_hashes": func(c *Claims) { c.Binding.FingerprintHashes = []string{"aa"} }, + "binding.server": func(c *Claims) { c.Binding.Server = "https://evil" }, + "binding.provider_data": func(c *Claims) { c.Binding.ProviderData = nil }, + "revocation_url changed": func(c *Claims) { c.RevocationURL = "https://evil/check" }, + "revocation_url removed": func(c *Claims) { c.RevocationURL = "" }, + "signing_key_id": func(c *Claims) { c.SigningKeyID = "v2" }, + } + base := mustCtx(t, goldenClaims(2)) + for name, mutate := range mutations { + c := goldenClaims(2) + mutate(&c) + got, err := c.BindingContext() + if err == nil && bytes.Equal(got, base) { + t.Errorf("%s: v2 context unchanged", name) + } + } + + // The fields that cannot be known before wrapping are excluded. + c := goldenClaims(2) + c.WrappedKeys = [][]byte{{1}, {2}} + c.UnboundSecret = []byte("other") + if !bytes.Equal(mustCtx(t, c), base) { + t.Fatal("wrapped_keys / unbound_secret changed the v2 context") + } +} + +// The mutation table above must name every JSON field of Claims and Binding, +// so a field added later cannot silently escape the test. +func TestBindingContextV2MutationTableIsComplete(t *testing.T) { + raw, err := json.Marshal(goldenClaims(2)) + if err != nil { + t.Fatal(err) + } + var top map[string]json.RawMessage + if err := json.Unmarshal(raw, &top); err != nil { + t.Fatal(err) + } + var bind map[string]json.RawMessage + if err := json.Unmarshal(top["binding"], &bind); err != nil { + t.Fatal(err) + } + want := map[string]bool{"wrapped_keys": true, "unbound_secret": true, "binding": true} + for _, k := range []string{"v", "license_id", "customer_id", "product", "edition", "payload_id", + "entitlements", "issued_at", "not_after", "revocation_url", "signing_key_id"} { + want[k] = true + } + for k := range top { + if !want[k] { + t.Errorf("claims field %q is not covered by TestBindingContextV2CoversEveryClaim", k) + } + } + for k := range bind { + switch k { + case "policy", "max", "fingerprint_hashes", "server", "provider_data": + default: + t.Errorf("binding field %q is not covered by TestBindingContextV2CoversEveryClaim", k) + } + } + if len(top) != len(want) { + t.Errorf("claims has %d fields, the test knows %d", len(top), len(want)) + } +} + +// canonicalClaims must not modify the caller's claims. +func TestBindingContextDoesNotMutate(t *testing.T) { + c := goldenClaims(2) + _ = mustCtx(t, c) + if len(c.WrappedKeys) != 1 || len(c.UnboundSecret) != 1 { + t.Fatal("BindingContext modified the claims") + } +} + +// Re-encoding after a JSON round trip (what the loader does) gives the same +// v2 context as at issue time, including for empty-but-present fields. +func TestBindingContextV2StableAcrossParse(t *testing.T) { + _, priv := genKey(t) + for _, c := range []Claims{goldenClaims(2), {Version: 2, LicenseID: "l", PayloadID: "p", Entitlements: []string{}, Binding: Binding{Policy: BindNone}}} { + lic, err := Sign(priv, c) + if err != nil { + t.Fatal(err) + } + b, _ := lic.Marshal() + parsed, err := Parse(b) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(mustCtx(t, c), mustCtx(t, parsed.Claims)) { + t.Fatalf("context differs after Parse for %+v", c) + } + } +} + +func TestParseVersionRange(t *testing.T) { + for v, ok := range map[int]bool{-1: false, 0: false, 1: true, 2: true, 3: false} { + raw := fmt.Sprintf(`{"claims":{"v":%d,"license_id":"l","payload_id":"p","issued_at":0,"not_after":0,"binding":{"policy":"none"},"wrapped_keys":null,"signing_key_id":""},"sig_alg":"ed25519","sig":""}`, v) + _, err := Parse([]byte(raw)) + if ok && err != nil { + t.Errorf("version %d rejected: %v", v, err) + } + if !ok && err == nil { + t.Errorf("version %d accepted", v) + } + } +} + +func TestSignRefusesWrappedKeysWithoutVersion(t *testing.T) { + _, priv := genKey(t) + c := sampleClaims() + c.Version = 0 + if _, err := Sign(priv, c); err == nil { + t.Fatal("Sign accepted wrapped keys with no version") + } +} diff --git a/pkg/license/license.go b/pkg/license/license.go index c4ff68f..3f9b724 100644 --- a/pkg/license/license.go +++ b/pkg/license/license.go @@ -7,6 +7,7 @@ package license import ( "bytes" + "crypto/sha256" "encoding/binary" "encoding/json" "errors" @@ -14,8 +15,18 @@ import ( "strconv" ) -// FormatVersion is the current license schema version. -const FormatVersion = 1 +// License format versions. The version selects the KEK binding context, so it +// is a crypto format change, not just a schema tag. +const ( + // FormatVersion1 binds a fixed subset of claims into the KEK (see + // bindingContextV1). Still accepted by the loader. + FormatVersion1 = 1 + // FormatVersion2 binds a hash of every claim except wrapped_keys and + // unbound_secret into the KEK (see bindingContextV2). + FormatVersion2 = 2 + // FormatVersion is the version new licenses are issued with. + FormatVersion = FormatVersion2 +) // ClockSkew is the tolerance (seconds) applied to issued_at so a slightly slow // client clock does not reject a fresh license. @@ -49,7 +60,10 @@ type Binding struct { ProviderData []byte `json:"provider_data,omitempty"` } -// Claims is the signed portion of a license. Field order is significant. +// Claims is the signed portion of a license. Field order is significant: the +// v2 KEK context hashes the encoding/json form of this struct, so fields must +// not be reordered or renamed, and any field added later must be `omitempty` +// (and empty in existing licenses), or every v2 license stops unwrapping. type Claims struct { Version int `json:"v"` LicenseID string `json:"license_id"` @@ -86,10 +100,27 @@ type License struct { Claims Claims `json:"-"` } -// BindingContext is the fixed, language-independent byte layout of the claims -// the KEK is bound to. Editing any of them changes the KEK, so a tampered -// license cannot unwrap the content key even if signature checks are patched. -func (c Claims) BindingContext() []byte { +// BindingContext returns the bytes the KEK is bound to, selected by the claims +// version. Editing anything the context covers changes the KEK, so a tampered +// license cannot unwrap the content key even if signature checks are patched +// out. Versions other than 1 and 2 are an error, never a fallback: the version +// is itself part of both contexts, so editing it also breaks the unwrap. +func (c Claims) BindingContext() ([]byte, error) { + switch c.Version { + case FormatVersion1: + return c.bindingContextV1(), nil + case FormatVersion2: + return c.bindingContextV2() + default: + return nil, fmt.Errorf("cryptship/license: no KEK binding context for license version %d", c.Version) + } +} + +// bindingContextV1 is the fixed, language-independent byte layout of the v1 +// bound claims: version, license id, customer id, product, payload id, binding +// policy, issued_at and not_after. Other claims are protected only by the +// signature. Kept byte-for-byte so v1 licenses keep unwrapping. +func (c Claims) bindingContextV1() []byte { var b []byte put := func(s string) { b = append(b, s...); b = append(b, 0) } put("cryptship/kek-ctx/v1") @@ -103,6 +134,30 @@ func (c Claims) BindingContext() []byte { return binary.BigEndian.AppendUint64(b, uint64(c.NotAfter)) } +// bindingContextV2 binds every claim: "cryptship/kek-ctx/v2" NUL followed by +// SHA-256 of the canonical claims. Only the two fields that cannot be known +// before wrapping are left out: wrapped_keys (the output of the wrap) and +// unbound_secret (the binding material itself, for binding "none"). +func (c Claims) bindingContextV2() ([]byte, error) { + raw, err := canonicalClaims(c) + if err != nil { + return nil, err + } + sum := sha256.Sum256(raw) + b := append([]byte("cryptship/kek-ctx/v2"), 0) + return append(b, sum[:]...), nil +} + +// canonicalClaims is the encoding hashed into the v2 context: encoding/json of +// Claims (fields in declaration order, no maps, so the output is deterministic) +// with wrapped_keys set to null and unbound_secret omitted. c is a copy, so the +// caller's claims are not modified. +func canonicalClaims(c Claims) ([]byte, error) { + c.WrappedKeys = nil + c.UnboundSecret = nil + return json.Marshal(c) +} + // Expired reports whether the license is outside its validity window at now. func (c Claims) Expired(now int64) bool { if c.NotAfter != 0 && now > c.NotAfter { @@ -123,6 +178,9 @@ func (c Claims) Validate() error { if c.PayloadID == "" { return errors.New("cryptship/license: empty payload_id") } + if c.Version != FormatVersion1 && c.Version != FormatVersion2 { + return fmt.Errorf("cryptship/license: unsupported version %d", c.Version) + } if c.NotAfter != 0 && c.NotAfter <= c.IssuedAt { return errors.New("cryptship/license: not_after <= issued_at") } @@ -171,8 +229,8 @@ func Parse(b []byte) (*License, error) { if l.Claims.Version == 0 { return nil, errors.New("cryptship/license: missing version") } - if l.Claims.Version > FormatVersion { - return nil, fmt.Errorf("cryptship/license: version %d newer than supported %d", l.Claims.Version, FormatVersion) + if l.Claims.Version < FormatVersion1 || l.Claims.Version > FormatVersion { + return nil, fmt.Errorf("cryptship/license: unsupported version %d (this build supports %d to %d)", l.Claims.Version, FormatVersion1, FormatVersion) } return &l, nil } diff --git a/pkg/license/sign.go b/pkg/license/sign.go index a537f7c..01c258b 100644 --- a/pkg/license/sign.go +++ b/pkg/license/sign.go @@ -32,11 +32,19 @@ func signingInput(alg string, raw []byte) []byte { // Sign signs the claims and returns a License whose ClaimsRaw is the exact // signed bytes (a detached signature over opaque bytes, JWS-style). +// +// Set c.Version before deriving the KEK: the version selects the binding +// context, so wrapped keys made under one version do not unwrap under another. +// A zero version is filled in with FormatVersion only for claims that carry +// no wrapped keys yet. func Sign(priv ed25519.PrivateKey, c Claims) (*License, error) { if len(priv) != ed25519.PrivateKeySize { return nil, ErrKeySize } if c.Version == 0 { + if len(c.WrappedKeys) != 0 { + return nil, errors.New("cryptship/license: claims have wrapped keys but no version; set Version before wrapping") + } c.Version = FormatVersion } raw, err := json.Marshal(c) diff --git a/pkg/licenseserver/server.go b/pkg/licenseserver/server.go index d0a6807..ab37564 100644 --- a/pkg/licenseserver/server.go +++ b/pkg/licenseserver/server.go @@ -10,7 +10,8 @@ import ( "net/http" "time" - "github.com/cryptship/cryptship/pkg/online" + "github.com/AI2TH/cryptship/pkg/attest" + "github.com/AI2TH/cryptship/pkg/online" ) // Server answers key requests. Master and SignKey are secret; SignKey's public @@ -21,9 +22,12 @@ type Server struct { KeyID string // recorded as signing_key_id TTL time.Duration // validity of each answer (default 24h) Revoked map[string]bool // license_id -> revoked - // Verify, when set, must return nil for the request's attestation evidence - // before a secret is released (attested mode). Nil = attestation not required. - Verify func(evidence []byte) error + // 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. + Verifier attest.Verifier } func (s *Server) ttl() time.Duration { @@ -55,8 +59,8 @@ func (s *Server) handleKey(w http.ResponseWriter, r *http.Request) { http.Error(w, "revoked", http.StatusGone) return } - if s.Verify != nil { - if err := s.Verify(req.Attestation); err != nil { + if s.Verifier != nil { + if _, err := s.Verifier.Verify(req.Attestation, online.AttestationNonce(req.LicenseID, req.Nonce)); err != nil { http.Error(w, "attestation rejected", http.StatusForbidden) return } diff --git a/pkg/licenseserver/server_test.go b/pkg/licenseserver/server_test.go new file mode 100644 index 0000000..7ad306a --- /dev/null +++ b/pkg/licenseserver/server_test.go @@ -0,0 +1,66 @@ +package licenseserver + +import ( + "bytes" + "crypto/ed25519" + "crypto/rand" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/AI2TH/cryptship/pkg/attest/attesttest" + "github.com/AI2TH/cryptship/pkg/online" +) + +func newServer(t *testing.T) *Server { + t.Helper() + _, priv, _ := ed25519.GenerateKey(rand.Reader) + master := make([]byte, 32) + _, _ = rand.Read(master) + return &Server{Master: master, SignKey: priv, KeyID: "v1", Revoked: map[string]bool{"lic_revoked": true}} +} + +func post(t *testing.T, h http.Handler, req online.KeyRequest) int { + t.Helper() + b, _ := json.Marshal(req) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/v1/key", bytes.NewReader(b))) + return rec.Code +} + +func TestKeyRequiresVerifiedAttestation(t *testing.T) { + s := newServer(t) + s.Verifier = attesttest.Verifier{} + h := s.Handler() + nonce := []byte("0123456789abcdef") + good, _ := attesttest.Attester{}.Evidence(t.Context(), online.AttestationNonce("lic_1", nonce)) + + cases := []struct { + name string + req online.KeyRequest + want int + }{ + {"valid evidence", online.KeyRequest{LicenseID: "lic_1", Nonce: nonce, Attestation: good}, http.StatusOK}, + {"no evidence", online.KeyRequest{LicenseID: "lic_1", Nonce: nonce}, http.StatusForbidden}, + {"arbitrary evidence", online.KeyRequest{LicenseID: "lic_1", Nonce: nonce, Attestation: []byte("anything")}, http.StatusForbidden}, + {"other nonce", online.KeyRequest{LicenseID: "lic_1", Nonce: []byte("fedcba9876543210"), Attestation: good}, http.StatusForbidden}, + {"other license", online.KeyRequest{LicenseID: "lic_2", Nonce: nonce, Attestation: good}, http.StatusForbidden}, + {"revoked", online.KeyRequest{LicenseID: "lic_revoked", Nonce: nonce, Attestation: good}, http.StatusGone}, + } + for _, tc := range cases { + if got := post(t, h, tc.req); got != tc.want { + t.Errorf("%s: status %d, want %d", tc.name, got, tc.want) + } + } +} + +func TestKeyWithoutVerifier(t *testing.T) { + h := newServer(t).Handler() + if got := post(t, h, online.KeyRequest{LicenseID: "lic_1", Nonce: []byte("0123456789abcdef")}); got != http.StatusOK { + t.Fatalf("status %d, want 200", got) + } + if got := post(t, h, online.KeyRequest{LicenseID: "lic_revoked", Nonce: []byte("0123456789abcdef")}); got != http.StatusGone { + t.Fatalf("revoked: status %d, want 410", got) + } +} diff --git a/pkg/online/protocol.go b/pkg/online/protocol.go index 9fed4b6..6bb822f 100644 --- a/pkg/online/protocol.go +++ b/pkg/online/protocol.go @@ -38,6 +38,20 @@ func DeriveSecret(master []byte, licenseID string) ([]byte, error) { return hkdf.Key(sha256.New, master, []byte(licenseID), "cryptship/online-secret/v1", SecretSize) } +// AttestationNonce is the value attested-mode evidence must commit to (for +// example in the SEV-SNP / TDX REPORT_DATA field): a hash of the license id and +// the request nonce, so evidence made for one request or license does not +// verify for another. The loader's attester and the server's verifier both +// compute it. +func AttestationNonce(licenseID string, nonce []byte) []byte { + h := sha256.New() + h.Write([]byte("cryptship/attestation-nonce/v1\x00")) + h.Write([]byte(licenseID)) + h.Write([]byte{0}) + h.Write(nonce) + return h.Sum(nil) +} + // ResponseSigningInput is the fixed byte layout the server signs and the loader // verifies. func ResponseSigningInput(r KeyResponse) []byte { diff --git a/scripts/check-image-opacity.sh b/scripts/check-image-opacity.sh new file mode 100644 index 0000000..d467840 --- /dev/null +++ b/scripts/check-image-opacity.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +# Prove an image carries no plaintext application source. +# +# scripts/check-image-opacity.sh IMAGE STRING [STRING...] +# +# Streams `docker save IMAGE` into a throwaway container, unpacks every layer +# blob (plain tar or gzip; legacy `/layer.tar` and OCI `blobs/sha256/*` +# layouts) into its own directory, and fails if any STRING appears anywhere: +# in a layer's files or in the image metadata. Grepping the save output without +# unpacking each layer would miss source inside compressed layers, so a blob +# that cannot be unpacked (including a zstd layer) is an error, never a pass. +# As a positive control the unpacked layers must contain +# /cryptship/payload.enc, so an empty scan cannot pass. +# +# Needs only docker: the unpacking runs in a Linux container, so host tar +# quirks (e.g. a case-insensitive filesystem) do not matter. +set -euo pipefail + +[ "$#" -ge 2 ] || { echo "usage: $0 IMAGE STRING..." >&2; exit 2; } +IMAGE="$1" +shift +SCANNER=${SCANNER_IMAGE:-python:3.12-slim} + +# shellcheck disable=SC2016 # expanded inside the scanner container +SCAN=' +set -euo pipefail +S=/scan/save L=/scan/layers +mkdir -p "$S" "$L" +tar -xf - -C "$S" +n=0 +while IFS= read -r -d "" blob; do + case "$(basename "$blob")" in VERSION|oci-layout|repositories) continue ;; esac + magic="$(head -c 4 "$blob" | od -An -tx1 | tr -d " \n")" + case "$magic" in + 7b*|5b*) continue ;; # JSON: manifest, config, index + esac + dest="$L/$n"; mkdir -p "$dest" + case "$magic" in + 1f8b*) ok=0; gzip -dc "$blob" | tar -xf - -C "$dest" 2>/tmp/err || ok=$? ;; + 28b52ffd) echo "!! ${blob#"$S"/} is a zstd layer, which this check cannot unpack" >&2; exit 1 ;; + *) ok=0; tar -xf "$blob" -C "$dest" 2>/tmp/err || ok=$? ;; + esac + if [ "$ok" -ne 0 ]; then + echo "!! could not unpack layer blob ${blob#"$S"/}:" >&2; sed "s/^/ /" /tmp/err >&2; exit 1 + fi + n=$((n + 1)) +done < <(find "$S" -type f -size +0 -print0) + +if ! find "$L" -path "*/cryptship/payload.enc" | grep -q .; then + echo "!! unpacked $n layer(s) but found no /cryptship/payload.enc; the scan would prove nothing" >&2 + exit 1 +fi +args=() +for s in "$@"; do args+=(-e "$s"); done +if grep -rlaF "${args[@]}" "$L" "$S" >/tmp/leaks; then + echo "!! LEAK: plaintext application source found in the image:" + sed "s#^/scan/# #" /tmp/leaks + exit 1 +fi +echo "OK: unpacked $n layer(s); none of the $# marker string(s) appears in any layer or in the image metadata." +' + +docker save "$IMAGE" | docker run --rm -i --network none "$SCANNER" bash -c "$SCAN" scan "$@" diff --git a/scripts/demo-compiled.sh b/scripts/demo-compiled.sh index be64cd1..451e1fd 100644 --- a/scripts/demo-compiled.sh +++ b/scripts/demo-compiled.sh @@ -37,12 +37,7 @@ docker build -q -f "$DEMO/Dockerfile.compiled" -t cryptship-demo-compiled "$ROOT echo echo "== 4. image opacity (payload is ciphertext) ==" -docker save cryptship-demo-compiled -o "$WORK/image.tar" -rm -rf "$WORK/extracted"; mkdir -p "$WORK/extracted"; tar -xf "$WORK/image.tar" -C "$WORK/extracted" -if grep -rai -e "$SECRET" "$WORK/extracted" >/dev/null 2>&1; then - echo "!! LEAK: plaintext in image"; exit 1 -fi -echo "OK: no plaintext secret in the shipped image." +bash "$ROOT/scripts/check-image-opacity.sh" cryptship-demo-compiled "$SECRET" "CRYPTSHIP-DEMO-SOURCE-MARKER-6f1c9a2e" echo echo "== 5. run it (compiled bytecode executes normally) ==" diff --git a/scripts/demo.sh b/scripts/demo.sh index 31184fc..06b700c 100644 --- a/scripts/demo.sh +++ b/scripts/demo.sh @@ -6,7 +6,8 @@ # 1. build the vendor CLI + loader in a Go container # 2. vendor steps: keygen, pack (encrypt app), issue (sign license) # 3. build the runtime image (loader + encrypted payload + public key only) -# 4. PROVE the shipped image carries no plaintext source (docker save + grep) +# 4. PROVE the shipped image carries no plaintext source (docker save, unpack +# every layer, grep for a marker planted in the app's source) # 5. RUN it (decrypts into tmpfs, app works) # 6. NEGATIVE: tamper the license -> loader refuses to run set -euo pipefail @@ -16,7 +17,9 @@ DEMO="$ROOT/examples/demo-python" WORK="$DEMO/_work" GO=golang:1.24 SECRET="the-answer-is-42-do-not-leak" -MARKER="proprietary_algorithm" +# Planted in examples/demo-python/app/app.py; appears nowhere else in the image. +MARKER="CRYPTSHIP-DEMO-SOURCE-MARKER-6f1c9a2e" +grep -qF "$MARKER" "$DEMO/app/app.py" || { echo "!! marker missing from app.py; the leak check would prove nothing"; exit 1; } rm -rf "$WORK"; mkdir -p "$WORK" @@ -40,16 +43,8 @@ echo "== 3. build the runtime image ==" docker build -q -f "$DEMO/Dockerfile" -t cryptship-demo "$ROOT" echo -echo "== 4. PROVE opacity: docker save, then search every layer for the secret ==" -docker save cryptship-demo -o "$WORK/image.tar" -rm -rf "$WORK/extracted"; mkdir -p "$WORK/extracted" -tar -xf "$WORK/image.tar" -C "$WORK/extracted" -if grep -rai -e "$SECRET" -e "$MARKER" "$WORK/extracted" >/dev/null 2>&1; then - echo "!! LEAK: plaintext application source found in the shipped image" - grep -rail -e "$SECRET" -e "$MARKER" "$WORK/extracted" - exit 1 -fi -echo "OK: neither the secret string nor the source marker appears anywhere in the image." +echo "== 4. PROVE opacity: docker save, unpack every layer, search for the source ==" +bash "$ROOT/scripts/check-image-opacity.sh" cryptship-demo "$MARKER" "$SECRET" "def proprietary_algorithm" echo " The app ships only as ciphertext in payload.enc." echo @@ -58,16 +53,15 @@ docker run --rm --tmpfs /run/cryptship cryptship-demo echo echo "== 6. NEGATIVE: flip one signature byte, loader must refuse ==" -cp "$WORK/license.json" "$WORK/license.bad.json" -python3 - "$WORK/license.bad.json" <<'PY' +# Done in a container (the runtime image's Python), so the host needs only docker. +docker run --rm -i --network none --entrypoint python cryptship-demo -c ' import json, sys, base64 -p = sys.argv[1] -d = json.load(open(p)) +d = json.load(sys.stdin) sig = bytearray(base64.b64decode(d["sig"])) sig[0] ^= 0x01 d["sig"] = base64.b64encode(bytes(sig)).decode() -json.dump(d, open(p, "w")) -PY +json.dump(d, sys.stdout) +' <"$WORK/license.json" >"$WORK/license.bad.json" if docker run --rm --tmpfs /run/cryptship \ -v "$WORK/license.bad.json":/cryptship/license.json:ro \ cryptship-demo >/dev/null 2>"$WORK/err.txt"; then