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
83 changes: 62 additions & 21 deletions cmd/cryptship-loader/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,13 @@
package main

import (
"bytes"
"context"
"crypto/ed25519"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
Expand All @@ -26,6 +31,7 @@ import (
"github.com/AI2TH/cryptship/pkg/crypto"
"github.com/AI2TH/cryptship/pkg/keyprovider"
"github.com/AI2TH/cryptship/pkg/license"
"github.com/AI2TH/cryptship/pkg/online"
)

type config struct {
Expand Down Expand Up @@ -97,7 +103,7 @@ func run(cfg config) error {
if lic.Claims.Expired(time.Now().Unix()) {
return fmt.Errorf("license outside validity window (expires %d)", lic.Claims.NotAfter)
}
if err := enforceRevocation(lic); err != nil {
if err := enforceRevocation(lic, ring); err != nil {
return err
}

Expand Down Expand Up @@ -263,28 +269,36 @@ func escapeID(licenseID string) string { return url.PathEscape(licenseID) }
// operator's failure policy (CRYPTSHIP_REVOCATION): "open" (default, run on
// error), "closed" (refuse on error), "grace:<dur>" (run if a prior successful
// check is younger than <dur>). Only "closed" is a hard guarantee.
func enforceRevocation(lic *license.License) error {
//
// A cryptship-server signs the check response; the loader verifies it against
// the vendor key ring, so an on-path attacker or captive portal cannot forge
// "not revoked". In "closed" mode an UNSIGNED "active" answer is rejected.
func enforceRevocation(lic *license.License, ring license.KeyRing) error {
if lic.Claims.RevocationURL == "" {
return nil
}
mode := env("CRYPTSHIP_REVOCATION", "open")
stateFile := stateFile("revocation", lic.Claims.LicenseID)
sf := stateFile("revocation", lic.Claims.LicenseID)

revoked, err := checkRevocation(lic)
if err == nil {
if revoked {
return fmt.Errorf("license %s has been revoked", lic.Claims.LicenseID)
}
_ = os.MkdirAll(filepath.Dir(stateFile), 0o700)
_ = os.WriteFile(stateFile, []byte(strconv.FormatInt(time.Now().Unix(), 10)), 0o600)
revoked, signed, err := checkRevocation(lic, ring)
if err == nil && revoked {
return fmt.Errorf("license %s has been revoked", lic.Claims.LicenseID)
}
if err == nil && (signed || mode != "closed") {
_ = os.MkdirAll(filepath.Dir(sf), 0o700)
_ = os.WriteFile(sf, []byte(strconv.FormatInt(time.Now().Unix(), 10)), 0o600)
return nil
}
if err == nil && !signed && mode == "closed" {
err = errors.New("revocation response was unsigned; CRYPTSHIP_REVOCATION=closed requires a signing cryptship-server")
}

switch {
case mode == "closed":
return fmt.Errorf("revocation check failed and CRYPTSHIP_REVOCATION=closed: %w", err)
case strings.HasPrefix(mode, "grace:"):
if d, perr := time.ParseDuration(strings.TrimPrefix(mode, "grace:")); perr == nil {
if b, rerr := os.ReadFile(stateFile); rerr == nil {
if b, rerr := os.ReadFile(sf); rerr == nil {
// A last-success time in the future (clock set back, or a
// hand-edited file) does not count as within grace.
if last, lerr := strconv.ParseInt(strings.TrimSpace(string(b)), 10, 64); lerr == nil &&
Expand All @@ -302,35 +316,62 @@ func enforceRevocation(lic *license.License) error {
}
}

// checkRevocation returns (revoked, err). 200 = active, 410 = revoked, anything
// else is an error so the operator's policy decides.
func checkRevocation(lic *license.License) (bool, error) {
// checkRevocation returns (revoked, signed, err). It sends a nonce and, if the
// server returns a signed online.CheckResponse that verifies against the ring
// and echoes the nonce, trusts its Revoked flag (signed=true). Otherwise it
// falls back to the legacy status-code reading (200 active / 410 revoked),
// reported as unsigned.
func checkRevocation(lic *license.License, ring license.KeyRing) (revoked bool, signed bool, err error) {
u, err := url.Parse(lic.Claims.RevocationURL)
if err != nil {
return false, err
return false, false, err
}
nonce := make([]byte, 16)
if _, err := rand.Read(nonce); err != nil {
return false, false, err
}
q := u.Query()
q.Set("license_id", lic.Claims.LicenseID)
q.Set("nonce", hex.EncodeToString(nonce))
u.RawQuery = q.Encode()

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return false, err
return false, false, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return false, err
return false, false, err
}
defer resp.Body.Close()
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
body, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10))

// Signed path: a valid, nonce-matching CheckResponse is authoritative.
var cr online.CheckResponse
if json.Unmarshal(body, &cr) == nil && len(cr.Sig) > 0 &&
cr.LicenseID == lic.Claims.LicenseID && bytes.Equal(cr.Nonce, nonce) {
pub, ok := ring[cr.SigningKeyID]
if !ok {
pub, ok = ring["*"]
}
if !ok || len(pub) != ed25519.PublicKeySize || !ed25519.Verify(pub, online.CheckSigningInput(cr), cr.Sig) {
return false, false, errors.New("revocation check: bad response signature")
}
if cr.NotAfter != 0 && time.Now().Unix() > cr.NotAfter {
return false, false, errors.New("revocation check: response expired")
}
return cr.Revoked, true, nil
}

// Legacy unsigned path.
switch resp.StatusCode {
case http.StatusOK:
return false, nil
return false, false, nil
case http.StatusGone:
return true, nil
return true, false, nil
default:
return false, fmt.Errorf("unexpected status %s", resp.Status)
return false, false, fmt.Errorf("unexpected status %s", resp.Status)
}
}
6 changes: 3 additions & 3 deletions cmd/cryptship-loader/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,15 +108,15 @@ func TestRevocationGraceIgnoresFutureTimestamp(t *testing.T) {
}

write(time.Now().Add(-10 * time.Minute).Unix())
if err := enforceRevocation(lic); err != nil {
if err := enforceRevocation(lic, license.KeyRing{}); err != nil {
t.Fatalf("recent success should be within grace: %v", err)
}
write(time.Now().Add(-2 * time.Hour).Unix())
if err := enforceRevocation(lic); err == nil {
if err := enforceRevocation(lic, license.KeyRing{}); err == nil {
t.Fatal("old success accepted as within grace")
}
write(time.Now().Add(365 * 24 * time.Hour).Unix())
if err := enforceRevocation(lic); err == nil {
if err := enforceRevocation(lic, license.KeyRing{}); err == nil {
t.Fatal("future success timestamp accepted as within grace")
}
}
17 changes: 16 additions & 1 deletion cmd/cryptship-loader/providers.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"net/http"
"os"
"time"

"github.com/AI2TH/cryptship/pkg/keyprovider"
Expand All @@ -10,11 +11,25 @@ import (

// buildProviders returns the key providers the loader will try, in order. The
// vendor key ring verifies signed server responses (online / attested).
//
// Online outage grace is opt-in: set CRYPTSHIP_ONLINE_GRACE to a duration (e.g.
// "12h") to let a cached, machine-sealed secret ride out a server outage for
// that long. It is off by default (every start needs the server).
func buildProviders(ring license.KeyRing) []keyprovider.Provider {
httpClient := &http.Client{Timeout: 10 * time.Second}

var grace time.Duration
if v := os.Getenv("CRYPTSHIP_ONLINE_GRACE"); v != "" {
if d, err := time.ParseDuration(v); err == nil {
grace = d
} else {
os.Stderr.WriteString("cryptship-loader: WARNING: bad CRYPTSHIP_ONLINE_GRACE, grace disabled: " + err.Error() + "\n")
}
}

return []keyprovider.Provider{
keyprovider.Offline{},
keyprovider.Online{Keys: ring, Client: httpClient},
keyprovider.Online{Keys: ring, Client: httpClient, CacheDir: stateDir(), Grace: grace},
keyprovider.Attested{Keys: ring, Client: httpClient, Attester: keyprovider.DefaultAttester()},
}
}
14 changes: 8 additions & 6 deletions cmd/cryptship-server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ func main() {
keyID := flag.String("key-id", "v1", "signing key id advertised in responses")
addr := flag.String("addr", ":8080", "listen address")
ttl := flag.Duration("ttl", 24*time.Hour, "validity of each key answer")
revoke := flag.String("revoke", "", "comma-separated license ids to deny")
revoke := flag.String("revoke", "", "comma-separated license ids to deny (static)")
revokeFile := flag.String("revoke-file", "", "path to a live denylist (one license id per line); edit it to revoke without restarting")
requireAtt := flag.Bool("require-attestation", false, "require verified TEE attestation (fails to start: no verifier is built in yet)")
flag.Parse()

Expand All @@ -51,11 +52,12 @@ func main() {
}

srv := &licenseserver.Server{
Master: master,
SignKey: ed25519.PrivateKey(priv),
KeyID: *keyID,
TTL: *ttl,
Revoked: revoked,
Master: master,
SignKey: ed25519.PrivateKey(priv),
KeyID: *keyID,
TTL: *ttl,
Revoked: revoked,
RevokedFile: *revokeFile,
}
verifier, err := attestationVerifier(*requireAtt, builtinVerifier())
must(err, "--require-attestation")
Expand Down
20 changes: 14 additions & 6 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -225,18 +225,26 @@ remote execution.
- **Offline:** by expiry. Issue short-lived licenses and renew. A distributed
denylist only helps for clients that check in.
- **Online:** the key server refuses to return the binding secret for a revoked
license, so its next start fails (revoke with `cryptship-server --revoke`;
running instances keep running). An online-bound app does not start while the
server is unreachable.
license, so its next start fails. Revoke with `cryptship-server --revoke`
(static) or `--revoke-file` (a live denylist re-read per request — no restart);
running instances keep running. By default an online-bound app does not start
while the server is unreachable; `CRYPTSHIP_ONLINE_GRACE=<dur>` lets it ride out
an outage using a machine-sealed cached secret for that long (a reachable
server that says revoked still wins).
- **Signed `revocation_url` check:** the loader sends a nonce and verifies the
server's signed answer against the key ring, so an on-path attacker or captive
portal cannot forge "not revoked"; `CRYPTSHIP_REVOCATION=closed` also rejects
an unsigned "active" answer.

## Roadmap

1. **TPM provider** — seal the content key to the TPM so a copied license is
useless off the physical machine, even to root.
2. **Online provider + reference license server** — IMPLEMENTED (signed,
nonce-bound replies; revocation by denylist). Still open: seat management
(the `machine` field is sent but not enforced), machine (re)activation API,
and offline grace caching of the online key.
nonce-bound replies; live `--revoke-file` denylist; signed `revocation_url`
check; `CRYPTSHIP_ONLINE_GRACE` outage caching). Still open: seat management
(the `machine` field is sent but not enforced) and a machine (re)activation
API.
3. **Cloud KMS provider** — wrap the content key with AWS/GCP/Azure KMS; unwrap
gated by cloud IAM + signed instance identity.
4. **Confidential-compute provider** — SEV-SNP/TDX with remote attestation; the
Expand Down
27 changes: 20 additions & 7 deletions docs/HOWTO.md
Original file line number Diff line number Diff line change
Expand Up @@ -205,8 +205,10 @@ cryptship-server \
--master master.key --sign vendor.key --key-id v1 \
--addr :8080 --ttl 24h
```
- Revoke a license immediately: add `--revoke lic_abc,lic_def` (restart) — bound
apps then refuse to start.
- Revoke a license immediately: add `--revoke lic_abc,lic_def` (static, applied
at start), or `--revoke-file deny.txt` for a **live denylist** — one license id
per line; edit the file and the next request sees it, **no restart needed**.
Bound apps then refuse to start.
- `--require-attestation` makes the server refuse to start: no SEV-SNP/TDX
verifier is built in yet, and accepting evidence it cannot verify would give
no protection. To use `attested` today, implement `attest.Verifier` (signature
Expand All @@ -218,9 +220,19 @@ cryptship-server \
asks, so give the attestation server its own master key and never run a
non-verifying server with that key.

The loader's revocation behaviour on a *network failure* is the operator's
choice via `CRYPTSHIP_REVOCATION`: `open` (default — run), `closed` (refuse),
`grace:<dur>` (run if the last good check is younger than `<dur>`).
A separate revocation check (`revocation_url` in the license) is **signed**: the
loader sends a nonce and verifies the server's signed answer against the key
ring, so a captive portal or on-path attacker cannot forge "not revoked".
`CRYPTSHIP_REVOCATION=closed` additionally rejects any *unsigned* "active" answer.
The loader's behaviour on a *network failure* is the operator's choice:
`open` (default — run), `closed` (refuse), `grace:<dur>` (run if the last good
check is younger than `<dur>`).

For the **online** binding itself, set `CRYPTSHIP_ONLINE_GRACE=<dur>` (e.g. `12h`)
to let a cached, machine-sealed secret ride out a license-server **outage** for
that long. It is off by default (every start needs the server); it never bypasses
revocation (a reachable server that says revoked still wins) and never applies to
`attested` (which must always re-attest).

---

Expand Down Expand Up @@ -257,8 +269,9 @@ accepts both versions.
| `CRYPTSHIP_PUBKEY` | `/cryptship/vendor.pub` | public key / ring |
| `CRYPTSHIP_EXTRACT` | `/run/cryptship/app` | decrypt dir (put on tmpfs) |
| `CRYPTSHIP_REQUIRE_TMPFS` | unset | `1` = refuse if not tmpfs |
| `CRYPTSHIP_REVOCATION` | `open` | `open` / `closed` / `grace:<dur>` |
| `CRYPTSHIP_STATE_DIR` | `/var/lib/cryptship` | revocation-grace and clock-rollback state (best effort: if it is not writable the clock check is skipped with a warning) |
| `CRYPTSHIP_REVOCATION` | `open` | `open` / `closed` / `grace:<dur>` (revocation-URL failure policy) |
| `CRYPTSHIP_ONLINE_GRACE` | unset | `<dur>` (e.g. `12h`): ride out an online license-server outage using a machine-sealed cached secret; off by default |
| `CRYPTSHIP_STATE_DIR` | `/var/lib/cryptship` | revocation-grace, online-grace, and clock-rollback state (best effort: if it is not writable those checks degrade with a warning) |

### CLI commands
| Command | Purpose |
Expand Down
2 changes: 1 addition & 1 deletion pkg/keyprovider/attested.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func (a Attested) ContentKey(ctx context.Context, lic *license.License) ([]byte,
}
return fetchAndUnwrap(ctx, a.Keys, a.Client, lic, func(nonce []byte) ([]byte, error) {
return a.Attester.Evidence(ctx, online.AttestationNonce(lic.Claims.LicenseID, nonce))
})
}, nil) // attested never uses the outage grace cache — it must always re-attest
}

// noTEE is the default attester on hosts without confidential-compute hardware.
Expand Down
Loading
Loading