diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..577854a --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,186 @@ +You are an experienced, pragmatic software engineering AI agent. Do not over-engineer a solution when a simple one is possible. Keep edits minimal. Ask for permission before making an exception to any rule. + +# AGENTS.md + +## Project Overview + +`gpgkms` (module `github.com/coder/gpgkms`) makes OpenPGP (GPG) signatures with an +RSA key held in Google Cloud KMS, so a release signing private key never exists +outside the HSM. It was extracted from coder/coder's `scripts/gpgkms` and is used +by the release jobs of coder/coder and coder/terraform-provider-coder, which +pin it as a Go tool dependency (`go get -tool …@`). + +It is both a Go library (package `gpgkms`) and a CLI (`cmd/gpgkms`) with two +subcommands: `public-key` (export the derived OpenPGP public key) and `sign` +(write a detached signature). + +Key terms: + +- **Derived key**: the OpenPGP key is not stored anywhere. It is rebuilt on every + run from the KMS public key, an `Identity` (name, comment, email), a pinned + creation time (`Created`) and an optional `Lifetime`. +- **Fingerprint**: the OpenPGP v4 fingerprint depends on the RSA public key and + `Created` only (not the user ID). Consumers and registries pin it, so anything + that changes it is a breaking change for every user. +- **Determinism**: RSA PKCS#1 v1.5 signatures are deterministic, and go-crypto's + random salt notation is disabled, so the exported public key (including its + self-signature) is byte-identical on every run. +- **Prepend**: `sign -prepend` writes an existing binary signature (for example + from an old `gpg` key) before the KMS signature, for key rotations. + +Technology: + +- Go (version and patched toolchain pinned in `go.mod`; `toolchain` is bumped + for security fixes, so `go install` builds with it). +- `github.com/ProtonMail/go-crypto/openpgp` for OpenPGP packets and armor. +- `google.golang.org/api/cloudkms/v1` for KMS, with Application Default + Credentials. Only the KMS algorithm `RSA_SIGN_PKCS1_4096_SHA256` is supported. +- Standard library `flag` for the CLI. No other frameworks, no database. + +**Security posture:** this code runs in release jobs that hold the KMS signer +role. `CODEOWNERS` assigns every file to `@coder/security`, and `SECURITY.md` +says to treat every change like a change to release signing. Consumers pin this +module by commit. + +## Reference + +| Path | Purpose | +|---|---| +| `gpgkms.go` | `Identity`, `NewEntity` (key derivation and self-signature), `WritePublicKey`, `Sign`, `SignOptions`, `ValidateSignatures`. | +| `kms.go` | `KMSSigner`, a `crypto.Signer` backed by a Cloud KMS CryptoKeyVersion. Checks the KMS algorithm and HSM protection level, only makes PKCS#1 v1.5 signatures of SHA-256 digests, bounds each request with a timeout, and verifies every KMS signature locally before returning it. | +| `kms_test.go` | Tests `KMSSigner` against a fake Cloud KMS (`httptest` server, `option.WithEndpoint`). Use it for any KMS change; there is no other way to exercise `kms.go` without credentials. | +| `cmd/gpgkms/main.go` | CLI: flag parsing, `-fingerprint` pinning, file I/O. `newSigner` is a package variable swapped in tests. | +| `gpgkms_test.go` | Library tests; `opaqueSigner` hides `*rsa.PrivateKey` so tests use the `crypto.Signer` path like KMS does. | +| `compat_test.go` | Verbatim copy of coder/coder's original derivation; asserts the same fingerprint and byte-identical public key. | +| `golden_test.go` | Pins exported public-key bytes against `testdata/*.asc.golden`. | +| `testdata/test-key.pem` | Throwaway RSA key used only by the golden test. Never use it for anything else. | +| `.github/workflows/ci.yml` | Tests (Linux, macOS), golangci-lint, govulncheck (also weekly), actionlint, zizmor. | +| `.github/dependabot.yml` | Weekly grouped Go (`/` and `/tools`) and Actions updates with a 7-day cooldown. | +| `tools/go.mod` | Separate module pinning golangci-lint and govulncheck, so their dependencies stay out of the library's module graph. Run them with `go tool -modfile=tools/go.mod`. | +| `.golangci.yml` | golangci-lint v2 config (gosec, revive, errorlint, gocritic, nolintlint, goimports with local prefix). | + +Data flow: `NewKMSSigner` fetches and validates the KMS public key → +`NewEntity` builds an OpenPGP primary key with `Created` and self-signs the user +ID through the signer → `WritePublicKey` exports it, or `Sign` writes a detached +signature (optionally after prepended signatures, optionally armored). Every +signature calls KMS `AsymmetricSign` through `KMSSigner.Sign`. + +## Essential Commands + +Run from the repository root. golangci-lint and govulncheck are pinned in +`tools/go.mod`; the actionlint and zizmor versions live in `ci.yml`'s `env`. + +```bash +go build ./... # build +gofmt -l . && go vet ./... # format check and vet (gofmt -w . to fix) +go test -race -shuffle=on -count=1 ./... # tests, as CI runs them +go mod tidy -diff && (cd tools && go mod tidy -diff) && go mod verify # module hygiene, as CI runs it +go tool -modfile=tools/go.mod golangci-lint run ./... # lint (also checks gofmt/goimports) +go tool -modfile=tools/go.mod govulncheck ./... # vulnerability scan +go run github.com/rhysd/actionlint/cmd/actionlint@v1.7.12 # workflow lint +pipx run zizmor==1.32.0 .github/ # workflow security audit +go clean -testcache # clean cached test results +``` + +There is no dev server. The CLI cannot run against real KMS without credentials +and the signer role; test it through `run()` with a swapped `newSigner` (see +`cmd/gpgkms/main_test.go`). + +Regenerate golden files (only when the change is intended; see Anti-patterns): + +```bash +go test -run TestGoldenPublicKey -update . +``` + +Pass `.`, not `./...`: only the root package defines `-update`, so the +`cmd/gpgkms` test binary fails on the unknown flag. The regenerated files +must match the committed ones byte for byte (`git status` stays clean). + +## Patterns + +- **Reproducible output is a feature.** Any `packet.Config` used for the + self-signature must set `Time` to `Identity.Created`, `DefaultHash` to SHA-256 + and `NonDeterministicSignaturesViaNotation` to `false`. Otherwise the exported + key changes on every run. +- **Validate early, with clear errors.** `Identity.validate` bounds `Lifetime` to + what fits in a `uint32` of seconds; the CLI requires `-key` and `-created` + before contacting KMS. Error messages say how to fix the input (for example + `(wrong -key, -created or KMS key?)`). +- **Fail closed on KMS responses.** `NewKMSSigner` rejects keys that are not + HSM-protected, and `KMSSigner.Sign` rejects PSS and non-SHA-256 input and + verifies the returned signature with the public key, so a corrupted response + never becomes a release signature. Keep these checks. +- **Fail closed on inputs that end up in public files.** `ValidateSignatures` + reads `-prepend` with `packet.Read`, not `packet.Reader.Next` (which silently + skips unknown and marker packets), and accepts only binary-document + signatures. The CLI writes `-out` through a temp file and rename, and refuses + an `-out` that is the file being signed. +- **Errors** are wrapped with `fmt.Errorf("context: %w", err)` and compared with + `errors.Is` (enforced by errorlint). +- **`//nolint` and `#nosec`** need a specific linter and a reason + (nolintlint `require-explanation`, `require-specific`), for example + `//nolint:gosec // validate bounds Lifetime to [0, 2^32-1] seconds`. +- **Tests** use only the standard library (`testing`, no testify), a local + `must(t, err)` helper, `t.Parallel()` in the library package, and map-driven + table tests. Generate throwaway keys with `rsa.GenerateKey` (2048 bits is + enough for tests); verify outputs with go-crypto's `CheckDetachedSignature` or + `ReadArmoredKeyRing` rather than comparing bytes, except in the golden test. + `cmd/gpgkms` tests swap the global `newSigner`, so they must not call + `t.Parallel()`. + +## Anti-patterns + +- **Changing the fingerprint or exported key bytes.** Never change how `Created`, + the key packet or the self-signature are built, and never edit + `compat_test.go`'s `coderCoderEntity` or the golden files to make a test pass. + Every consumer has published and pinned the current key; a change forces a key + re-publication. If a dependency update changes the golden output, stop and + report it. +- **Adding non-deterministic or extra signature data** (salt notations, + random-based signing, new subpackets) to release signatures. Older verifiers + and the Terraform Registry consume them. +- **Supporting more KMS algorithms or hashes casually.** OpenPGP v4 RSA uses + PKCS#1 v1.5, and `KMSSigner` signs only SHA-256 digests; widening this needs a + security review. +- **Unpinned tooling or actions.** Actions are pinned by commit SHA with a + version comment, checkouts use `persist-credentials: false`, workflow + permissions stay `contents: read`, and tools run at exact versions: Go tools + through `tools/go.mod`, the rest through `ci.yml`'s `env`. actionlint cannot + move into `tools/go.mod` because of a dependency conflict (see the comment in + `ci.yml`). +- **New dependencies.** Each one enters a release-signing job. Prefer the + standard library; ask before adding a module. + +## Code Style + +- `gofmt` and `goimports` with `github.com/coder/gpgkms` as the local import + prefix: standard library, third-party, then local imports, each group + separated by a blank line. +- Every exported identifier has a doc comment that starts with its name + (revive `exported`). Comments explain why, not what. +- Keep the package flat: library in the root, CLI in `cmd/gpgkms`. Keep + `README.md`, the `cmd/gpgkms` package doc and the `usage` string in sync when + flags change. + +## Commit and Pull Request Guidelines + +Before committing, run and pass: `gofmt -l .` (no output), `go vet ./...`, +`go test -race -shuffle=on -count=1 ./...`, `go mod tidy -diff` (root and +`tools/`), golangci-lint, +and govulncheck. Run actionlint and zizmor when touching `.github/`. + +Commit messages use `type: short imperative summary`, lowercase, as in the +history: `deps:` for dependency bumps (Dependabot uses it for Go modules), +`ci:` for workflow and Actions changes, `test:` for tests, and `feat:`, `fix:`, +`docs:` otherwise. PRs are squash-merged, so the PR title becomes the commit +subject. + +PR descriptions must say: + +- what changed and why; +- whether the exported public key or fingerprint can change (normally: "no, + golden and compat tests pass unchanged"); +- for dependency bumps, that the golden test still passes; +- the validation you ran. + +Every PR is reviewed by `@coder/security`. Do not open a PR unless asked. diff --git a/README.md b/README.md index 35c1512..8108b47 100644 --- a/README.md +++ b/README.md @@ -23,11 +23,11 @@ go tool gpgkms sign IDENTITY -out SHA256SUMS.sig -armor=false SHA256SUMS | Flag | | |---|---| -| `-key` | CryptoKeyVersion, e.g. `projects/p/locations/l/keyRings/r/cryptoKeys/k/cryptoKeyVersions/1`. Algorithm `RSA_SIGN_PKCS1_4096_SHA256`. | +| `-key` | CryptoKeyVersion, e.g. `projects/p/locations/l/keyRings/r/cryptoKeys/k/cryptoKeyVersions/1`. Algorithm `RSA_SIGN_PKCS1_4096_SHA256`, protection level `HSM` (software and external keys are rejected). | | `-name`, `-comment`, `-email` | OpenPGP user ID. | | `-created` | Key creation time (RFC 3339). **Part of the fingerprint: never change it.** | | `-lifetime` | Validity from `-created` (Go duration, e.g. `35040h`). 0 = never expires. | -| `-fingerprint` | Fail unless the derived key has this fingerprint. Use it in CI to pin the identity. | +| `-fingerprint` | Fail unless the derived key has this fingerprint. Use it in CI to pin the key. The fingerprint covers only `-key` and `-created`, not the user ID or `-lifetime`. | `sign` writes an ASCII-armored signature by default; `-armor=false` writes a binary one, which the Terraform Registry requires for `SHA256SUMS.sig`. diff --git a/cmd/gpgkms/main.go b/cmd/gpgkms/main.go index 74c3f73..30d1159 100644 --- a/cmd/gpgkms/main.go +++ b/cmd/gpgkms/main.go @@ -15,8 +15,10 @@ // is a CryptoKeyVersion resource name with the algorithm // RSA_SIGN_PKCS1_4096_SHA256. -created is part of the fingerprint and must // never change for a key. -fingerprint makes the command fail unless the -// derived key has exactly that fingerprint, which pins the identity in CI. -// Credentials come from Application Default Credentials. +// derived key has exactly that fingerprint. The fingerprint covers only the KMS +// public key and -created, not -name, -comment, -email or -lifetime, so it pins +// the key, not the whole published identity. Credentials come from +// Application Default Credentials. package main import ( @@ -29,7 +31,10 @@ import ( "fmt" "io" "os" + "os/signal" + "path/filepath" "strings" + "syscall" "time" "github.com/ProtonMail/go-crypto/openpgp" @@ -38,7 +43,11 @@ import ( ) func main() { - if err := run(context.Background(), os.Args[1:], os.Stdout, os.Stderr); err != nil { + // Cancel in-flight KMS requests when the CI job is cancelled. + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + err := run(ctx, os.Args[1:], os.Stdout, os.Stderr) + stop() + if err != nil { fmt.Fprintln(os.Stderr, "gpgkms:", err) os.Exit(1) } @@ -88,7 +97,7 @@ func (f *identityFlags) register(fs *flag.FlagSet) { fs.StringVar(&f.email, "email", "", "OpenPGP user ID email") fs.StringVar(&f.created, "created", "", "OpenPGP key creation time, RFC 3339 (part of the fingerprint: never change it)") fs.DurationVar(&f.lifetime, "lifetime", 0, "key validity from -created (0 = never expires)") - fs.StringVar(&f.fingerprint, "fingerprint", "", "fail unless the derived key has this fingerprint (hex)") + fs.StringVar(&f.fingerprint, "fingerprint", "", "fail unless the derived key has this fingerprint (hex; covers -key and -created, not the user ID or -lifetime)") } func (f *identityFlags) entity(ctx context.Context, stderr io.Writer) (*openpgp.Entity, error) { @@ -179,14 +188,63 @@ func runSign(ctx context.Context, args []string, stderr io.Writer) error { return fmt.Errorf("open file to sign: %w", err) } defer message.Close() + if err := checkNotSameFile(message, *outPath); err != nil { + return err + } var out bytes.Buffer if err := gpgkms.Sign(&out, e, message, gpgkms.SignOptions{Prepend: prepend, Armored: *armored}); err != nil { return err } - // #nosec G306 -- detached signatures are public. - if err := os.WriteFile(*outPath, out.Bytes(), 0o644); err != nil { + if err := writeFileAtomic(*outPath, out.Bytes()); err != nil { return fmt.Errorf("write signature: %w", err) } return nil } + +// checkNotSameFile refuses an -out that is the file being signed, which would +// replace the release artifact with its own signature. +func checkNotSameFile(message *os.File, outPath string) error { + outInfo, err := os.Stat(outPath) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return fmt.Errorf("stat -out: %w", err) + } + msgInfo, err := message.Stat() + if err != nil { + return fmt.Errorf("stat file to sign: %w", err) + } + if os.SameFile(msgInfo, outInfo) { + return fmt.Errorf("-out %s is the file to sign", outPath) + } + return nil +} + +// writeFileAtomic writes data to a temporary file next to path and renames it +// over path. Readers never see a partial signature, and an existing symlink at +// path is replaced instead of followed. +func writeFileAtomic(path string, data []byte) (err error) { + tmp, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".tmp-*") + if err != nil { + return err + } + defer func() { + if err != nil { + _ = tmp.Close() + _ = os.Remove(tmp.Name()) + } + }() + if _, err = tmp.Write(data); err != nil { + return err + } + // #nosec G302 -- detached signatures are public; CreateTemp makes the file 0600. + if err = tmp.Chmod(0o644); err != nil { + return err + } + if err = tmp.Close(); err != nil { + return err + } + return os.Rename(tmp.Name(), path) +} diff --git a/cmd/gpgkms/main_test.go b/cmd/gpgkms/main_test.go index c1faf2d..0999548 100644 --- a/cmd/gpgkms/main_test.go +++ b/cmd/gpgkms/main_test.go @@ -9,10 +9,12 @@ import ( "encoding/hex" "os" "path/filepath" + "runtime" "strings" "testing" "github.com/ProtonMail/go-crypto/openpgp" + "github.com/ProtonMail/go-crypto/openpgp/packet" ) func useTestSigner(t *testing.T) { @@ -81,15 +83,157 @@ func TestFingerprintPin(t *testing.T) { func TestRequiredFlags(t *testing.T) { useTestSigner(t) - for name, args := range map[string][]string{ - "no key": {"public-key", "-name", "x", "-created", "2026-11-17T00:00:00Z"}, - "no created": {"public-key", "-key", "k", "-name", "x"}, - "bad time": {"public-key", "-key", "k", "-name", "x", "-created", "yesterday"}, - "no out": append(append([]string{"sign"}, identityArgs...), "file"), - "unknown": {"frobnicate"}, + file := writeTestFile(t, "SHA256SUMS", "abc file.zip\n") + for name, tc := range map[string]struct { + args []string + want string + }{ + "no key": {[]string{"public-key", "-name", "x", "-created", "2026-11-17T00:00:00Z"}, "-key is required"}, + "no created": {[]string{"public-key", "-key", "k", "-name", "x"}, "-created is required"}, + "bad time": {[]string{"public-key", "-key", "k", "-name", "x", "-created", "yesterday"}, "-created:"}, + "no out": {append(append([]string{"sign"}, identityArgs...), file), "-out is required"}, + "no file": {append(append([]string{"sign"}, identityArgs...), "-out", file+".sig"), "exactly one file"}, + "unknown": {[]string{"frobnicate"}, "unknown command"}, } { - if err := run(context.Background(), args, &bytes.Buffer{}, &bytes.Buffer{}); err == nil { - t.Errorf("%s: want error", name) + err := run(context.Background(), tc.args, &bytes.Buffer{}, &bytes.Buffer{}) + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Errorf("%s: err = %v, want %q", name, err, tc.want) } } } + +// writeTestFile writes content to name in a new temporary directory. +func writeTestFile(t *testing.T, name, content string) string { + t.Helper() + path := filepath.Join(t.TempDir(), name) + if err := os.WriteFile(path, []byte(content), 0o600); err != nil { + t.Fatal(err) + } + return path +} + +// publicKey runs public-key with identityArgs and returns the parsed key. +func publicKey(t *testing.T) openpgp.EntityList { + t.Helper() + var pub bytes.Buffer + if err := run(context.Background(), append([]string{"public-key"}, identityArgs...), &pub, &bytes.Buffer{}); err != nil { + t.Fatal(err) + } + keyring, err := openpgp.ReadArmoredKeyRing(&pub) + if err != nil { + t.Fatal(err) + } + return keyring +} + +func TestBinaryPublicKey(t *testing.T) { + useTestSigner(t) + var pub bytes.Buffer + if err := run(context.Background(), append([]string{"public-key", "-armor=false"}, identityArgs...), &pub, &bytes.Buffer{}); err != nil { + t.Fatal(err) + } + if bytes.HasPrefix(pub.Bytes(), []byte("-----BEGIN")) { + t.Fatal("-armor=false public key is armored") + } + keyring, err := openpgp.ReadKeyRing(&pub) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(keyring[0].PrimaryKey.Fingerprint, publicKey(t)[0].PrimaryKey.Fingerprint) { + t.Fatal("binary and armored public keys differ") + } +} + +func TestSignArmoredWithPrepend(t *testing.T) { + useTestSigner(t) + message := "abc file.zip\n" + file := writeTestFile(t, "checksums.txt", message) + + // An old software key, as used before a rotation to KMS. + oldKey, err := openpgp.NewEntity("Old Key", "", "old@example.com", &packet.Config{RSABits: 2048, Algorithm: packet.PubKeyAlgoRSA}) + if err != nil { + t.Fatal(err) + } + var oldSig bytes.Buffer + if err := openpgp.DetachSign(&oldSig, oldKey, strings.NewReader(message), nil); err != nil { + t.Fatal(err) + } + prependPath := file + ".old.sig" + if err := os.WriteFile(prependPath, oldSig.Bytes(), 0o600); err != nil { + t.Fatal(err) + } + + sigPath := file + ".asc" + args := append(append([]string{"sign"}, identityArgs...), "-prepend", prependPath, "-out", sigPath, file) + if err := run(context.Background(), args, &bytes.Buffer{}, &bytes.Buffer{}); err != nil { + t.Fatal(err) + } + sig, err := os.ReadFile(sigPath) + if err != nil { + t.Fatal(err) + } + if !bytes.HasPrefix(sig, []byte("-----BEGIN PGP SIGNATURE-----")) { + t.Fatalf("signature is not armored by default:\n%s", sig) + } + newKey := publicKey(t) + for name, keyring := range map[string]openpgp.EntityList{"old": {oldKey}, "new": newKey} { + if _, err := openpgp.CheckArmoredDetachedSignature(keyring, strings.NewReader(message), bytes.NewReader(sig), nil); err != nil { + t.Errorf("%s key: %v", name, err) + } + } +} + +func TestSignRefusesToOverwriteInput(t *testing.T) { + useTestSigner(t) + file := writeTestFile(t, "SHA256SUMS", "abc file.zip\n") + link := file + ".sig" + if err := os.Symlink(file, link); err != nil { + t.Skipf("symlinks unsupported: %v", err) + } + for _, out := range []string{file, link} { + args := append(append([]string{"sign"}, identityArgs...), "-out", out, file) + err := run(context.Background(), args, &bytes.Buffer{}, &bytes.Buffer{}) + if err == nil || !strings.Contains(err.Error(), "is the file to sign") { + t.Errorf("-out %s: err = %v", out, err) + } + } + if got, _ := os.ReadFile(file); string(got) != "abc file.zip\n" { + t.Fatalf("input changed: %q", got) + } +} + +func TestSignReplacesSymlinkAtomically(t *testing.T) { + useTestSigner(t) + file := writeTestFile(t, "SHA256SUMS", "abc file.zip\n") + dir := filepath.Dir(file) + victim := writeTestFile(t, "victim", "do not overwrite") + sigPath := filepath.Join(dir, "SHA256SUMS.sig") + if err := os.Symlink(victim, sigPath); err != nil { + t.Skipf("symlinks unsupported: %v", err) + } + + args := append(append([]string{"sign"}, identityArgs...), "-armor=false", "-out", sigPath, file) + if err := run(context.Background(), args, &bytes.Buffer{}, &bytes.Buffer{}); err != nil { + t.Fatal(err) + } + if got, _ := os.ReadFile(victim); string(got) != "do not overwrite" { + t.Fatalf("symlink target overwritten: %q", got) + } + info, err := os.Lstat(sigPath) + if err != nil { + t.Fatal(err) + } + if !info.Mode().IsRegular() { + t.Fatalf("-out is %v, want a regular file", info.Mode()) + } + if runtime.GOOS != "windows" && info.Mode().Perm() != 0o644 { + t.Fatalf("-out mode %v, want 0644 (signatures are public)", info.Mode().Perm()) + } + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + if len(entries) != 2 { + t.Fatalf("leftover files in %s: %v", dir, entries) + } +} diff --git a/gpgkms.go b/gpgkms.go index a2a8fb8..25606ac 100644 --- a/gpgkms.go +++ b/gpgkms.go @@ -44,8 +44,15 @@ func (id Identity) validate() error { if id.Created.IsZero() { return errors.New("identity creation time is required (it is part of the fingerprint)") } - if id.Lifetime < 0 || id.Lifetime/time.Second > 1<<32-1 { - return fmt.Errorf("invalid key lifetime %s", id.Lifetime) + // OpenPGP v4 stores the creation time as unsigned 32-bit seconds since the + // epoch; go-crypto truncates out-of-range times without an error. + if created := id.Created.Unix(); created < 0 || created > 1<<32-1 { + return fmt.Errorf("identity creation time %s is outside the OpenPGP range (1970 to 2106)", id.Created) + } + // The lifetime is stored in whole seconds, and 0 means "never expires", so a + // fraction (500ms) would silently become a key that never expires. + if id.Lifetime < 0 || id.Lifetime%time.Second != 0 || id.Lifetime/time.Second > 1<<32-1 { + return fmt.Errorf("invalid key lifetime %s: want whole seconds in [0, 2^32-1]", id.Lifetime) } return nil } @@ -164,21 +171,28 @@ func Sign(w io.Writer, e *openpgp.Entity, message io.Reader, opts SignOptions) e } // ValidateSignatures checks that b is a binary stream of one or more OpenPGP -// signature packets and nothing else. +// binary-document signature packets (type 0x00, what `gpg --detach-sign` +// makes) and nothing else. It does not check which data they sign. Other +// packets or signature types make gpg fail the file, or check only the first +// signature, so the new signature appended by Sign would be ignored. func ValidateSignatures(b []byte) error { - reader := packet.NewReader(bytes.NewReader(b)) + // packet.Read, not packet.Reader.Next: Next silently skips unknown, + // unsupported and marker packets, which would then be copied into the + // output and make gpg reject the whole signature file. + r := bytes.NewReader(b) count := 0 - for { - p, err := reader.Next() - if errors.Is(err, io.EOF) { - break - } + for r.Len() > 0 { + p, err := packet.Read(r) if err != nil { - return fmt.Errorf("parse packet (the signature must be binary, not armored): %w", err) + return fmt.Errorf("parse packet %d (the signature must be binary, not armored): %w", count+1, err) } - if _, ok := p.(*packet.Signature); !ok { + sig, ok := p.(*packet.Signature) + if !ok { return fmt.Errorf("unexpected %T packet, want only signatures", p) } + if sig.SigType != packet.SigTypeBinary { + return fmt.Errorf("signature %d has type %#x, want a binary document signature (0x00)", count+1, uint8(sig.SigType)) + } count++ } if count == 0 { diff --git a/gpgkms_test.go b/gpgkms_test.go index 99d8a35..646e947 100644 --- a/gpgkms_test.go +++ b/gpgkms_test.go @@ -3,6 +3,8 @@ package gpgkms import ( "bytes" "crypto" + "crypto/ecdsa" + "crypto/elliptic" "crypto/rand" "crypto/rsa" "errors" @@ -122,11 +124,93 @@ func TestIdentityValidation(t *testing.T) { "no created": {Name: "x"}, "negative": {Name: "x", Created: time.Unix(1, 0), Lifetime: -time.Hour}, "too long": {Name: "x", Created: time.Unix(1, 0), Lifetime: (1 << 32) * time.Second}, + // Truncating to whole seconds would make these "never expires". + "sub-second": {Name: "x", Created: time.Unix(1, 0), Lifetime: 500 * time.Millisecond}, + "fraction": {Name: "x", Created: time.Unix(1, 0), Lifetime: 1500 * time.Millisecond}, + // OpenPGP stores the creation time as uint32 seconds, which would wrap. + "before 1970": {Name: "x", Created: time.Date(1969, 12, 31, 23, 59, 59, 0, time.UTC)}, + "after 2106": {Name: "x", Created: time.Date(2107, 1, 1, 0, 0, 0, 0, time.UTC)}, } { if _, err := NewEntity(newTestSigner(t), id); err == nil { t.Errorf("%s: want error", name) } } + + // The extremes of the valid ranges still work. + for name, id := range map[string]Identity{ + "max lifetime": {Name: "x", Created: time.Unix(1, 0), Lifetime: (1<<32 - 1) * time.Second}, + "max created": {Name: "x", Created: time.Unix(1<<32-1, 0)}, + } { + e, err := NewEntity(newTestSigner(t), id) + if err != nil { + t.Errorf("%s: %v", name, err) + continue + } + if !e.PrimaryKey.CreationTime.Equal(id.Created) { + t.Errorf("%s: creation time %v, want %v", name, e.PrimaryKey.CreationTime, id.Created) + } + } +} + +func TestNewEntityRejectsNonRSA(t *testing.T) { + t.Parallel() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + must(t, err) + if _, err := NewEntity(key, testIdentity); err == nil || !strings.Contains(err.Error(), "want RSA") { + t.Fatalf("err = %v", err) + } +} + +// detachSign returns a binary detached signature over message made by e. +func detachSign(t *testing.T, e *openpgp.Entity, message string) []byte { + t.Helper() + var buf bytes.Buffer + must(t, openpgp.DetachSign(&buf, e, strings.NewReader(message), nil)) + return buf.Bytes() +} + +func TestValidateSignatures(t *testing.T) { + t.Parallel() + e, err := NewEntity(newTestSigner(t), testIdentity) + must(t, err) + sig := detachSign(t, e, "x") + + var textSig bytes.Buffer + must(t, openpgp.DetachSignText(&textSig, e, strings.NewReader("x"), nil)) + var certSig bytes.Buffer + must(t, e.Identities[testUserID].SelfSignature.Serialize(&certSig)) + var pubKey bytes.Buffer + must(t, e.PrimaryKey.Serialize(&pubKey)) + // New-format packet headers: 0xC0 | tag, then a one-octet length. + unknownPacket := []byte{0xC0 | 60, 4, 'j', 'u', 'n', 'k'} + markerPacket := []byte{0xC0 | 10, 3, 'P', 'G', 'P'} + + for name, b := range map[string][]byte{ + "one": sig, + "two": append(append([]byte{}, sig...), sig...), + } { + if err := ValidateSignatures(b); err != nil { + t.Errorf("%s: %v", name, err) + } + } + + for name, b := range map[string][]byte{ + "empty": nil, + "truncate": sig[:len(sig)-1], + // packet.Reader.Next silently skips these, and gpg rejects the output. + "unknown packet after": append(append([]byte{}, sig...), unknownPacket...), + "marker packet before": append(append([]byte{}, markerPacket...), sig...), + "public key packet": pubKey.Bytes(), + // gpg checks only the first signature when text and binary ones are + // mixed, so the KMS signature would go unchecked. + "text signature": textSig.Bytes(), + // gpg reports a BAD signature, failing the whole file. + "certification signature": certSig.Bytes(), + } { + if err := ValidateSignatures(b); err == nil { + t.Errorf("%s: want error", name) + } + } } func TestFingerprintDependsOnCreated(t *testing.T) { diff --git a/kms.go b/kms.go index 5cf4a6e..5d58f8f 100644 --- a/kms.go +++ b/kms.go @@ -10,6 +10,7 @@ import ( "encoding/pem" "fmt" "io" + "time" "google.golang.org/api/cloudkms/v1" "google.golang.org/api/option" @@ -19,6 +20,15 @@ import ( // signatures are PKCS#1 v1.5 (not PSS), and gpgkms always hashes with SHA-256. const KMSAlgorithm = "RSA_SIGN_PKCS1_4096_SHA256" +// kmsRequestTimeout bounds each Cloud KMS call, so a hung request fails the +// release job quickly instead of running until the CI job's own timeout. +const kmsRequestTimeout = time.Minute + +// hsmProtectionLevels are the Cloud KMS protection levels accepted: the key +// material must stay inside an HSM. SOFTWARE keys and external (EKM) keys are +// rejected. +var hsmProtectionLevels = map[string]bool{"HSM": true, "HSM_SINGLE_TENANT": true} + // KMSSigner is a crypto.Signer backed by a Cloud KMS CryptoKeyVersion with the // algorithm KMSAlgorithm. type KMSSigner struct { @@ -31,8 +41,12 @@ type KMSSigner struct { // NewKMSSigner returns a signer for the CryptoKeyVersion name, e.g. // projects/p/locations/l/keyRings/r/cryptoKeys/k/cryptoKeyVersions/1. // Credentials come from Application Default Credentials unless opts override -// them. The caller needs roles/cloudkms.publicKeyViewer, and +// them. The key must have the algorithm KMSAlgorithm and an HSM protection +// level. The caller needs roles/cloudkms.publicKeyViewer, and // roles/cloudkms.signer to sign. +// +// ctx is used for every later Sign call too, because crypto.Signer has no +// context parameter; each KMS request is additionally limited to one minute. func NewKMSSigner(ctx context.Context, name string, opts ...option.ClientOption) (*KMSSigner, error) { svc, err := cloudkms.NewService(ctx, opts...) if err != nil { @@ -40,13 +54,18 @@ func NewKMSSigner(ctx context.Context, name string, opts ...option.ClientOption) } versions := svc.Projects.Locations.KeyRings.CryptoKeys.CryptoKeyVersions - resp, err := versions.GetPublicKey(name).Context(ctx).Do() + reqCtx, cancel := context.WithTimeout(ctx, kmsRequestTimeout) + defer cancel() + resp, err := versions.GetPublicKey(name).Context(reqCtx).Do() if err != nil { return nil, fmt.Errorf("get public key for %q: %w", name, err) } if resp.Algorithm != KMSAlgorithm { return nil, fmt.Errorf("key %q has algorithm %s, want %s", name, resp.Algorithm, KMSAlgorithm) } + if !hsmProtectionLevels[resp.ProtectionLevel] { + return nil, fmt.Errorf("key %q has protection level %q, want HSM", name, resp.ProtectionLevel) + } block, _ := pem.Decode([]byte(resp.Pem)) if block == nil { return nil, fmt.Errorf("decode public key PEM for %q", name) @@ -67,14 +86,20 @@ func (s *KMSSigner) Public() crypto.PublicKey { return s.pub } -// Sign implements crypto.Signer. It only signs SHA-256 digests. +// Sign implements crypto.Signer. It only makes PKCS#1 v1.5 signatures of +// SHA-256 digests. func (s *KMSSigner) Sign(_ io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) { + if _, ok := opts.(*rsa.PSSOptions); ok { + return nil, fmt.Errorf("RSA-PSS requested: %s only makes PKCS#1 v1.5 signatures", KMSAlgorithm) + } if opts.HashFunc() != crypto.SHA256 || len(digest) != sha256.Size { return nil, fmt.Errorf("unsupported hash %v: %s only signs SHA-256 digests", opts.HashFunc(), KMSAlgorithm) } + ctx, cancel := context.WithTimeout(s.ctx, kmsRequestTimeout) + defer cancel() resp, err := s.svc.AsymmetricSign(s.name, &cloudkms.AsymmetricSignRequest{ Digest: &cloudkms.Digest{Sha256: base64.StdEncoding.EncodeToString(digest)}, - }).Context(s.ctx).Do() + }).Context(ctx).Do() if err != nil { return nil, fmt.Errorf("cloud KMS asymmetric sign: %w", err) } diff --git a/kms_test.go b/kms_test.go new file mode 100644 index 0000000..b022e05 --- /dev/null +++ b/kms_test.go @@ -0,0 +1,203 @@ +package gpgkms + +import ( + "bytes" + "context" + "crypto" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/rsa" + "crypto/sha256" + "crypto/sha512" + "crypto/x509" + "encoding/base64" + "encoding/json" + "encoding/pem" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/ProtonMail/go-crypto/openpgp" + "google.golang.org/api/cloudkms/v1" + "google.golang.org/api/option" +) + +const testKeyVersion = "projects/p/locations/l/keyRings/r/cryptoKeys/k/cryptoKeyVersions/1" + +// fakeKMS serves the two Cloud KMS endpoints KMSSigner uses, backed by a +// software RSA key. +type fakeKMS struct { + publicKey cloudkms.PublicKey + // sign makes the signature returned by asymmetricSign. + sign func(r *http.Request, digest []byte) []byte +} + +func newFakeKMS(t *testing.T) *fakeKMS { + t.Helper() + key := newTestSigner(t).(opaqueSigner).key + der, err := x509.MarshalPKIXPublicKey(&key.PublicKey) + must(t, err) + return &fakeKMS{ + publicKey: cloudkms.PublicKey{ + Name: testKeyVersion, + Algorithm: KMSAlgorithm, + ProtectionLevel: "HSM", + Pem: string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: der})), + }, + sign: func(_ *http.Request, digest []byte) []byte { + sig, err := rsa.SignPKCS1v15(nil, key, crypto.SHA256, digest) + if err != nil { + panic(err) + } + return sig + }, + } +} + +// signer starts the fake server and returns a KMSSigner connected to it. +func (f *fakeKMS) signer(ctx context.Context, t *testing.T) (*KMSSigner, error) { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var resp any + switch { + case r.Method == http.MethodGet && r.URL.Path == "/v1/"+testKeyVersion+"/publicKey": + resp = &f.publicKey + case r.Method == http.MethodPost && r.URL.Path == "/v1/"+testKeyVersion+":asymmetricSign": + var req cloudkms.AsymmetricSignRequest + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + digest, err := base64.StdEncoding.DecodeString(req.Digest.Sha256) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + resp = &cloudkms.AsymmetricSignResponse{Signature: base64.StdEncoding.EncodeToString(f.sign(r, digest))} + default: + http.NotFound(w, r) + return + } + _ = json.NewEncoder(w).Encode(resp) + })) + t.Cleanup(srv.Close) + return NewKMSSigner(ctx, testKeyVersion, option.WithEndpoint(srv.URL+"/"), option.WithHTTPClient(srv.Client())) +} + +func TestKMSSignerSignsVerifiableSignatures(t *testing.T) { + t.Parallel() + for _, level := range []string{"HSM", "HSM_SINGLE_TENANT"} { + f := newFakeKMS(t) + f.publicKey.ProtectionLevel = level + signer, err := f.signer(context.Background(), t) + must(t, err) + + e, err := NewEntity(signer, testIdentity) + must(t, err) + var sig bytes.Buffer + must(t, Sign(&sig, e, strings.NewReader("release"), SignOptions{})) + if _, err := openpgp.CheckDetachedSignature(openpgp.EntityList{e}, strings.NewReader("release"), &sig, nil); err != nil { + t.Errorf("%s: %v", level, err) + } + } +} + +func TestKMSSignerRejectsKey(t *testing.T) { + t.Parallel() + ecKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + must(t, err) + ecDER, err := x509.MarshalPKIXPublicKey(&ecKey.PublicKey) + must(t, err) + ecPEM := string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: ecDER})) + + for name, tc := range map[string]struct { + edit func(*cloudkms.PublicKey) + want string + }{ + "wrong algorithm": {func(k *cloudkms.PublicKey) { k.Algorithm = "RSA_SIGN_PSS_4096_SHA256" }, "algorithm"}, + "software key": {func(k *cloudkms.PublicKey) { k.ProtectionLevel = "SOFTWARE" }, "protection level"}, + "external key": {func(k *cloudkms.PublicKey) { k.ProtectionLevel = "EXTERNAL" }, "protection level"}, + "no protection set": {func(k *cloudkms.PublicKey) { k.ProtectionLevel = "" }, "protection level"}, + "bad PEM": {func(k *cloudkms.PublicKey) { k.Pem = "not PEM" }, "decode public key PEM"}, + "bad DER": {func(k *cloudkms.PublicKey) { k.Pem = "-----BEGIN PUBLIC KEY-----\nAAAA\n-----END PUBLIC KEY-----\n" }, "parse public key"}, + "not RSA": {func(k *cloudkms.PublicKey) { k.Pem = ecPEM }, "want RSA"}, + } { + f := newFakeKMS(t) + tc.edit(&f.publicKey) + if _, err := f.signer(context.Background(), t); err == nil || !strings.Contains(err.Error(), tc.want) { + t.Errorf("%s: err = %v, want %q", name, err, tc.want) + } + } +} + +func TestKMSSignerRejectsUnsupportedSignOpts(t *testing.T) { + t.Parallel() + signer, err := newFakeKMS(t).signer(context.Background(), t) + must(t, err) + sha256Digest := sha256.Sum256([]byte("x")) + sha512Digest := sha512.Sum512([]byte("x")) + + for name, tc := range map[string]struct { + digest []byte + opts crypto.SignerOpts + }{ + "PSS": {sha256Digest[:], &rsa.PSSOptions{Hash: crypto.SHA256}}, + "SHA-512": {sha512Digest[:], crypto.SHA512}, + "short digest": {sha256Digest[:31], crypto.SHA256}, + } { + if _, err := signer.Sign(rand.Reader, tc.digest, tc.opts); err == nil { + t.Errorf("%s: want error", name) + } + } + if _, err := signer.Sign(rand.Reader, sha256Digest[:], crypto.SHA256); err != nil { + t.Fatalf("SHA-256 PKCS#1 v1.5: %v", err) + } +} + +func TestKMSSignerRejectsCorruptSignature(t *testing.T) { + t.Parallel() + f := newFakeKMS(t) + sign := f.sign + f.sign = func(r *http.Request, digest []byte) []byte { + sig := sign(r, digest) + sig[len(sig)-1] ^= 1 + return sig + } + signer, err := f.signer(context.Background(), t) + must(t, err) + digest := sha256.Sum256([]byte("x")) + if _, err := signer.Sign(rand.Reader, digest[:], crypto.SHA256); err == nil || !strings.Contains(err.Error(), "verify Cloud KMS signature") { + t.Fatalf("err = %v", err) + } +} + +func TestKMSSignerStopsWhenContextEnds(t *testing.T) { + t.Parallel() + f := newFakeKMS(t) + f.sign = func(r *http.Request, _ []byte) []byte { + <-r.Context().Done() // hang until the client gives up + return nil + } + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + signer, err := f.signer(ctx, t) + must(t, err) + + done := make(chan error, 1) + go func() { + digest := sha256.Sum256([]byte("x")) + _, err := signer.Sign(rand.Reader, digest[:], crypto.SHA256) + done <- err + }() + select { + case err := <-done: + if err == nil { + t.Fatal("want error from a hung KMS request") + } + case <-time.After(time.Minute): + t.Fatal("Sign did not return after its context ended") + } +}