gunk-dev/the-valley

attestation.go

source818813f26b40main's published tip history
7.7 KiB
1package main
2
3import (
4 "bufio"
5 "bytes"
6 "crypto/ed25519"
7 "crypto/sha256"
8 "encoding/base64"
9 "encoding/binary"
10 "errors"
11 "fmt"
12 "io/fs"
13 "os"
14 "regexp"
15 "strings"
16 "unicode/utf8"
17)
18
19// An attestation ref is named for what it holds: the digest of the tree
20// its notes are about, then the key hash of the signer it is filed under
21// (design/contribute.md, step 5). attest writes the digest as 64 lowercase
22// hex digits and the key hash as 8.
23var attestationName = regexp.MustCompile(`^refs/the-valley/attestations/([0-9a-f]{64})/([0-9a-f]{8})$`)
24
25// statementType is the first line of every statement's written form
26// (attest/statement.go).
27const statementType = "the-valley/attestation/v1"
28
29// signatureMark opens a signature line in the note format: U+2014 EM DASH,
30// then a space (attest/sign.go).
31const signatureMark = "— "
32
33// checkAttestation decides whether a push may create the attestation ref
34// ref pointing at id. The namespace is create-only, so whoever creates a
35// name first holds it for good, and a name that anyone could take would
36// let one pusher keep another signer's evidence out. So a ref must be what
37// its name says before it may exist:
38//
39// - its name is exactly <digest>/<key hash>. A ref named for the digest
40// alone would stop git creating any ref beneath it.
41// - it points at a tree of notes, and every note is a statement about
42// the digest the name gives.
43// - every note carries a signature under the key hash the name gives.
44// When the host names the keys it accepts, that signature has to
45// verify under one of them, and every signature by a key it names has
46// to verify too.
47//
48// The pusher is not compared with the signer. Evidence is routinely
49// relayed: the host's own key signs what `attest run` observes there, and
50// the operator's key pushes it.
51func (p policy) checkAttestation(ref, id string) error {
52 parts := attestationName.FindStringSubmatch(ref)
53 if parts == nil {
54 return errors.New("an attestation ref is named refs/the-valley/attestations/<digest>/<key hash>, with the tree digest as 64 lowercase hex digits and the signer's key hash as 8")
55 }
56 digest, keyHash := parts[1], parts[2]
57
58 notes, err := p.repo.notes(id)
59 if err != nil {
60 return err
61 }
62 for _, path := range sortedKeys(notes) {
63 if err := p.checkNote(notes[path], digest, keyHash); err != nil {
64 return fmt.Errorf("the note at %s %s", path, err)
65 }
66 }
67 return nil
68}
69
70func (p policy) checkNote(note []byte, digest, keyHash string) error {
71 text, lines, err := splitNote(note)
72 if err != nil {
73 return err
74 }
75 if about, err := subjectDigest(text); err != nil {
76 return err
77 } else if about != digest {
78 return fmt.Errorf("is about the tree %s, not the one the ref is named for", about)
79 }
80
81 filed := false
82 for _, line := range lines {
83 name, encoded, ok := strings.Cut(strings.TrimPrefix(line, signatureMark), " ")
84 blob, err := base64.StdEncoding.DecodeString(encoded)
85 if !ok || err != nil || len(blob) < 5 {
86 return fmt.Errorf("carries a signature line that does not decode: %q", line)
87 }
88 hash := binary.BigEndian.Uint32(blob[:4])
89 claimed := fmt.Sprintf("%08x", hash) == keyHash
90
91 if !p.verify {
92 filed = filed || claimed
93 continue
94 }
95 key, known := p.verifier(name, hash)
96 if !known {
97 continue
98 }
99 if len(blob[4:]) != ed25519.SignatureSize || !ed25519.Verify(key.pub, text, blob[4:]) {
100 return fmt.Errorf("carries a signature by %s+%08x that does not check out", name, hash)
101 }
102 filed = filed || claimed
103 }
104 switch {
105 case filed:
106 return nil
107 case !p.verify:
108 return fmt.Errorf("carries no signature under the key hash %s the ref is named for", keyHash)
109 default:
110 return fmt.Errorf("carries no signature under the key hash %s by a key this host accepts", keyHash)
111 }
112}
113
114func (p policy) verifier(name string, hash uint32) (verifierKey, bool) {
115 for _, k := range p.verifiers {
116 if k.name == name && k.hash == hash {
117 return k, true
118 }
119 }
120 return verifierKey{}, false
121}
122
123// splitNote separates a note's text from its signature lines, the way
124// attest does: the last blank line is the separator, and every line after
125// it is a signature line.
126func splitNote(note []byte) (text []byte, sigs []string, err error) {
127 if !utf8.Valid(note) {
128 return nil, nil, errors.New("is not UTF-8")
129 }
130 split := bytes.LastIndex(note, []byte("\n\n"))
131 if split < 0 {
132 return nil, nil, errors.New("is not a note: no blank line separates the text from its signatures")
133 }
134 text, block := note[:split+1], note[split+2:]
135 if len(block) == 0 || block[len(block)-1] != '\n' {
136 return nil, nil, errors.New("is not a note: the signature block is empty or does not end with a newline")
137 }
138 for _, line := range strings.Split(strings.TrimSuffix(string(block), "\n"), "\n") {
139 if !strings.HasPrefix(line, signatureMark) {
140 return nil, nil, fmt.Errorf("is not a note: %q is not a signature line", line)
141 }
142 sigs = append(sigs, line)
143 }
144 return text, sigs, nil
145}
146
147// subjectDigest reads the primary digest a statement's text names: the
148// subject.primary line names the scheme, and the subject.digest.<scheme>
149// line carries the digest (attest/text.go).
150func subjectDigest(text []byte) (string, error) {
151 lines := strings.Split(strings.TrimSuffix(string(text), "\n"), "\n")
152 if lines[0] != statementType {
153 return "", fmt.Errorf("is not a statement: its text opens with %q, not %q", lines[0], statementType)
154 }
155 fields := map[string]string{}
156 for _, line := range lines[1:] {
157 key, value, _ := strings.Cut(line, " ")
158 fields[key] = value
159 }
160 scheme := fields["subject.primary"]
161 if scheme == "" {
162 return "", errors.New("names no primary subject digest")
163 }
164 digest := fields["subject.digest."+scheme]
165 if digest == "" {
166 return "", fmt.Errorf("names %s as its primary digest and carries no value for it", scheme)
167 }
168 return digest, nil
169}
170
171// verifierKey is a key whose signatures the host accepts, in the note
172// format's verifier key form: name+hash+base64 of the algorithm byte and
173// the public key (attest/sign.go).
174type verifierKey struct {
175 name string
176 hash uint32
177 pub ed25519.PublicKey
178}
179
180const algEd25519 = 1
181
182// readVerifiers adds the verifier keys in one file. A file that does not
183// exist adds none: the compiled file is missing until the first
184// compilation, and then no attestation verifies, which is the direction a
185// missing key has to default in. A line that is not a verifier key, or
186// whose hash is not the one its name and key produce, fails the read.
187func readVerifiers(path string) ([]verifierKey, error) {
188 f, err := os.Open(path)
189 if errors.Is(err, fs.ErrNotExist) {
190 return nil, nil
191 }
192 if err != nil {
193 return nil, err
194 }
195 defer f.Close()
196
197 var keys []verifierKey
198 lines := bufio.NewScanner(f)
199 for n := 1; lines.Scan(); n++ {
200 line := strings.TrimSpace(lines.Text())
201 if line == "" || strings.HasPrefix(line, "#") {
202 continue
203 }
204 k, err := parseVerifierKey(line)
205 if err != nil {
206 return nil, fmt.Errorf("%s:%d: %w", path, n, err)
207 }
208 keys = append(keys, k)
209 }
210 return keys, lines.Err()
211}
212
213func parseVerifierKey(line string) (verifierKey, error) {
214 // Two separators and no more: the base64 that ends the line may hold
215 // a plus of its own.
216 parts := strings.SplitN(line, "+", 3)
217 if len(parts) != 3 {
218 return verifierKey{}, fmt.Errorf("%q is not a verifier key: one is name+hash+base64", line)
219 }
220 raw, err := base64.StdEncoding.DecodeString(parts[2])
221 if err != nil || len(raw) != 1+ed25519.PublicKeySize || raw[0] != algEd25519 {
222 return verifierKey{}, fmt.Errorf("%q is not an ed25519 verifier key", line)
223 }
224 k := verifierKey{name: parts[0], pub: raw[1:]}
225 h := sha256.New()
226 h.Write([]byte(k.name + "\n"))
227 h.Write(raw)
228 k.hash = binary.BigEndian.Uint32(h.Sum(nil))
229 if fmt.Sprintf("%08x", k.hash) != parts[1] {
230 return verifierKey{}, fmt.Errorf("%q carries hash %s, and its name and key produce %08x", line, parts[1], k.hash)
231 }
232 return k, nil
233}