From c70227d171d52a0bf15db248f2a872c5243fc182 Mon Sep 17 00:00:00 2001 From: Marko Petzold Date: Tue, 3 Nov 2026 14:20:01 +0100 Subject: [PATCH] Implement OpenPGP signing tool with Cloud KMS integration - Added `tools/sign-openpgp` for creating detached OpenPGP signatures. - Integrated Cloud KMS for signing operations using asymmetric keys. - Implemented unit tests for KMS signing and verification processes. - Updated GitHub Actions workflow to include tests for the signing tool. - Enhanced README with usage instructions for the new signing tool. --- .github/workflows/selftest.yml | 27 ++ README.md | 22 ++ tools/sign-openpgp/go.mod | 15 + tools/sign-openpgp/go.sum | 12 + tools/sign-openpgp/kms.go | 185 ++++++++++++ tools/sign-openpgp/kms_test.go | 174 +++++++++++ tools/sign-openpgp/main.go | 492 ++++++++++++++++++++++++++++++++ tools/sign-openpgp/main_test.go | 136 +++++++++ 8 files changed, 1063 insertions(+) create mode 100644 tools/sign-openpgp/go.mod create mode 100644 tools/sign-openpgp/go.sum create mode 100644 tools/sign-openpgp/kms.go create mode 100644 tools/sign-openpgp/kms_test.go create mode 100644 tools/sign-openpgp/main.go create mode 100644 tools/sign-openpgp/main_test.go diff --git a/.github/workflows/selftest.yml b/.github/workflows/selftest.yml index 3e1ca5c..3635ed1 100644 --- a/.github/workflows/selftest.yml +++ b/.github/workflows/selftest.yml @@ -82,6 +82,33 @@ jobs: exit 1 fi + # The release signer callers run from their harness checkout + # (tools/sign-openpgp): its tests sign with a development key and check the + # signatures with gpgv, as an appliance or device does. + sign-openpgp: + runs-on: ubuntu-latest + timeout-minutes: 10 + defaults: + run: + working-directory: tools/sign-openpgp + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: tools/sign-openpgp/go.mod + cache: false + - name: gofmt, go mod tidy, go vet + run: | + test -z "$(gofmt -l .)" + go mod tidy -diff + go vet ./... + - name: unit tests + run: | + command -v gpgv + go test -race -count=1 ./... + gate-pass: uses: ./.github/workflows/go-gate.yml with: diff --git a/README.md b/README.md index 688f68e..c65d936 100644 --- a/README.md +++ b/README.md @@ -109,6 +109,28 @@ them from [templates/workflows](templates/workflows). A change to the logic is made once here and reaches every repository when `v1` moves after a green self-test; a change to triggers or settings needs a pull request per repository. +## Release signatures + +[tools/sign-openpgp](tools/sign-openpgp) makes the detached OpenPGP signatures +(`.asc`) that an install or update checks before it runs or uses what it +downloaded — with `gpgv` or `sqv`, which every apt-based host has. The private +key stays in Cloud KMS (`-kms-key`, Application Default Credentials: the +release job's workload identity) or OpenBao transit (`-signer`); the tool +hashes locally and sends only digests. A release job runs it from its harness +checkout (add `tools/sign-openpgp` to the sparse checkout, set up Go from its +`go.mod`): + +```sh +cd "$HARNESS/tools/sign-openpgp" +go run . sign -cert "$CERT" -kms-key "$KMS_KEY_VERSION" FILE... # writes FILE.asc +go run . verify -cert "$CERT" FILE... +``` + +`cert` makes the public certificate once (`-uid` names it), `export` its base64 +form for a script to embed, `fingerprint` the fingerprint the operator docs +publish, `keygen` a development key for tests. The commands are documented at +the top of [main.go](tools/sign-openpgp/main.go). + ## Protected main branch Each repository protects `main` with a ruleset: changes only through pull diff --git a/tools/sign-openpgp/go.mod b/tools/sign-openpgp/go.mod new file mode 100644 index 0000000..cd98c1a --- /dev/null +++ b/tools/sign-openpgp/go.mod @@ -0,0 +1,15 @@ +module github.com/ironflock/workflows/tools/sign-openpgp + +go 1.27.3 + +require ( + github.com/ProtonMail/go-crypto v1.5.2 + golang.org/x/oauth2 v0.37.0 +) + +require ( + cloud.google.com/go/compute/metadata v0.3.0 // indirect + github.com/cloudflare/circl v1.6.3 // indirect + golang.org/x/crypto v0.41.0 // indirect + golang.org/x/sys v0.35.0 // indirect +) diff --git a/tools/sign-openpgp/go.sum b/tools/sign-openpgp/go.sum new file mode 100644 index 0000000..489bf1b --- /dev/null +++ b/tools/sign-openpgp/go.sum @@ -0,0 +1,12 @@ +cloud.google.com/go/compute/metadata v0.3.0 h1:Tz+eQXMEqDIKRsmY3cHTL6FVaynIjX2QxYC4trgAKZc= +cloud.google.com/go/compute/metadata v0.3.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k= +github.com/ProtonMail/go-crypto v1.5.2 h1:cucYnvqcY7UOXVD//mSyjeaPY0SSN3v5cDkYPxumINk= +github.com/ProtonMail/go-crypto v1.5.2/go.mod h1:/RaSu30DaKO4RY+XdV/ACcCcZkGr7AhUIduq5sjzzCo= +github.com/cloudflare/circl v1.6.3 h1:9GPOhQGF9MCYUeXyMYlqTR6a5gTrgR/fBLXvUgtVcg8= +github.com/cloudflare/circl v1.6.3/go.mod h1:2eXP6Qfat4O/Yhh8BznvKnJ+uzEoTQ6jVKJRn81BiS4= +golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4= +golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc= +golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98= +golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58= +golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI= +golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= diff --git a/tools/sign-openpgp/kms.go b/tools/sign-openpgp/kms.go new file mode 100644 index 0000000..dfe652b --- /dev/null +++ b/tools/sign-openpgp/kms.go @@ -0,0 +1,185 @@ +package main + +// The Cloud KMS backend: -kms-key signs every digest +// with an asymmetric KMS key (RSA_SIGN_PKCS1_4096_SHA256, not exportable) +// through the KMS REST API, as the Application Default Credentials (in CI the +// workload identity credentials google-github-actions/auth writes). Only the +// SHA-256 digests leave this process; CRC32C checks guard both directions, as +// KMS recommends. + +import ( + "bytes" + "context" + "crypto/rsa" + "crypto/x509" + "encoding/base64" + "encoding/json" + "encoding/pem" + "errors" + "fmt" + "hash/crc32" + "io" + "net/http" + "strconv" + "time" + + "golang.org/x/oauth2" + "golang.org/x/oauth2/google" +) + +// kmsAPI is what the signer needs from Cloud KMS; the tests put a fake behind it. +type kmsAPI interface { + asymmetricSign(ctx context.Context, name string, digest []byte) ([]byte, error) + publicKey(ctx context.Context, name string) (*rsa.PublicKey, error) +} + +// newKMS returns the real client; a variable so the tests can replace it. +var newKMS = func(ctx context.Context) (kmsAPI, error) { + creds, err := google.FindDefaultCredentials(ctx, "https://www.googleapis.com/auth/cloudkms") + if err != nil { + return nil, fmt.Errorf("kms: no Google credentials: %w", err) + } + return &kmsREST{client: oauth2.NewClient(ctx, creds.TokenSource), endpoint: "https://cloudkms.googleapis.com/v1/"}, nil +} + +type kmsREST struct { + client *http.Client + endpoint string +} + +var crc32c = crc32.MakeTable(crc32.Castagnoli) + +func (k *kmsREST) call(ctx context.Context, method, path string, body, into any) error { + var in io.Reader + if body != nil { + data, err := json.Marshal(body) + if err != nil { + return err + } + in = bytes.NewReader(data) + } + ctx, cancel := context.WithTimeout(ctx, time.Minute) + defer cancel() + req, err := http.NewRequestWithContext(ctx, method, k.endpoint+path, in) + if err != nil { + return err + } + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + resp, err := k.client.Do(req) + if err != nil { + return fmt.Errorf("kms: %w", err) + } + defer func() { _ = resp.Body.Close() }() + data, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + if err != nil { + return fmt.Errorf("kms: %w", err) + } + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("kms: %s %s: %s: %s", method, path, resp.Status, bytes.TrimSpace(data)) + } + return json.Unmarshal(data, into) +} + +func (k *kmsREST) asymmetricSign(ctx context.Context, name string, digest []byte) ([]byte, error) { + var answer struct { + Signature string `json:"signature"` + SignatureCrc32c string `json:"signatureCrc32c"` + VerifiedDigestCrc32c bool `json:"verifiedDigestCrc32c"` + Name string `json:"name"` + } + request := map[string]any{ + "digest": map[string]string{"sha256": base64.StdEncoding.EncodeToString(digest)}, + "digestCrc32c": strconv.FormatUint(uint64(crc32.Checksum(digest, crc32c)), 10), + } + if err := k.call(ctx, http.MethodPost, name+":asymmetricSign", request, &answer); err != nil { + return nil, err + } + if !answer.VerifiedDigestCrc32c { + return nil, errors.New("kms: the digest was damaged on the way to KMS") + } + if answer.Name != name { + return nil, fmt.Errorf("kms: signed with %q, not %q", answer.Name, name) + } + sig, err := base64.StdEncoding.DecodeString(answer.Signature) + if err != nil { + return nil, fmt.Errorf("kms: the signature is not base64: %w", err) + } + if strconv.FormatUint(uint64(crc32.Checksum(sig, crc32c)), 10) != answer.SignatureCrc32c { + return nil, errors.New("kms: the signature was damaged on the way back") + } + return sig, nil +} + +func (k *kmsREST) publicKey(ctx context.Context, name string) (*rsa.PublicKey, error) { + var answer struct { + Pem string `json:"pem"` + Algorithm string `json:"algorithm"` + PemCrc32c string `json:"pemCrc32c"` + } + if err := k.call(ctx, http.MethodGet, name+"/publicKey", nil, &answer); err != nil { + return nil, err + } + if answer.Algorithm != "RSA_SIGN_PKCS1_4096_SHA256" { + return nil, fmt.Errorf("kms: %s is %s, want RSA_SIGN_PKCS1_4096_SHA256", name, answer.Algorithm) + } + if answer.PemCrc32c != "" && strconv.FormatUint(uint64(crc32.Checksum([]byte(answer.Pem), crc32c)), 10) != answer.PemCrc32c { + return nil, errors.New("kms: the public key was damaged on the way") + } + return parsePublicKeyPEM([]byte(answer.Pem), name) +} + +// kmsBackend signs with the KMS key, after checking that it is the key the +// certificate names (a rotated key version would sign for another cert). +func kmsBackend(name string, pub *rsa.PublicKey) (func([][]byte) ([][]byte, error), error) { + ctx := context.Background() + api, err := newKMS(ctx) + if err != nil { + return nil, err + } + kmsPub, err := api.publicKey(ctx, name) + if err != nil { + return nil, err + } + if !kmsPub.Equal(pub) { + return nil, fmt.Errorf("kms: %s is not the certificate's key", name) + } + return func(digests [][]byte) ([][]byte, error) { + out := make([][]byte, len(digests)) + for i, d := range digests { + sig, err := api.asymmetricSign(ctx, name, d) + if err != nil { + return nil, err + } + out[i] = sig + } + return out, nil + }, nil +} + +// kmsPublicKey fetches the key version's public key (for `cert`). +func kmsPublicKey(name string) (*rsa.PublicKey, error) { + ctx := context.Background() + api, err := newKMS(ctx) + if err != nil { + return nil, err + } + return api.publicKey(ctx, name) +} + +func parsePublicKeyPEM(data []byte, source string) (*rsa.PublicKey, error) { + block, _ := pem.Decode(data) + if block == nil { + return nil, fmt.Errorf("%s: no PEM key", source) + } + key, err := x509.ParsePKIXPublicKey(block.Bytes) + if err != nil { + return nil, fmt.Errorf("%s: %w", source, err) + } + rsaKey, ok := key.(*rsa.PublicKey) + if !ok || rsaKey.N.BitLen() < 3072 { + return nil, fmt.Errorf("%s: not an RSA key of 3072 bits or more", source) + } + return rsaKey, nil +} diff --git a/tools/sign-openpgp/kms_test.go b/tools/sign-openpgp/kms_test.go new file mode 100644 index 0000000..28f0148 --- /dev/null +++ b/tools/sign-openpgp/kms_test.go @@ -0,0 +1,174 @@ +package main + +import ( + "bytes" + "context" + "crypto" + "crypto/rand" + "crypto/rsa" + "crypto/sha256" + "crypto/x509" + "encoding/base64" + "encoding/json" + "encoding/pem" + "hash/crc32" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strconv" + "strings" + "testing" +) + +const testKeyVersion = "projects/p/locations/l/keyRings/r/cryptoKeys/k/cryptoKeyVersions/1" + +// fakeKMS signs with an in-process RSA key, as KMS would with its own. +type fakeKMS struct { + key *rsa.PrivateKey + signs int +} + +func (f *fakeKMS) asymmetricSign(_ context.Context, name string, digest []byte) ([]byte, error) { + if name != testKeyVersion { + return nil, os.ErrNotExist + } + f.signs++ + return rsa.SignPKCS1v15(nil, f.key, crypto.SHA256, digest) +} + +func (f *fakeKMS) publicKey(_ context.Context, name string) (*rsa.PublicKey, error) { + if name != testKeyVersion { + return nil, os.ErrNotExist + } + return &f.key.PublicKey, nil +} + +func useFakeKMS(t *testing.T) *fakeKMS { + t.Helper() + key, err := rsa.GenerateKey(rand.Reader, 3072) + if err != nil { + t.Fatal(err) + } + fake := &fakeKMS{key: key} + saved := newKMS + newKMS = func(context.Context) (kmsAPI, error) { return fake, nil } + t.Cleanup(func() { newKMS = saved }) + return fake +} + +// The KMS path makes the same certificate and signatures as the others: +// the public key comes from KMS, the self-signature and the file signatures +// from KMS, and the existing verify path accepts them. +func TestKMSCertSignVerify(t *testing.T) { + fake := useFakeKMS(t) + dir := t.TempDir() + cert := filepath.Join(dir, "cert.asc") + armored := runOK(t, "cert", "-kms-key", testKeyVersion, "-created", "2026-10-25T00:00:00Z") + if err := os.WriteFile(cert, []byte(armored), 0o644); err != nil { + t.Fatal(err) + } + files := []string{filepath.Join(dir, "install.sh"), filepath.Join(dir, "version.txt")} + for _, f := range files { + os.WriteFile(f, []byte(f), 0o644) + } + before := fake.signs + runOK(t, append([]string{"sign", "-cert", cert, "-kms-key", testKeyVersion}, files...)...) + if got := fake.signs - before; got != len(files) { + t.Errorf("KMS signed %d digests, want %d", got, len(files)) + } + runOK(t, append([]string{"verify", "-cert", cert}, files...)...) + + t.Run("a KMS key that is not the certificate's", func(t *testing.T) { + _, other := devCert(t, t.TempDir()) + err := run([]string{"sign", "-cert", other, "-kms-key", testKeyVersion, files[0]}, &bytes.Buffer{}) + if err == nil || !strings.Contains(err.Error(), "not the certificate's key") { + t.Fatalf("signed for another certificate: %v", err) + } + }) + t.Run("two backends", func(t *testing.T) { + key, _ := devCert(t, t.TempDir()) + if err := run([]string{"sign", "-cert", cert, "-kms-key", testKeyVersion, "-key-file", key, files[0]}, &bytes.Buffer{}); err == nil { + t.Fatal("accepted two signing backends") + } + }) +} + +// The REST client against a stand-in for the KMS API: the request KMS +// expects, and the CRC32C checks in both directions. +func TestKMSREST(t *testing.T) { + key, err := rsa.GenerateKey(rand.Reader, 4096) + if err != nil { + t.Fatal(err) + } + der, _ := x509.MarshalPKIXPublicKey(&key.PublicKey) + pubPEM := string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: der})) + crc := func(b []byte) string { return strconv.FormatUint(uint64(crc32.Checksum(b, crc32c)), 10) } + + var damage string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodGet && r.URL.Path == "/"+testKeyVersion+"/publicKey": + json.NewEncoder(w).Encode(map[string]string{"pem": pubPEM, "algorithm": "RSA_SIGN_PKCS1_4096_SHA256", "pemCrc32c": crc([]byte(pubPEM))}) + case r.Method == http.MethodPost && r.URL.Path == "/"+testKeyVersion+":asymmetricSign": + var req struct { + Digest struct{ Sha256 string } `json:"digest"` + DigestCrc32c string `json:"digestCrc32c"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + digest, _ := base64.StdEncoding.DecodeString(req.Digest.Sha256) + sig, err := rsa.SignPKCS1v15(nil, key, crypto.SHA256, digest) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + answer := map[string]any{ + "signature": base64.StdEncoding.EncodeToString(sig), + "signatureCrc32c": crc(sig), + "verifiedDigestCrc32c": req.DigestCrc32c == crc(digest), + "name": testKeyVersion, + } + switch damage { + case "signature": + answer["signatureCrc32c"] = "1" + case "digest": + answer["verifiedDigestCrc32c"] = false + } + json.NewEncoder(w).Encode(answer) + default: + http.NotFound(w, r) + } + })) + defer srv.Close() + k := &kmsREST{client: srv.Client(), endpoint: srv.URL + "/"} + ctx := context.Background() + + pub, err := k.publicKey(ctx, testKeyVersion) + if err != nil { + t.Fatal(err) + } + if !pub.Equal(&key.PublicKey) { + t.Fatal("wrong public key") + } + digest := sha256.Sum256([]byte("version.txt")) + sig, err := k.asymmetricSign(ctx, testKeyVersion, digest[:]) + if err != nil { + t.Fatal(err) + } + if err := rsa.VerifyPKCS1v15(&key.PublicKey, crypto.SHA256, digest[:], sig); err != nil { + t.Fatalf("signature does not verify: %v", err) + } + for _, d := range []string{"signature", "digest"} { + damage = d + if _, err := k.asymmetricSign(ctx, testKeyVersion, digest[:]); err == nil { + t.Errorf("a damaged %s was accepted", d) + } + } + damage = "" + if _, err := k.asymmetricSign(ctx, testKeyVersion+"0", digest[:]); err == nil { + t.Error("an unknown key version answered") + } +} diff --git a/tools/sign-openpgp/main.go b/tools/sign-openpgp/main.go new file mode 100644 index 0000000..62b024b --- /dev/null +++ b/tools/sign-openpgp/main.go @@ -0,0 +1,492 @@ +// Command sign-openpgp makes the detached OpenPGP signatures an IronFlock +// install or update checks before it runs or uses anything it downloaded: +// device-init's install.sh (version.txt, ironflock-init) and the appliance's +// ironflock-update and installer (install_ironflock.sh, availableVersions.json, +// the release manifest), and the signatures users check those scripts with. +// The private key never leaves its signer — a Cloud KMS key (-kms-key, +// kms.go: what CI signs releases with) or an OpenBao transit key (-signer, by +// hand), RSA-4096 and not exportable: this tool hashes locally and hands only +// digests to the signer. +// +// Detached OpenPGP signatures, because a device can check them with what apt +// already depends on (sqv on Debian 13, gpgv everywhere else) — Ed25519 with +// OpenSSL is not available on Debian 11, Ubuntu 20.04 or Raspberry Pi OS 11. +// +// cert [-public-key ] -created [-uid >] > cert.asc +// (with -kms-key the public key comes from KMS) +// sign -cert ... writes .asc +// verify -cert ... checks .asc +// export -cert the binary certificate, base64 (install.sh embeds it) +// fingerprint -cert +// keygen -out a DEVELOPMENT key (tests, dry runs) +// +// is -signer '' (reads " " +// lines, answers " vault:v:": what +// scripts/openbao-sign-bootstrap.sh does in one OpenBao session), +// -kms-key projects/…/cryptoKeyVersions/ (Cloud KMS, Application Default +// Credentials) or -key-file (a development key). +package main + +import ( + "bufio" + "bytes" + "crypto" + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "encoding/base64" + "encoding/pem" + "errors" + "flag" + "fmt" + "io" + "os" + "os/exec" + "strconv" + "strings" + "sync" + "time" + + "github.com/ProtonMail/go-crypto/openpgp" + "github.com/ProtonMail/go-crypto/openpgp/armor" + "github.com/ProtonMail/go-crypto/openpgp/packet" +) + +const defaultUID = "IronFlock Bootstrap " + +func main() { + if err := run(os.Args[1:], os.Stdout); err != nil { + fmt.Fprintln(os.Stderr, "sign-openpgp:", err) + os.Exit(1) + } +} + +func run(args []string, stdout io.Writer) error { + if len(args) == 0 { + return errors.New("usage: sign-openpgp cert|sign|verify|export|fingerprint|keygen [flags]") + } + flags := flag.NewFlagSet(args[0], flag.ContinueOnError) + certPath := flags.String("cert", "", "the certificate (armored public key)") + publicKey := flags.String("public-key", "", "cert: the RSA public key, PEM (OpenBao transit/keys/ public_key)") + created := flags.String("created", "", "cert: the key's creation time, RFC 3339 (it is part of the fingerprint)") + uid := flags.String("uid", defaultUID, "cert: the user ID") + signerCmd := flags.String("signer", "", "signing command (see the package doc)") + keyFile := flags.String("key-file", "", "development RSA private key, PEM") + kmsKey := flags.String("kms-key", "", "Cloud KMS key version resource (projects/…/cryptoKeyVersions/)") + out := flags.String("out", "", "keygen: the key file to write") + if err := flags.Parse(args[1:]); err != nil { + return err + } + + switch args[0] { + case "keygen": + return keygen(*out) + case "cert": + var pub *rsa.PublicKey + var err error + if *publicKey == "" && *kmsKey != "" { + pub, err = kmsPublicKey(*kmsKey) + } else { + pub, err = readPublicKey(*publicKey) + } + if err != nil { + return err + } + when, err := time.Parse(time.RFC3339, *created) + if err != nil { + return fmt.Errorf("-created: %w", err) + } + b, err := newBatch(*signerCmd, *keyFile, *kmsKey, pub) + if err != nil { + return err + } + return cert(stdout, pub, when.UTC(), *uid, b) + } + + entity, err := readCert(*certPath) + if err != nil { + return err + } + switch args[0] { + case "sign": + pub, ok := entity.PrimaryKey.PublicKey.(*rsa.PublicKey) + if !ok { + return errors.New("the certificate is not an RSA key") + } + b, err := newBatch(*signerCmd, *keyFile, *kmsKey, pub) + if err != nil { + return err + } + return sign(stdout, entity, b, flags.Args()) + case "verify": + return verify(stdout, entity, flags.Args()) + case "export": + var buf bytes.Buffer + if err := entity.Serialize(&buf); err != nil { + return err + } + _, err := fmt.Fprintln(stdout, base64.StdEncoding.EncodeToString(buf.Bytes())) + return err + case "fingerprint": + _, err := fmt.Fprintf(stdout, "%X\n", entity.PrimaryKey.Fingerprint) + return err + } + return fmt.Errorf("unknown subcommand %q", args[0]) +} + +// config: SHA-256 everywhere (Sequoia's sqv refuses SHA-1), deterministic +// time for the certificate. +func config(now time.Time) *packet.Config { + return &packet.Config{DefaultHash: crypto.SHA256, Time: func() time.Time { return now }} +} + +func cert(stdout io.Writer, pub *rsa.PublicKey, created time.Time, uid string, b *batch) error { + name, email, ok := strings.Cut(strings.TrimSuffix(uid, ">"), " <") + if !ok { + return fmt.Errorf("-uid %q: want \"Name \"", uid) + } + primary := packet.NewRSAPublicKey(created, pub) + entity := &openpgp.Entity{ + PrimaryKey: primary, + PrivateKey: &packet.PrivateKey{PublicKey: *primary, PrivateKey: b.signer()}, + Identities: map[string]*openpgp.Identity{}, + } + var err error + b.run(1, func() { err = entity.AddUserId(name, "", email, config(created)) }) + if b.err != nil { + return b.err + } + if err != nil { + return err + } + w, err := armor.Encode(stdout, openpgp.PublicKeyType, nil) + if err != nil { + return err + } + if err := entity.Serialize(w); err != nil { + return err + } + if err := w.Close(); err != nil { + return err + } + _, err = fmt.Fprintln(stdout) + return err +} + +func sign(stdout io.Writer, entity *openpgp.Entity, b *batch, files []string) error { + if len(files) == 0 { + return errors.New("sign needs at least one file") + } + entity.PrivateKey = &packet.PrivateKey{PublicKey: *entity.PrimaryKey, PrivateKey: b.signer()} + now := time.Now().UTC() + sigs := make([]bytes.Buffer, len(files)) + errs := make([]error, len(files)) + data := make([][]byte, len(files)) + for i, file := range files { + var err error + if data[i], err = os.ReadFile(file); err != nil { //nolint:gosec // G304: the files to sign are the arguments + return err + } + } + b.run(len(files), func() { + var wg sync.WaitGroup + for i := range files { + wg.Add(1) + go func(i int) { + defer wg.Done() + errs[i] = openpgp.ArmoredDetachSign(&sigs[i], entity, bytes.NewReader(data[i]), config(now)) + }(i) + } + wg.Wait() + }) + if err := errors.Join(errs...); err != nil { + return err + } + // go-crypto drops an RSA signer's error (and then fails to serialize): + // say what the signer said. + if b.err != nil { + return b.err + } + // Every signature is checked before any is written. + keyring := openpgp.EntityList{entity} + for i, file := range files { + if _, err := openpgp.CheckArmoredDetachedSignature(keyring, bytes.NewReader(data[i]), bytes.NewReader(sigs[i].Bytes()), nil); err != nil { + return fmt.Errorf("%s: the new signature does not verify: %w", file, err) + } + } + for i, file := range files { + if err := os.WriteFile(file+".asc", append(sigs[i].Bytes(), '\n'), 0o644); err != nil { //nolint:gosec // G306: a signature is public + return err + } + if _, err := fmt.Fprintf(stdout, "signed %s -> %s.asc\n", file, file); err != nil { + return err + } + } + return nil +} + +func verify(stdout io.Writer, entity *openpgp.Entity, files []string) error { + if len(files) == 0 { + return errors.New("verify needs at least one file") + } + for _, file := range files { + data, err := os.ReadFile(file) //nolint:gosec // G304: the files to check are the arguments + if err != nil { + return err + } + sig, err := os.ReadFile(file + ".asc") //nolint:gosec // G304: their signatures, next to them + if err != nil { + return err + } + if _, err := openpgp.CheckArmoredDetachedSignature(openpgp.EntityList{entity}, bytes.NewReader(data), bytes.NewReader(sig), nil); err != nil { + return fmt.Errorf("%s: %w", file, err) + } + if _, err := fmt.Fprintf(stdout, "%s: good signature by %X\n", file, entity.PrimaryKey.Fingerprint); err != nil { + return err + } + } + return nil +} + +// --- the batch signer -------------------------------------------------------- + +// batch collects the digests of n concurrent signing operations and has the +// backend sign them all at once (one OpenBao session), then hands every +// operation its signature. +type batch struct { + pub *rsa.PublicKey + backend func(digests [][]byte) ([][]byte, error) + + err error // the backend's, of the last run + mu sync.Mutex + want int + requests []request + ready chan struct{} +} + +type request struct { + digest []byte + reply chan result +} + +type result struct { + sig []byte + err error +} + +func newBatch(signerCmd, keyFile, kmsKey string, pub *rsa.PublicKey) (*batch, error) { + b := &batch{pub: pub} + given := 0 + for _, s := range []string{signerCmd, keyFile, kmsKey} { + if s != "" { + given++ + } + } + if given != 1 { + return nil, errors.New("give exactly one of -signer, -kms-key and -key-file") + } + switch { + case signerCmd != "": + b.backend = func(digests [][]byte) ([][]byte, error) { return commandSign(signerCmd, digests) } + case kmsKey != "": + backend, err := kmsBackend(kmsKey, pub) + if err != nil { + return nil, err + } + b.backend = backend + default: + key, err := readPrivateKey(keyFile) + if err != nil { + return nil, err + } + if !key.PublicKey.Equal(pub) { + return nil, errors.New("-key-file is not the certificate's key") + } + b.backend = func(digests [][]byte) ([][]byte, error) { + out := make([][]byte, len(digests)) + for i, d := range digests { + sig, err := rsa.SignPKCS1v15(nil, key, crypto.SHA256, d) + if err != nil { + return nil, err + } + out[i] = sig + } + return out, nil + } + } + return b, nil +} + +// run runs ops, which makes exactly n Sign calls, and answers them together. +func (b *batch) run(n int, ops func()) { + b.mu.Lock() + b.want, b.requests, b.ready = n, nil, make(chan struct{}) + b.mu.Unlock() + done := make(chan struct{}) + go func() { ops(); close(done) }() + select { + case <-b.ready: + case <-done: // an operation failed before it signed + return + } + b.mu.Lock() + requests := b.requests + b.requests = nil + b.mu.Unlock() + digests := make([][]byte, len(requests)) + for i, r := range requests { + digests[i] = r.digest + } + sigs, err := b.backend(digests) + b.err = err + for i, r := range requests { + if err != nil { + r.reply <- result{err: err} + } else { + r.reply <- result{sig: sigs[i]} + } + } + <-done +} + +func (b *batch) signer() crypto.Signer { return batchSigner{b} } + +type batchSigner struct{ b *batch } + +func (s batchSigner) Public() crypto.PublicKey { return s.b.pub } + +func (s batchSigner) Sign(_ io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) { + if opts.HashFunc() != crypto.SHA256 { + return nil, fmt.Errorf("asked to sign a %v digest; only SHA-256", opts.HashFunc()) + } + reply := make(chan result, 1) + s.b.mu.Lock() + s.b.requests = append(s.b.requests, request{digest: append([]byte(nil), digest...), reply: reply}) + if len(s.b.requests) == s.b.want { + close(s.b.ready) + } + s.b.mu.Unlock() + r := <-reply + return r.sig, r.err +} + +// commandSign sends " " lines to the signer command and +// reads " vault:v:" answers. +func commandSign(command string, digests [][]byte) ([][]byte, error) { + var in bytes.Buffer + for i, d := range digests { + fmt.Fprintf(&in, "%d %s\n", i, base64.StdEncoding.EncodeToString(d)) + } + cmd := exec.Command("sh", "-c", command) //nolint:gosec // G204: the signer command is the caller's own (-signer) // nosemgrep: go.lang.security.audit.dangerous-exec-command.dangerous-exec-command + cmd.Stdin = &in + cmd.Stderr = os.Stderr + out, err := cmd.Output() + if err != nil { + return nil, fmt.Errorf("signer: %w", err) + } + sigs := make([][]byte, len(digests)) + scanner := bufio.NewScanner(bytes.NewReader(out)) + for scanner.Scan() { + id, answer, ok := strings.Cut(strings.TrimSpace(scanner.Text()), " ") + i, err := strconv.Atoi(id) + if !ok || err != nil || i < 0 || i >= len(sigs) || sigs[i] != nil { + return nil, fmt.Errorf("unexpected line from the signer: %q", scanner.Text()) + } + rest, ok := strings.CutPrefix(answer, "vault:v") + _, encoded, found := strings.Cut(rest, ":") + if !ok || !found { + return nil, fmt.Errorf("not a transit signature: %q", answer) + } + if sigs[i], err = base64.StdEncoding.DecodeString(encoded); err != nil { + return nil, fmt.Errorf("not a transit signature: %q", answer) + } + } + for i, s := range sigs { + if s == nil { + return nil, fmt.Errorf("the signer did not answer request %d", i) + } + } + return sigs, nil +} + +// --- keys ---------------------------------------------------------------------- + +func keygen(out string) error { + if out == "" { + return errors.New("keygen needs -out") + } + key, err := rsa.GenerateKey(rand.Reader, 4096) + if err != nil { + return err + } + der, err := x509.MarshalPKCS8PrivateKey(key) + if err != nil { + return err + } + f, err := os.OpenFile(out, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) //nolint:gosec // G304: -out names the key file to write + if err != nil { + return err + } + if err := pem.Encode(f, &pem.Block{Type: "PRIVATE KEY", Bytes: der}); err != nil { + _ = f.Close() + return err + } + if err := f.Close(); err != nil { + return err + } + pubDER, err := x509.MarshalPKIXPublicKey(&key.PublicKey) + if err != nil { + return err + } + return os.WriteFile(out+".pub", pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: pubDER}), 0o644) //nolint:gosec // G306: a public key +} + +func readPrivateKey(path string) (*rsa.PrivateKey, error) { + data, err := os.ReadFile(path) //nolint:gosec // G304: -key-file names the key + if err != nil { + return nil, err + } + block, _ := pem.Decode(data) + if block == nil { + return nil, fmt.Errorf("%s: no PEM key", path) + } + key, err := x509.ParsePKCS8PrivateKey(block.Bytes) + if err != nil { + return nil, fmt.Errorf("%s: %w", path, err) + } + rsaKey, ok := key.(*rsa.PrivateKey) + if !ok { + return nil, fmt.Errorf("%s: not an RSA key", path) + } + return rsaKey, nil +} + +func readPublicKey(path string) (*rsa.PublicKey, error) { + if path == "" { + return nil, errors.New("cert needs -public-key or -kms-key") + } + data, err := os.ReadFile(path) //nolint:gosec // G304: -public-key names the key + if err != nil { + return nil, err + } + return parsePublicKeyPEM(data, path) +} + +func readCert(path string) (*openpgp.Entity, error) { + if path == "" { + return nil, errors.New("-cert is required") + } + f, err := os.Open(path) //nolint:gosec // G304: -cert names the certificate + if err != nil { + return nil, err + } + defer func() { _ = f.Close() }() + entities, err := openpgp.ReadArmoredKeyRing(f) + if err != nil { + return nil, fmt.Errorf("%s: %w", path, err) + } + if len(entities) != 1 { + return nil, fmt.Errorf("%s holds %d keys, want 1", path, len(entities)) + } + return entities[0], nil +} diff --git a/tools/sign-openpgp/main_test.go b/tools/sign-openpgp/main_test.go new file mode 100644 index 0000000..7431a6d --- /dev/null +++ b/tools/sign-openpgp/main_test.go @@ -0,0 +1,136 @@ +package main + +import ( + "bytes" + "encoding/base64" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +func runOK(t *testing.T, args ...string) string { + t.Helper() + var out bytes.Buffer + if err := run(args, &out); err != nil { + t.Fatalf("%v: %v", args, err) + } + return out.String() +} + +// devCert makes a development key and its certificate in dir. +func devCert(t *testing.T, dir string) (key, cert string) { + key = filepath.Join(dir, "dev.pem") + runOK(t, "keygen", "-out", key) + cert = filepath.Join(dir, "cert.asc") + armored := runOK(t, "cert", "-public-key", key+".pub", "-created", "2026-10-18T00:00:00Z", "-key-file", key) + if err := os.WriteFile(cert, []byte(armored), 0o644); err != nil { + t.Fatal(err) + } + return key, cert +} + +func TestSignAndVerify(t *testing.T) { + dir := t.TempDir() + key, cert := devCert(t, dir) + files := []string{filepath.Join(dir, "install.sh"), filepath.Join(dir, "version.txt"), filepath.Join(dir, "ironflock-init")} + for i, f := range files { + if err := os.WriteFile(f, []byte(strings.Repeat("x", i*1000+1)), 0o644); err != nil { + t.Fatal(err) + } + } + runOK(t, append([]string{"sign", "-cert", cert, "-key-file", key}, files...)...) + runOK(t, append([]string{"verify", "-cert", cert}, files...)...) + + // The fingerprint depends only on the key and its creation time. + again := filepath.Join(dir, "again.asc") + armored := runOK(t, "cert", "-public-key", key+".pub", "-created", "2026-10-18T00:00:00Z", "-key-file", key) + os.WriteFile(again, []byte(armored), 0o644) + if a, b := runOK(t, "fingerprint", "-cert", cert), runOK(t, "fingerprint", "-cert", again); a != b { + t.Errorf("fingerprint changed: %s %s", a, b) + } + + t.Run("tampered", func(t *testing.T) { + os.WriteFile(files[1], []byte("9.9.9\n"), 0o644) + if err := run([]string{"verify", "-cert", cert, files[1]}, &bytes.Buffer{}); err == nil { + t.Fatal("a changed file verified") + } + }) + t.Run("another key", func(t *testing.T) { + _, other := devCert(t, t.TempDir()) + if err := run([]string{"verify", "-cert", other, files[0]}, &bytes.Buffer{}); err == nil { + t.Fatal("verified with another key") + } + }) + t.Run("gpgv and sqv", func(t *testing.T) { + exported := strings.TrimSpace(runOK(t, "export", "-cert", cert)) + binary, err := base64.StdEncoding.DecodeString(exported) + if err != nil { + t.Fatal(err) + } + keyring := filepath.Join(dir, "keyring.gpg") + os.WriteFile(keyring, binary, 0o644) + tried := false + for _, tool := range []string{"gpgv", "sqv"} { + if _, err := exec.LookPath(tool); err != nil { + continue + } + tried = true + out, err := exec.Command(tool, "--keyring", keyring, files[0]+".asc", files[0]).CombinedOutput() + if err != nil { + t.Errorf("%s: %v\n%s", tool, err, out) + } + } + if !tried { + t.Skip("neither gpgv nor sqv here; CI runs this on Ubuntu, which has gpgv") + } + }) +} + +// The OpenBao path: a signer command that answers in transit's format, in +// one call for every file. +func TestSignerCommand(t *testing.T) { + dir := t.TempDir() + key, cert := devCert(t, dir) + // A fake transit: signs each digest with the dev key via this binary. + self, err := os.Executable() + if err != nil { + t.Fatal(err) + } + calls := filepath.Join(dir, "calls") + signer := "echo call >> " + calls + "; FAKE_TRANSIT_KEY=" + key + " " + self + " -test.run=TestFakeTransit" + files := []string{filepath.Join(dir, "a"), filepath.Join(dir, "b")} + for _, f := range files { + os.WriteFile(f, []byte(f), 0o644) + } + runOK(t, append([]string{"sign", "-cert", cert, "-signer", signer}, files...)...) + runOK(t, append([]string{"verify", "-cert", cert}, files...)...) + if data, _ := os.ReadFile(calls); strings.Count(string(data), "call") != 1 { + t.Errorf("signer called %d times, want once", strings.Count(string(data), "call")) + } +} + +// TestFakeTransit is the signer command TestSignerCommand runs. +func TestFakeTransit(t *testing.T) { + keyFile := os.Getenv("FAKE_TRANSIT_KEY") + if keyFile == "" { + t.Skip("only as a signer command") + } + key, err := readPrivateKey(keyFile) + if err != nil { + t.Fatal(err) + } + b, _ := newBatch("", keyFile, "", &key.PublicKey) + data, _ := os.ReadFile("/dev/stdin") + for _, line := range strings.Split(strings.TrimSpace(string(data)), "\n") { + id, digest, _ := strings.Cut(line, " ") + raw, _ := base64.StdEncoding.DecodeString(digest) + sigs, err := b.backend([][]byte{raw}) + if err != nil { + t.Fatal(err) + } + os.Stdout.WriteString(id + " vault:v1:" + base64.StdEncoding.EncodeToString(sigs[0]) + "\n") + } + os.Exit(0) // no "PASS" on stdout: that is the answer channel +}