gunk-dev/the-valley

sign.go

source25a17935048dmain's published tip history
16.4 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// — laddie.gunk.dev/attestations WhFo+DGb1c/Fk6…
15// — witness.gunk.dev/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// # On not taking the dependency
35//
36// golang.org/x/mod/sumdb/note is the reference implementation of this
37// format, and this file is that format written out again. The trade was
38// weighed as follows.
39//
40// The format is frozen. It is what sum.golang.org publishes and what every
41// checkpoint verifier already reads, so it cannot drift out from under a
42// second implementation the way a live API would. Writing it out is
43// roughly a hundred lines over crypto/ed25519, all of it visible here.
44//
45// Against that, gunk-dev holds that the size of a dependency graph is
46// itself the exposure. This program depends on nothing outside the
47// standard library today: it builds with vendorHash = null, it fetches
48// nothing, and the whole of what it runs is in this directory. One module
49// would end that property for code this short.
50//
51// Interoperability is bought by pinning bytes rather than by sharing code.
52// attest/conformance/ holds notes that must verify, and the unit tests
53// re-derive the published key hash of sum.golang.org from its name and its
54// public key — an answer the reference implementation computed, which this
55// implementation has to match exactly or the vectors are worthless.
56
57import (
58 "bytes"
59 "crypto/ed25519"
60 "crypto/sha256"
61 "encoding/base64"
62 "encoding/binary"
63 "encoding/pem"
64 "fmt"
65 "os"
66 "strings"
67 "unicode"
68 "unicode/utf8"
69)
70
71// algEd25519 is the algorithm identifier the note format prefixes a public
72// key with. Ed25519 is the only algorithm this program signs or verifies
73// with; a signature under any other is reported and left unchecked.
74const algEd25519 = 1
75
76// signatureMark opens a signature line. U+2014 EM DASH, then a space.
77const signatureMark = "— "
78
79// signer is a key this host signs with: a name, the private key, and the
80// key hash the two together produce.
81type signer struct {
82 name string
83 priv ed25519.PrivateKey
84 hash uint32
85}
86
87// verifierKey is a key a verifier is willing to accept a signature from.
88// It is written as one line — the name, the key hash in hex, and base64 of
89// the algorithm byte and the public key, joined by plus signs:
90//
91// laddie.gunk.dev/attestations+1f9c40b2+AbUmzL2t…
92//
93// This is the whole of what a verifier is given. There is no allowed
94// signers file, no certificate and no directory lookup: `attest verify`
95// takes a file of these lines, and a signature by a key not among them is
96// a signature by nobody it accepts.
97type verifierKey struct {
98 name string
99 hash uint32
100 pub ed25519.PublicKey
101}
102
103// keyHash is the note format's identifier for a name-and-key pair:
104// SHA-256 over the name, a newline, the algorithm byte and the public key,
105// truncated to its first four bytes.
106//
107// The name is inside the hash and outside the signature. So the same
108// public key published under two names is two verifier keys and cannot be
109// confused, while the signature itself commits only to the text — which is
110// what makes the text's first line, rather than the signer's name, the
111// thing that separates one kind of note from another.
112func keyHash(name string, pub ed25519.PublicKey) uint32 {
113 h := sha256.New()
114 h.Write([]byte(name))
115 h.Write([]byte("\n"))
116 h.Write([]byte{algEd25519})
117 h.Write(pub)
118 return binary.BigEndian.Uint32(h.Sum(nil))
119}
120
121// checkSignerName holds a name to what a signature line can carry: no
122// space, because a space separates the name from the base64 that follows,
123// and no plus, because a plus separates the fields of a verifier key.
124func checkSignerName(name string) error {
125 switch {
126 case name == "":
127 return fmt.Errorf("a signer name may not be empty")
128 case !utf8.ValidString(name):
129 return fmt.Errorf("signer name %q is not valid utf-8", name)
130 case strings.ContainsFunc(name, unicode.IsSpace):
131 return fmt.Errorf("signer name %q holds a space, which separates the name from the signature", name)
132 case strings.Contains(name, "+"):
133 return fmt.Errorf("signer name %q holds a plus, which separates the fields of a verifier key", name)
134 }
135 return nil
136}
137
138func (v verifierKey) String() string {
139 return fmt.Sprintf("%s+%08x+%s", v.name, v.hash,
140 base64.StdEncoding.EncodeToString(append([]byte{algEd25519}, v.pub...)))
141}
142
143func (s signer) verifierKey() verifierKey {
144 return verifierKey{name: s.name, hash: s.hash, pub: s.priv.Public().(ed25519.PublicKey)}
145}
146
147// parseVerifierKey reads one verifier key line. The key hash it carries is
148// checked against the one its name and public key produce, so a line whose
149// hash was edited is refused here rather than quietly matching nothing at
150// verification time.
151func parseVerifierKey(line string) (verifierKey, error) {
152 malformed := fmt.Errorf("%q is not a verifier key: one is name+hash+base64", line)
153 name, rest, found := strings.Cut(strings.TrimSpace(line), "+")
154 if !found {
155 return verifierKey{}, malformed
156 }
157 written, encoded, found := strings.Cut(rest, "+")
158 if !found {
159 return verifierKey{}, malformed
160 }
161 if err := checkSignerName(name); err != nil {
162 return verifierKey{}, err
163 }
164 raw, err := base64.StdEncoding.DecodeString(encoded)
165 if err != nil {
166 return verifierKey{}, fmt.Errorf("verifier key %s: %w", name, err)
167 }
168 if len(raw) != 1+ed25519.PublicKeySize || raw[0] != algEd25519 {
169 return verifierKey{}, fmt.Errorf("verifier key %s is not an ed25519 key", name)
170 }
171 v := verifierKey{name: name, hash: keyHash(name, raw[1:]), pub: raw[1:]}
172 if fmt.Sprintf("%08x", v.hash) != written {
173 return verifierKey{}, fmt.Errorf("verifier key %s carries hash %s, but its name and key produce %08x", name, written, v.hash)
174 }
175 return v, nil
176}
177
178// readVerifierKeys reads a known-keys file: one verifier key per line,
179// with blank lines and # comments ignored.
180func readVerifierKeys(path string) ([]verifierKey, error) {
181 raw, err := os.ReadFile(path)
182 if err != nil {
183 return nil, err
184 }
185 var keys []verifierKey
186 for i, line := range strings.Split(string(raw), "\n") {
187 line = strings.TrimSpace(line)
188 if line == "" || strings.HasPrefix(line, "#") {
189 continue
190 }
191 v, err := parseVerifierKey(line)
192 if err != nil {
193 return nil, fmt.Errorf("%s:%d: %w", path, i+1, err)
194 }
195 keys = append(keys, v)
196 }
197 if len(keys) == 0 {
198 return nil, fmt.Errorf("%s lists no verifier keys", path)
199 }
200 return keys, nil
201}
202
203// signNote writes a note: the text, a blank line, and one signature line.
204func signNote(text []byte, s signer) ([]byte, error) {
205 if err := checkNoteText(text); err != nil {
206 return nil, err
207 }
208 var b bytes.Buffer
209 b.Write(text)
210 b.WriteByte('\n')
211 b.WriteString(signatureLine(text, s))
212 return b.Bytes(), nil
213}
214
215// addSignature adds a signature line to a note that already carries one.
216// This is how several parties attest to one subject: the second signer
217// signs the same text, and its signature lands beside the first, under the
218// text both of them cover.
219func addSignature(note []byte, s signer) ([]byte, error) {
220 text, sigs, err := splitNote(note)
221 if err != nil {
222 return nil, err
223 }
224 line := signatureLine(text, s)
225 for _, existing := range sigs {
226 if existing == strings.TrimSuffix(line, "\n") {
227 return note, nil
228 }
229 }
230 return append(append([]byte{}, note...), line...), nil
231}
232
233func signatureLine(text []byte, s signer) string {
234 var hb [4]byte
235 binary.BigEndian.PutUint32(hb[:], s.hash)
236 blob := append(hb[:], ed25519.Sign(s.priv, text)...)
237 return signatureMark + s.name + " " + base64.StdEncoding.EncodeToString(blob) + "\n"
238}
239
240// noteSignature is one signature line as read back: who it says signed,
241// under which key hash, and what a verifier made of it.
242type noteSignature struct {
243 name string
244 hash uint32
245 known bool
246 verified bool
247}
248
249// splitNote separates a note's text from its signature lines. The blank
250// line before the signature block is the separator, and the last one wins,
251// so text holding a blank line of its own does not move the split.
252func splitNote(note []byte) (text []byte, sigs []string, err error) {
253 if err := checkNoteBytes(note); err != nil {
254 return nil, nil, err
255 }
256 split := bytes.LastIndex(note, []byte("\n\n"))
257 if split < 0 {
258 return nil, nil, fmt.Errorf("this is not a note: no blank line separates the text from its signatures")
259 }
260 text, block := note[:split+1], note[split+2:]
261 if len(block) == 0 || block[len(block)-1] != '\n' {
262 return nil, nil, fmt.Errorf("this is not a note: the signature block is empty or does not end with a newline")
263 }
264 for _, line := range strings.Split(strings.TrimSuffix(string(block), "\n"), "\n") {
265 if !strings.HasPrefix(line, signatureMark) {
266 return nil, nil, fmt.Errorf("%q is not a signature line: one opens with an em-dash and a space", line)
267 }
268 sigs = append(sigs, line)
269 }
270 return text, sigs, nil
271}
272
273// openNote checks a note against the keys a verifier holds. It returns the
274// text and what became of every signature line over it.
275//
276// A signature line naming a key the verifier holds must check out, or the
277// whole note is refused: one good signature standing beside a forgery is
278// not a note anybody should read past. A line naming a key the verifier
279// does not hold is neither an error nor evidence — it is reported as
280// unknown and carried through.
281func openNote(note []byte, known []verifierKey) ([]byte, []noteSignature, error) {
282 text, lines, err := splitNote(note)
283 if err != nil {
284 return nil, nil, err
285 }
286 if err := checkNoteText(text); err != nil {
287 return nil, nil, err
288 }
289 var found []noteSignature
290 verified := 0
291 for _, line := range lines {
292 name, encoded, ok := strings.Cut(strings.TrimPrefix(line, signatureMark), " ")
293 if !ok {
294 return nil, nil, fmt.Errorf("the signature line for %q carries no signature", name)
295 }
296 blob, err := base64.StdEncoding.DecodeString(encoded)
297 if err != nil || len(blob) < 5 {
298 return nil, nil, fmt.Errorf("the signature line for %q does not decode", name)
299 }
300 sig := noteSignature{name: name, hash: binary.BigEndian.Uint32(blob[:4])}
301 for _, k := range known {
302 if k.name != name || k.hash != sig.hash {
303 continue
304 }
305 sig.known = true
306 if len(blob[4:]) != ed25519.SignatureSize || !ed25519.Verify(k.pub, text, blob[4:]) {
307 return nil, nil, fmt.Errorf("the signature by %s+%08x does not check out over this text", name, sig.hash)
308 }
309 sig.verified = true
310 verified++
311 break
312 }
313 found = append(found, sig)
314 }
315 if verified == 0 {
316 return nil, nil, fmt.Errorf("no signature on this note is by a key the verifier holds")
317 }
318 return text, found, nil
319}
320
321// checkNoteText holds a note's text to what the format allows: valid
322// UTF-8, no ASCII control character but the newline, and a closing
323// newline. Statement text satisfies all of it by construction; a caller
324// signing something else is held to it here.
325func checkNoteText(text []byte) error {
326 if len(text) == 0 || text[len(text)-1] != '\n' {
327 return fmt.Errorf("a note's text must end with a newline")
328 }
329 return checkNoteBytes(text)
330}
331
332func checkNoteBytes(b []byte) error {
333 if !utf8.Valid(b) {
334 return fmt.Errorf("a note is valid utf-8, and this is not")
335 }
336 for _, c := range b {
337 if c < 0x20 && c != '\n' || c == 0x7f {
338 return fmt.Errorf("a note holds no ascii control character but the newline, and this holds %#02x", c)
339 }
340 }
341 return nil
342}
343
344// loadSigner reads an unencrypted OpenSSH Ed25519 private key and pairs it
345// with the name it signs under. /etc/ssh/ssh_host_ed25519_key is the
346// natural production identity — the host already has it, and it already
347// says which host this is — but the key is a parameter and provisioning
348// one is deployment.
349func loadSigner(path, name string) (signer, error) {
350 if path == "" {
351 return signer{}, fmt.Errorf("no signing key: pass --key. The host signs; an unsigned statement is not an attestation")
352 }
353 if err := checkSignerName(name); err != nil {
354 return signer{}, err
355 }
356 raw, err := os.ReadFile(path)
357 if err != nil {
358 return signer{}, fmt.Errorf("signing key: %w", err)
359 }
360 priv, err := parseOpenSSHEd25519(raw)
361 if err != nil {
362 return signer{}, fmt.Errorf("%s: %w", path, err)
363 }
364 pub := priv.Public().(ed25519.PublicKey)
365 return signer{name: name, priv: priv, hash: keyHash(name, pub)}, nil
366}
367
368// parseOpenSSHEd25519 reads the private key format ssh-keygen writes. The
369// container is
370//
371// "openssh-key-v1\0"
372// string cipher, string kdf, string kdf options
373// uint32 number of keys, string public key
374// string the private section, which for one unencrypted key is
375// uint32 check, uint32 check, string "ssh-ed25519",
376// string public key, string seed and public key, string comment
377//
378// Only the unencrypted single-key case is read. A key behind a passphrase
379// is refused rather than prompted for: attest runs unattended, and a tool
380// that asked a host for a passphrase it does not have would fail later and
381// less clearly.
382func parseOpenSSHEd25519(raw []byte) (ed25519.PrivateKey, error) {
383 block, _ := pem.Decode(raw)
384 if block == nil || block.Type != "OPENSSH PRIVATE KEY" {
385 return nil, fmt.Errorf("not an openssh private key; attest signs with the ed25519 key `ssh-keygen -t ed25519` writes")
386 }
387 body := sshBytes{rest: block.Bytes}
388 magic := []byte("openssh-key-v1\x00")
389 if !bytes.HasPrefix(body.rest, magic) {
390 return nil, fmt.Errorf("not an openssh private key: the container is unrecognised")
391 }
392 body.rest = body.rest[len(magic):]
393
394 cipher := body.str()
395 kdf := body.str()
396 body.str() // the kdf options
397 count := body.u32()
398 body.str() // the public key, which the private section repeats
399 section := sshBytes{rest: body.str()}
400 if body.err != nil {
401 return nil, body.err
402 }
403 if string(cipher) != "none" || string(kdf) != "none" {
404 return nil, fmt.Errorf("the key is encrypted with %s; attest runs unattended and cannot ask for a passphrase", cipher)
405 }
406 if count != 1 {
407 return nil, fmt.Errorf("the file holds %d keys; attest signs with one", count)
408 }
409
410 if a, b := section.u32(), section.u32(); a != b {
411 return nil, fmt.Errorf("the key is encrypted or damaged: its check words differ")
412 }
413 if kind := section.str(); string(kind) != "ssh-ed25519" {
414 return nil, fmt.Errorf("the key is %s; attest signs with ed25519, which is what a note carries", kind)
415 }
416 pub := section.str()
417 priv := section.str()
418 if section.err != nil {
419 return nil, section.err
420 }
421 if len(pub) != ed25519.PublicKeySize || len(priv) != ed25519.PrivateKeySize {
422 return nil, fmt.Errorf("the key is not the size an ed25519 key is")
423 }
424 key := ed25519.PrivateKey(priv)
425 if !bytes.Equal(key.Public().(ed25519.PublicKey), pub) {
426 return nil, fmt.Errorf("the key's two halves do not agree: its private half does not produce its public one")
427 }
428 return key, nil
429}
430
431// sshBytes reads the ssh wire encoding, where a string is a four-byte
432// big-endian length and that many bytes. The first error is kept and every
433// later read is a no-op, so a caller checks once at the end.
434type sshBytes struct {
435 rest []byte
436 err error
437}
438
439func (s *sshBytes) u32() uint32 {
440 if s.err != nil {
441 return 0
442 }
443 if len(s.rest) < 4 {
444 s.err = fmt.Errorf("the key ends in the middle of a field")
445 return 0
446 }
447 v := binary.BigEndian.Uint32(s.rest)
448 s.rest = s.rest[4:]
449 return v
450}
451
452func (s *sshBytes) str() []byte {
453 n := s.u32()
454 if s.err != nil {
455 return nil
456 }
457 if uint64(n) > uint64(len(s.rest)) {
458 s.err = fmt.Errorf("the key claims a %d-byte field with %d bytes left", n, len(s.rest))
459 return nil
460 }
461 v := s.rest[:n]
462 s.rest = s.rest[n:]
463 return v
464}