Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 38 additions & 19 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
105 changes: 105 additions & 0 deletions cmd/cryptship-loader/clock.go
Original file line number Diff line number Diff line change
@@ -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...)
}
87 changes: 87 additions & 0 deletions cmd/cryptship-loader/clock_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
Loading
Loading