gunk-dev/the-valley

sign.go

source7309e1d6b8bbmain's published tip history
9.9 KiB
1package main
2
3// The envelope: a signed note.
4//
5// A note is the statement text, then a blank line, then one or more
6// signature lines. Each signature line is an em-dash, a space, the
7// signer's name, a space, and base64 of a four-byte key hash followed by
8// the raw Ed25519 signature over the text:
9//
10// the-valley/attestation/v1
11// subject.primary valley-tree-v1
12// …
13//
14// — valley-host.example.org/attestations WhFo+DGb1c/Fk6…
15// — witness.example.org/attestations Ro+Yc3q9nSs8W…
16//
17// This is the format golang.org/x/mod/sumdb/note defines and transparency
18// log checkpoints are published in.
19//
20// It is chosen for what it does to composition. Several parties attesting
21// to one subject become sibling signature lines under one text, so a
22// signature cannot be lifted onto a different statement: it sits under the
23// text it covers, and moving it means moving the text with it. That
24// property is structural here rather than a rule a verifier has to
25// remember to apply. It is also the envelope a Phase 6 checkpoint arrives
26// in, so the same envelope carries an attestation now and a log checkpoint
27// later rather than changing at the boundary.
28//
29// A signature covers the text and nothing else — not the signer's name,
30// not a namespace, and no git object (ida-51605e8). What separates an
31// attestation from any other note a key signs is therefore the text's own
32// first line, which is the statement type.
33//
34// # One reading of the envelope
35//
36// The envelope is read and written by the note module (../note), not by
37// this program alone. attest signs with it and attest verify opens with
38// it, and so does the pre-receive hook a valley host checks pushed
39// attestations with (valleyhook/). One reading means a note the hook
40// accepts into the attestation namespace, where no note is ever changed or
41// removed, is a note every verifier opens,
42// and a note this program writes is one the hook accepts.
43//
44// golang.org/x/mod/sumdb/note is the reference implementation of the
45// format, and the note module is that format written out again. The
46// format is frozen — it is what sum.golang.org publishes and every
47// checkpoint verifier reads — and the project holds that the size of a
48// dependency graph is itself the exposure, so the valley's programs depend
49// on nothing outside the standard library and their own repository.
50// Interoperability is bought by pinning bytes rather than by sharing code:
51// attest/conformance/ holds notes that must verify, and the unit tests
52// re-derive the published key hash of sum.golang.org from its name and its
53// public key.
54
55import (
56 "bytes"
57 "crypto/ed25519"
58 "encoding/binary"
59 "encoding/pem"
60 "fmt"
61 "os"
62
63 "the-valley/note"
64)
65
66// algEd25519 is the algorithm identifier the note format prefixes a public
67// key with. Ed25519 is the only algorithm this program signs or verifies
68// with.
69const algEd25519 = note.AlgEd25519
70
71// signer is a key this host signs with: a name, the private key, and the
72// key hash the two together produce.
73type signer struct {
74 name string
75 priv ed25519.PrivateKey
76 hash uint32
77}
78
79// verifierKey is a key a verifier is willing to accept a signature from.
80// It is written as one line — the name, the key hash in hex, and base64 of
81// the algorithm byte and the public key, joined by plus signs.
82//
83// This is the whole of what a verifier is given. There is no allowed
84// signers file, no certificate and no directory lookup: `attest verify`
85// takes a file of these lines, and a signature by a key not among them is
86// a signature by nobody it accepts.
87type verifierKey = note.VerifierKey
88
89func keyHash(name string, pub ed25519.PublicKey) uint32 { return note.KeyHash(name, pub) }
90
91func checkSignerName(name string) error { return note.CheckName(name) }
92
93func checkNoteText(text []byte) error { return note.CheckText(text) }
94
95func (s signer) verifierKey() verifierKey {
96 return note.NewVerifierKey(s.name, s.priv.Public().(ed25519.PublicKey))
97}
98
99func parseVerifierKey(line string) (verifierKey, error) { return note.ParseVerifierKey(line) }
100
101// readVerifierKeys reads a known-keys file: one verifier key per line,
102// with blank lines and # comments ignored.
103func readVerifierKeys(path string) ([]verifierKey, error) {
104 raw, err := os.ReadFile(path)
105 if err != nil {
106 return nil, err
107 }
108 keys, err := note.ParseVerifierKeys(raw)
109 if err != nil {
110 return nil, fmt.Errorf("%s: %w", path, err)
111 }
112 if len(keys) == 0 {
113 return nil, fmt.Errorf("%s lists no verifier keys", path)
114 }
115 return keys, nil
116}
117
118// signNote writes a note: the text, a blank line, and one signature line.
119func signNote(text []byte, s signer) ([]byte, error) {
120 return note.Sign(text, s.name, s.priv)
121}
122
123// addSignature adds a signature line to a note that already carries one.
124// This is how several parties attest to one subject: the second signer
125// signs the same text, and its signature lands beside the first, under the
126// text both of them cover.
127func addSignature(n []byte, s signer) ([]byte, error) {
128 return note.AddSignature(n, s.name, s.priv)
129}
130
131// noteSignature is one signature line as read back: who it says signed,
132// under which key hash, and what a verifier made of it.
133type noteSignature struct {
134 name string
135 hash uint32
136 known bool
137 verified bool
138}
139
140// openNote checks a note against the keys a verifier holds, and returns
141// the text and what became of every signature line over it. The reading
142// and the rules are the note module's: a signature by a key the verifier
143// holds must check out, at least one must, and a line that is not a
144// well-formed Ed25519 signature line refuses the note.
145func openNote(n []byte, known []verifierKey) ([]byte, []noteSignature, error) {
146 text, checked, err := note.Open(n, known)
147 if err != nil {
148 return nil, nil, err
149 }
150 var found []noteSignature
151 for _, c := range checked {
152 found = append(found, noteSignature{name: c.Name, hash: c.Hash, known: c.Known, verified: c.Verified})
153 }
154 return text, found, nil
155}
156
157// loadSigner reads an unencrypted OpenSSH Ed25519 private key and pairs it
158// with the name it signs under. /etc/ssh/ssh_host_ed25519_key is the
159// natural production identity — the host already has it, and it already
160// says which host this is — but the key is a parameter and provisioning
161// one is deployment.
162func loadSigner(path, name string) (signer, error) {
163 if path == "" {
164 return signer{}, fmt.Errorf("no signing key: pass --key. The host signs; an unsigned statement is not an attestation")
165 }
166 if err := checkSignerName(name); err != nil {
167 return signer{}, err
168 }
169 raw, err := os.ReadFile(path)
170 if err != nil {
171 return signer{}, fmt.Errorf("signing key: %w", err)
172 }
173 priv, err := parseOpenSSHEd25519(raw)
174 if err != nil {
175 return signer{}, fmt.Errorf("%s: %w", path, err)
176 }
177 pub := priv.Public().(ed25519.PublicKey)
178 return signer{name: name, priv: priv, hash: keyHash(name, pub)}, nil
179}
180
181// parseOpenSSHEd25519 reads the private key format ssh-keygen writes. The
182// container is
183//
184// "openssh-key-v1\0"
185// string cipher, string kdf, string kdf options
186// uint32 number of keys, string public key
187// string the private section, which for one unencrypted key is
188// uint32 check, uint32 check, string "ssh-ed25519",
189// string public key, string seed and public key, string comment
190//
191// Only the unencrypted single-key case is read. A key behind a passphrase
192// is refused rather than prompted for: attest runs unattended, and a tool
193// that asked a host for a passphrase it does not have would fail later and
194// less clearly.
195func parseOpenSSHEd25519(raw []byte) (ed25519.PrivateKey, error) {
196 block, _ := pem.Decode(raw)
197 if block == nil || block.Type != "OPENSSH PRIVATE KEY" {
198 return nil, fmt.Errorf("not an openssh private key; attest signs with the ed25519 key `ssh-keygen -t ed25519` writes")
199 }
200 body := sshBytes{rest: block.Bytes}
201 magic := []byte("openssh-key-v1\x00")
202 if !bytes.HasPrefix(body.rest, magic) {
203 return nil, fmt.Errorf("not an openssh private key: the container is unrecognised")
204 }
205 body.rest = body.rest[len(magic):]
206
207 cipher := body.str()
208 kdf := body.str()
209 body.str() // the kdf options
210 count := body.u32()
211 body.str() // the public key, which the private section repeats
212 section := sshBytes{rest: body.str()}
213 if body.err != nil {
214 return nil, body.err
215 }
216 if string(cipher) != "none" || string(kdf) != "none" {
217 return nil, fmt.Errorf("the key is encrypted with %s; attest runs unattended and cannot ask for a passphrase", cipher)
218 }
219 if count != 1 {
220 return nil, fmt.Errorf("the file holds %d keys; attest signs with one", count)
221 }
222
223 if a, b := section.u32(), section.u32(); a != b {
224 return nil, fmt.Errorf("the key is encrypted or damaged: its check words differ")
225 }
226 if kind := section.str(); string(kind) != "ssh-ed25519" {
227 return nil, fmt.Errorf("the key is %s; attest signs with ed25519, which is what a note carries", kind)
228 }
229 pub := section.str()
230 priv := section.str()
231 if section.err != nil {
232 return nil, section.err
233 }
234 if len(pub) != ed25519.PublicKeySize || len(priv) != ed25519.PrivateKeySize {
235 return nil, fmt.Errorf("the key is not the size an ed25519 key is")
236 }
237 key := ed25519.PrivateKey(priv)
238 if !bytes.Equal(key.Public().(ed25519.PublicKey), pub) {
239 return nil, fmt.Errorf("the key's two halves do not agree: its private half does not produce its public one")
240 }
241 return key, nil
242}
243
244// sshBytes reads the ssh wire encoding, where a string is a four-byte
245// big-endian length and that many bytes. The first error is kept and every
246// later read is a no-op, so a caller checks once at the end.
247type sshBytes struct {
248 rest []byte
249 err error
250}
251
252func (s *sshBytes) u32() uint32 {
253 if s.err != nil {
254 return 0
255 }
256 if len(s.rest) < 4 {
257 s.err = fmt.Errorf("the key ends in the middle of a field")
258 return 0
259 }
260 v := binary.BigEndian.Uint32(s.rest)
261 s.rest = s.rest[4:]
262 return v
263}
264
265func (s *sshBytes) str() []byte {
266 n := s.u32()
267 if s.err != nil {
268 return nil
269 }
270 if uint64(n) > uint64(len(s.rest)) {
271 s.err = fmt.Errorf("the key claims a %d-byte field with %d bytes left", n, len(s.rest))
272 return nil
273 }
274 v := s.rest[:n]
275 s.rest = s.rest[n:]
276 return v
277}