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
49 changes: 49 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Changelog

All notable changes to cryptship. Format loosely follows
[Keep a Changelog](https://keepachangelog.com/); versions are git tags /
GitHub releases.

## [Unreleased]

### Security / fixed (from a full code review)
- **Online grace cache reworked.** It now caches the **content key** instead of
the per-license binding secret (no portable license-wide credential), and the
`cached_at` / `not_after` timestamps are **authenticated via the AEAD** and
both enforced — editing them to widen the window now fails the open.
- **Live revocation freshness.** `cryptship-server` re-reads `--revoke-file` on
every request (was an mtime/size cache that could miss a same-length edit and
keep honouring a just-revoked license).
- **Grace timer only refreshes on a signed answer**, so an unsigned (captive
portal / on-path) "active" response can't extend `CRYPTSHIP_REVOCATION=grace`.
- Server wipes the per-license secret after signing; the signing-key id is bound
into the signed response/check inputs.
- Loader no longer writes a separate extract-marker file (removes an `O_EXCL`
collision with a payload that ships that name); it recognises its own extract
dir by the manifest instead.
- `cryptship` propagates `crypto/rand` errors when generating ids.

### Docs / project hygiene
- Added `SECURITY.md` (private disclosure + honest scope), `CONTRIBUTING.md`,
this `CHANGELOG.md`.
- README: `go install` now targets `cryptship` + `cryptship-server` only (not the
loader); roadmap corrected (online grace is shipped).
- HOWTO: documented the Linux-only `fingerprint`, the `cryptship_devfp` /
`CRYPTSHIP_FINGERPRINT` dev hatch, and the `-- <command>` default.

## [0.2.0]

- Code-review hardening: context-bound KEK (format **v2** binds every claim;
editing any claim breaks the unwrap), archive symlink-escape fix, clock-rollback
guard, non-root example images, a layer-opacity scan that unpacks every layer.
- Online/revocation: live `--revoke-file`, **signed** `/v1/check` revocation,
`CRYPTSHIP_ONLINE_GRACE` outage caching, attestation fails closed
(`--require-attestation` without a verifier refuses to start).
- `go.mod` module path corrected to `github.com/AI2TH/cryptship`.

## [0.1.0]

- Initial release: AES-256-GCM payload encryption, Ed25519-signed licenses,
offline key provider (none / strict / pool machine binding), the loader, the
`cryptship` CLI, the `cryptship-server` reference broker, compile/transform
seam, container hardening, per-license watermarking, three demos, and docs.
52 changes: 52 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Contributing to cryptship

Thanks for your interest! cryptship is an open-source (GPLv3) toolkit for
shipping encrypted, license-gated application code in container images.

## Build and test

The module is **Go 1.24+** and standard-library only (no third-party
dependencies). You don't need Go on your host — everything can run in a
container:

```bash
# build + vet + race tests, exactly as CI runs them
docker run --rm -v "$PWD":/src -w /src golang:1.24 sh -c '
gofmt -l . # must print nothing
go vet ./...
go build ./...
go build -tags cryptship_devfp ./cmd/cryptship-loader
go test -race ./...'
```

End-to-end demos (need Docker, e.g. colima):

```bash
bash scripts/demo.sh # baseline
bash scripts/demo-compiled.sh # ships bytecode, not source
bash scripts/demo-online.sh # server-gated key + revocation
bash scripts/check-mermaid.sh # validates the diagrams in docs/
```

The `cryptship_devfp` build tag enables the `CRYPTSHIP_FINGERPRINT` override so
you can exercise `strict`/`pool` binding without real machine ids; it is compiled
out of production builds.

## Pull requests

- Keep the tree **gofmt-clean** and `go vet` / `go test -race` green — CI gates on all three plus mermaid rendering.
- Add tests for behavior changes (the suite leans heavily on table/round-trip tests).
- Touching crypto, the license format, or the online/attested protocol? Say so
in the PR description and keep changes minimal and reviewable — these are
security-sensitive. Note any on-disk or wire-format change.
- One logical change per PR where practical.

## Security

Please report vulnerabilities privately — see [SECURITY.md](SECURITY.md). Do not
open a public issue for a security problem.

## License

By contributing, you agree your contributions are licensed under the project's
GPLv3 license.
29 changes: 19 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,12 +77,16 @@ tamper step also run in containers.
bash scripts/demo.sh
```

To install the tools directly (Go 1.24 or later):
To install the vendor-side tools directly (Go 1.24 or later):

```bash
go install github.com/AI2TH/cryptship/cmd/...@latest
go install github.com/AI2TH/cryptship/cmd/cryptship@latest
go install github.com/AI2TH/cryptship/cmd/cryptship-server@latest
```

(The loader, `cmd/cryptship-loader`, is built *into your image* from source — see the
Dockerfiles — so there's no need to install it on your host.)

The demo packs a tiny Python app, issues a license, builds the image, then
**`docker save`s it, unpacks every layer and greps for a marker planted in the
app's source** to show the source isn't there, runs it to show it decrypts and
Expand All @@ -97,6 +101,7 @@ works, and finally tampers with the license to show the loader refuses it.
- **[docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)** — design, threat model, license
format, roadmap.
- **[deploy/README.md](deploy/README.md)** — hardened docker / Kubernetes deployment.
- **[SECURITY.md](SECURITY.md)** — reporting vulnerabilities + what's in scope. **[CONTRIBUTING.md](CONTRIBUTING.md)** · **[CHANGELOG.md](CHANGELOG.md)**

## Deployment modes = key providers

Expand Down Expand Up @@ -159,14 +164,18 @@ for the full schema and the threat model.
signature over the stored bytes); context-bound KEK (format v2: editing any claim breaks
the unwrap); machine binding (none / strict / pool); online key provider + reference
`cryptship-server`; signing-key rotation (key ring); configurable revocation
(open / closed / grace); the compile/transform seam; loader + container
hardening; per-license watermarking; and the attested (confidential-compute)
provider behind `Attester` / `attest.Verifier` interfaces with test-only
implementations (no production verifier yet).

**Roadmap:** a real SEV-SNP/TDX `Attester` + Trustee-style KBS integration,
TPM-sealed binding, cloud-KMS wrapping, offline grace caching for `online`, and
chunked AEAD for very large payloads.
(open / closed / grace) with **signed** revocation checks; **live `--revoke-file`
revocation** (no restart); **online outage grace** (`CRYPTSHIP_ONLINE_GRACE`, a
machine-sealed cached content key with authenticated validity); the
compile/transform seam; loader + container hardening; per-license watermarking;
and the attested (confidential-compute) provider behind `Attester` /
`attest.Verifier` interfaces with test-only implementations (no production
verifier yet).

**Roadmap:** a real SEV-SNP/TDX `Attester` + Trustee-style KBS integration (and
the attested replay fix: server-issued challenge + ephemeral TEE key), TPM-sealed
binding, cloud-KMS wrapping, seat management, and chunked AEAD for very large
payloads.

## Crypto

Expand Down
45 changes: 45 additions & 0 deletions SECURITY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Security policy

## Reporting a vulnerability

Please report security issues **privately**, not as a public issue or PR.

- Preferred: GitHub → the repository's **Security** tab → **Report a vulnerability**
(private vulnerability reporting / security advisory).
- Include: affected version or commit, a description, and ideally a minimal
reproduction (a crafted license, a sequence of commands, or a short test).

We aim to acknowledge a report within a few days and to agree on a disclosure
timeline with you. Please give us reasonable time to fix before any public
disclosure.

## Supported versions

cryptship is pre-1.0 and moves fast. Fixes land on `main` and in the latest
tagged release; please verify against the latest release before reporting.

## Scope — what is and isn't a vulnerability

cryptship's threat model is stated plainly in the [README](README.md) and
[docs/ARCHITECTURE.md](docs/ARCHITECTURE.md). In particular, these are **known,
documented limitations, not vulnerabilities**:

- **Host/container root extracting the running plaintext** (dumping tmpfs or
`/proc/<pid>/mem`). Code that runs on hardware the attacker controls can always
be extracted; only a confidential-compute key provider (SEV-SNP/TDX, the
`attested` roadmap) or remote execution prevents this.
- **A patched loader** skipping loader-enforced policy (expiry comparison,
revocation). The crypto design makes license *forgery* and claim *tampering*
fail the unwrap; it does not stop someone from modifying the open-source loader
they run.
- **`attested` mode without a real verifier.** It ships with test-only
attestation; `cryptship-server --require-attestation` fails closed precisely so
this isn't mistaken for protection.
- **Enabling `CRYPTSHIP_ONLINE_GRACE` on an untrusted host** (documented
trade-off), and **software machine fingerprints being spoofable by root**.

In scope and very welcome: key/secret handling bugs, signature or AEAD
verification that can be bypassed, nonce/replay/downgrade flaws, path-traversal
or extraction escapes, anything that lets an **unprivileged** in-container
attacker read the decrypted app, or any way to unwrap the content key without
legitimate license material.
25 changes: 12 additions & 13 deletions cmd/cryptship-loader/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,11 +152,9 @@ func run(cfg config) error {
return execApp(cfg, lic.Claims)
}

// extractMarker is created in the extract dir before anything is extracted,
// so a later run knows the directory is cryptship's to empty.
const extractMarker = ".cryptship-extract-dir"

// manifestName is the per-license watermark written after extraction.
// manifestName is the per-license watermark written after extraction. Its
// presence also marks the extract dir as cryptship's to empty on a later run,
// so there is no separate marker file to collide with payload contents.
const manifestName = ".cryptship-manifest.json"

// prepareDir empties the extract dir for a fresh extraction. It only deletes
Expand All @@ -178,19 +176,16 @@ func prepareDir(dir string) error {
if err != nil {
return err
}
if len(entries) > 0 && !hasEntry(entries, extractMarker) && !hasEntry(entries, manifestName) {
return fmt.Errorf("refusing to empty extract dir %s: it is not empty and was not created by cryptship-loader (no %s); point CRYPTSHIP_EXTRACT at an empty directory", abs, extractMarker)
if len(entries) > 0 && !hasEntry(entries, manifestName) {
return fmt.Errorf("refusing to empty extract dir %s: it is not empty and has no %s from a previous cryptship run; point CRYPTSHIP_EXTRACT at an empty directory", abs, manifestName)
}
// Empty the dir without removing it — it may be the tmpfs mount point.
for _, e := range entries {
if err := os.RemoveAll(filepath.Join(abs, e.Name())); err != nil {
return fmt.Errorf("clean extract dir: %w", err)
}
}
if err := os.Chmod(abs, 0o700); err != nil {
return err
}
return os.WriteFile(filepath.Join(abs, extractMarker), nil, 0o400)
return os.Chmod(abs, 0o700)
}

func hasEntry(entries []os.DirEntry, name string) bool {
Expand Down Expand Up @@ -285,8 +280,12 @@ func enforceRevocation(lic *license.License, ring license.KeyRing) error {
return fmt.Errorf("license %s has been revoked", lic.Claims.LicenseID)
}
if err == nil && (signed || mode != "closed") {
_ = os.MkdirAll(filepath.Dir(sf), 0o700)
_ = os.WriteFile(sf, []byte(strconv.FormatInt(time.Now().Unix(), 10)), 0o600)
// Only a SIGNED "active" answer refreshes the grace clock; an unsigned
// answer (captive portal / on-path) must not be able to extend grace.
if signed {
_ = os.MkdirAll(filepath.Dir(sf), 0o700)
_ = os.WriteFile(sf, []byte(strconv.FormatInt(time.Now().Unix(), 10)), 0o600)
}
return nil
}
if err == nil && !signed && mode == "closed" {
Expand Down
20 changes: 6 additions & 14 deletions cmd/cryptship-loader/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,29 +35,21 @@ func TestPrepareDirReusesItsOwnDir(t *testing.T) {
if err := prepareDir(dir); err != nil {
t.Fatal(err)
}
// Simulate a completed prior run: extracted files plus the manifest that
// marks the dir as cryptship's.
if err := os.WriteFile(filepath.Join(dir, "old.py"), []byte("x"), 0o600); err != nil {
t.Fatal(err)
}
// Second run over the first run's tree: emptied and re-marked.
if err := os.WriteFile(filepath.Join(dir, manifestName), []byte("{}"), 0o400); err != nil {
t.Fatal(err)
}
// Second run over that tree: emptied because the manifest marks it as ours.
if err := prepareDir(dir); err != nil {
t.Fatalf("second prepareDir: %v", err)
}
if _, err := os.Stat(filepath.Join(dir, "old.py")); !os.IsNotExist(err) {
t.Fatal("old extraction not removed")
}
if _, err := os.Stat(filepath.Join(dir, extractMarker)); err != nil {
t.Fatalf("marker missing: %v", err)
}
// A dir left by an older loader (manifest, no marker) is accepted too.
if err := os.Remove(filepath.Join(dir, extractMarker)); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, manifestName), []byte("{}"), 0o400); err != nil {
t.Fatal(err)
}
if err := prepareDir(dir); err != nil {
t.Fatalf("prepareDir over an older loader's dir: %v", err)
}
}

func TestWriteManifestDoesNotFollowSymlink(t *testing.T) {
Expand Down
19 changes: 14 additions & 5 deletions cmd/cryptship/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,10 @@ func cmdPack(args []string) error {
if err != nil {
return err
}
payloadID := randHex(16)
payloadID, err := randHex(16)
if err != nil {
return err
}
blob, err := crypto.SealPayload(contentKey, tarBytes, payloadID)
if err != nil {
return err
Expand Down Expand Up @@ -273,7 +276,11 @@ func cmdIssue(args []string) error {

lid := *licID
if lid == "" {
lid = "lic_" + randHex(8)
h, err := randHex(8)
if err != nil {
return err
}
lid = "lic_" + h
}
notAfter, err := resolveExpiry(*expires, *days)
if err != nil {
Expand Down Expand Up @@ -490,10 +497,12 @@ func tsStr(u int64) string {
return time.Unix(u, 0).UTC().Format(time.RFC3339)
}

func randHex(n int) string {
func randHex(n int) (string, error) {
b := make([]byte, n)
_, _ = rand.Read(b)
return hex.EncodeToString(b)
if _, err := rand.Read(b); err != nil {
return "", err
}
return hex.EncodeToString(b), nil
}

func writeB64(path string, data []byte, mode os.FileMode) error {
Expand Down
10 changes: 8 additions & 2 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -229,8 +229,14 @@ remote execution.
(static) or `--revoke-file` (a live denylist re-read per request — no restart);
running instances keep running. By default an online-bound app does not start
while the server is unreachable; `CRYPTSHIP_ONLINE_GRACE=<dur>` lets it ride out
an outage using a machine-sealed cached secret for that long (a reachable
server that says revoked still wins).
an outage for that long. The cache holds the **content key** (not the
per-license secret), sealed to a machine/state-dir key, with `cached_at` and
the server's `not_after` **authenticated** (editing them to widen the window
fails the open) and both enforced; a reachable server that says revoked still
wins. **Trade-off (honest):** on a host the licensee controls, enabling grace
writes a sealed content key to disk, so for the window it is extractable much
like the running process already is — use it where availability matters more
than instant offline revocation, or on hosts you trust. Off by default.
- **Signed `revocation_url` check:** the loader sends a nonce and verifies the
server's signed answer against the key ring, so an on-path attacker or captive
portal cannot forge "not revoked"; `CRYPTSHIP_REVOCATION=closed` also rejects
Expand Down
13 changes: 12 additions & 1 deletion docs/HOWTO.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,10 @@ ENTRYPOINT ["/cryptship-loader", "--", "python", "app.py"]
```

Everything after `--` is the command to run after decryption (the loader `cd`s
into the extracted app dir first). Run it with the decrypt dir on tmpfs:
into the extracted app dir first). If you omit `-- <command>`, the loader runs
`./entrypoint` from the extracted tree and, if there is none, exits with
`locate command "./entrypoint": ... not found` — so always pass your command.
Run it with the decrypt dir on tmpfs:

```bash
docker run --rm --tmpfs /run/cryptship your-image
Expand Down Expand Up @@ -114,6 +117,14 @@ cryptship issue ... --binding strict --fingerprint 8af75d... ...
In a container, bind-mount a stable id so the fingerprint is readable and
constant: `-v /etc/machine-id:/etc/machine-id:ro`.

> **Note:** `cryptship fingerprint` reads **Linux** identifiers (`/etc/machine-id`,
> DMI) — it is meant to run on the (Linux) deploy host, and returns an error on
> macOS/Windows. To exercise strict/pool **locally without real machine ids**,
> build the loader with the dev tag and set `CRYPTSHIP_FINGERPRINT`:
> `go build -tags cryptship_devfp ./cmd/cryptship-loader` then run it with
> `-e CRYPTSHIP_FINGERPRINT=machineA`. This override is **compiled out of
> production builds**, so it can't be used to defeat binding on a real deployment.

### pool — a set of machines
Wrap to several fingerprints; any one of them decrypts. For clusters with known
nodes.
Expand Down
Loading
Loading