gunk-dev/the-valley

approvalsign.go

source64f5539ce840main's published tip history
13.6 KiB
1package main
2
3// A signed approval (approve.go): the approval key a command signs with,
4// what the host publishes about approval keys, and the note an approval
5// publishes beside its request.
6//
7// An approval key is selected by a flag or the environment, never by
8// default:
9//
10// --approval-key FILE VALLEY_APPROVAL_KEY=FILE an unencrypted OpenSSH ed25519 key
11// --approval-piv VALLEY_APPROVAL_PIV=SLOT the key in a YubiKey's PIV slot
12//
13// A flag beats the environment, and at each level the two kinds exclude
14// each other. --approval-piv signs on VALLEY_APPROVAL_PIV's slot when it is
15// set, and on 9c otherwise; VALLEY_APPROVAL_PIV_READER picks the reader.
16// The key that signs evidence (VALLEY_ATTEST_KEY) is another power and is
17// never read here. With no key selected, nothing in this file runs: approve
18// files the request as it does unsigned, and says no signed approval was
19// written.
20//
21// With a key selected, an approval of a change with a record signs one
22// statement (../approval): the instance identity the host publishes, the
23// project origin's URL names, main, the change, the version and head the
24// approval bound, the record commit that version was read from, the
25// principal the key is published under, and the time. Before any check
26// runs, approve reads the publication once and pins its tree, and refuses
27// a software key that it does not list. After the checks the key signs: a
28// PIV slot's session is opened, asks for the PIN and a touch, and is closed
29// again. The note verifies under the signing key before anything is
30// pushed. The publication is read again just before the push, and an
31// approval whose publication changed meanwhile is refused. The note goes
32// to approval.Ref(main, id) in the one push that files the request, leased
33// against what approve read there, nothing included. Whatever stops the
34// signing, nothing is pushed: approve never falls back to filing unsigned
35// or to another key.
36//
37// The published lists say which keys the host lists for approving, which
38// is what a client can check. What the host decides when it lands a change
39// is its own reading of its own files.
40
41import (
42 "bytes"
43 "errors"
44 "fmt"
45 "io"
46 "os"
47 "strconv"
48 "strings"
49 "time"
50
51 approvals "the-valley/approval"
52 "the-valley/change"
53 "the-valley/note"
54)
55
56// startPIV starts the PIV signer's helper (approval.StartPIV). A test
57// holds a start open through it.
58var startPIV = approvals.StartPIV
59
60// pivSigner is the valley-piv-signer helper a PIV approval key signs
61// through. The package fixes it to the helper's store path at build time
62// where the helper builds, Linux, so no PATH changes which program
63// receives the statements. Elsewhere it is empty, and a PIV key cannot be
64// selected.
65var pivSigner = ""
66
67// The publication's files about approval keys (integrator/signers.go).
68const (
69 signersApprovers = "approval-signers"
70 signersHardware = "approval-signers-hardware"
71 signersInstance = "instance-id"
72)
73
74// approvalFlags are the approval-key flags one command was given.
75type approvalFlags struct {
76 file string
77 piv bool
78}
79
80// take reads the approval-key flag at args[i], if it is one, and returns
81// the index of the last argument it read.
82func (f *approvalFlags) take(args []string, i int) (last int, ok bool, err error) {
83 value := ""
84 switch arg := args[i]; {
85 case arg == "--approval-piv":
86 f.piv = true
87 return i, true, nil
88 case arg == "--approval-key" && i+1 < len(args):
89 value, i = args[i+1], i+1
90 case strings.HasPrefix(arg, "--approval-key="):
91 value = strings.TrimPrefix(arg, "--approval-key=")
92 default:
93 return i, false, nil
94 }
95 if value == "" {
96 return i, true, failure("--approval-key needs a key file")
97 }
98 f.file = value
99 return i, true, nil
100}
101
102// approvalKey is the approval key a command signs with: a software key's
103// file, or a YubiKey's PIV slot.
104type approvalKey struct {
105 file string // a software key; "" for a PIV slot
106 slot, reader string // the PIV slot and reader; "" for the helper's defaults
107 from string // what selected it
108}
109
110// key is the approval key the flags select, or else the environment, or
111// nil when neither selects one.
112func (f approvalFlags) key() (*approvalKey, error) {
113 reader := os.Getenv("VALLEY_APPROVAL_PIV_READER")
114 switch {
115 case f.file != "" && f.piv:
116 return nil, failure("--approval-key and --approval-piv select two approval keys; give one")
117 case f.file != "":
118 return &approvalKey{file: f.file, from: "--approval-key"}, nil
119 case f.piv:
120 return pivKey(os.Getenv("VALLEY_APPROVAL_PIV"), reader, "--approval-piv")
121 }
122 file, slot := os.Getenv("VALLEY_APPROVAL_KEY"), os.Getenv("VALLEY_APPROVAL_PIV")
123 switch {
124 case file != "" && slot != "":
125 return nil, failure("VALLEY_APPROVAL_KEY and VALLEY_APPROVAL_PIV select two approval keys; unset one, or give --approval-key or --approval-piv")
126 case file != "":
127 return &approvalKey{file: file, from: "VALLEY_APPROVAL_KEY"}, nil
128 case slot != "":
129 return pivKey(slot, reader, "VALLEY_APPROVAL_PIV")
130 }
131 return nil, nil
132}
133
134// pivKey is a PIV slot selected as the approval key, where this build has
135// a PIV signer.
136func pivKey(slot, reader, from string) (*approvalKey, error) {
137 if pivSigner == "" {
138 return nil, failure("hardware signing is not available on this platform; " + from + " selects it")
139 }
140 return &approvalKey{slot: slot, reader: reader, from: from}, nil
141}
142
143// software reads a software key.
144func (k *approvalKey) software() (approvals.Key, error) {
145 raw, err := os.ReadFile(k.file)
146 if err != nil {
147 return approvals.Key{}, fmt.Errorf("the approval key %s (from %s) cannot be read: %v", k.file, k.from, err)
148 }
149 key, err := approvals.ParseKey(raw)
150 if err != nil {
151 return approvals.Key{}, fmt.Errorf("the approval key %s (from %s): %v", k.file, k.from, err)
152 }
153 return key, nil
154}
155
156// open is the key's signer, and what closes it: a software key read, or a
157// PIV session started, whose touch requests go to prompt.
158//
159// The session's helper is a's child from the moment it starts, so a
160// signal that interrupts the approval, while the helper reaches the device
161// or waits for the PIN, stops it and waits for it: the helper then resets
162// the YubiKey and the terminal it reads the PIN on. Whether the approval
163// is interrupted, the helper's start and its registration are one
164// critical section under a.mu, which interrupt reads the child under: an
165// interrupt either comes first, and no helper starts, or finds it
166// registered. The terminal's settings are saved before the helper starts,
167// and put back whenever it has ended with them changed, as one killed
168// while echo was off leaves them.
169func (k *approvalKey) open(a *approval, prompt io.Writer) (approvals.Signer, func(), error) {
170 if k.file != "" {
171 key, err := k.software()
172 return key, func() {}, err
173 }
174 tty := saveTerminal()
175 done := make(chan struct{})
176 a.mu.Lock()
177 if a.interrupted {
178 a.mu.Unlock()
179 tty.release()
180 return nil, nil, errors.New("the approval was interrupted before the PIV signer started")
181 }
182 p, err := startPIV(pivSigner, k.slot, k.reader, prompt)
183 if err == nil {
184 a.child, a.childDone, a.tty = p.Process(), done, tty
185 }
186 a.mu.Unlock()
187 if err != nil {
188 tty.release()
189 return nil, nil, err
190 }
191 closeSigner := func() {
192 p.Close()
193 tty.restore()
194 a.mu.Lock()
195 interrupted := a.interrupted
196 a.child, a.tty = nil, nil
197 close(done)
198 a.mu.Unlock()
199 // An interrupt restores the terminal once done is closed, through
200 // this descriptor, and then ends the process; it is not released
201 // under it.
202 if !interrupted {
203 tty.release()
204 }
205 }
206 if err := p.Open(); err != nil {
207 closeSigner()
208 return nil, nil, err
209 }
210 return p, closeSigner, nil
211}
212
213// approvalAuthority is what the host publishes about approval keys, read
214// from one publication tree: the instance's identity and the keys of both
215// approval signers files. An empty file lists no key, so no key of it
216// approves.
217type approvalAuthority struct {
218 instance, oid, where string // where it was read, and the tree
219 id string // instance-id
220 approvers, hardware []note.VerifierKey
221}
222
223// readApprovalAuthority reads the publication's approval files. A
224// publication that is missing, or whose approval files are missing, are
225// not files or do not read, is an error.
226func readApprovalAuthority(g git) (*approvalAuthority, error) {
227 p, err := readSigners(g)
228 if err != nil {
229 return nil, err
230 }
231 if p == nil {
232 return nil, errors.New("the host publishes no " + signersRef + ", so no approval key is known")
233 }
234 read := func(file string) (string, error) {
235 if p.kinds[file] != "100644 blob" {
236 return "", fmt.Errorf("%s holds no %s file", p.where, file)
237 }
238 body, err := g.restricted().output(true, "cat-file", "blob", p.blobs[file])
239 if err != nil {
240 return "", fmt.Errorf("could not read %s in %s", file, p.where)
241 }
242 return body, nil
243 }
244 a := &approvalAuthority{instance: p.instance, oid: p.oid, where: p.where}
245 if a.id, err = read(signersInstance); err != nil {
246 return nil, err
247 }
248 if len(a.id) != 64 || strings.Trim(a.id, "0123456789abcdef") != "" {
249 return nil, fmt.Errorf("%s in %s is not 64 lowercase hex digits", signersInstance, p.where)
250 }
251 for file, into := range map[string]*[]note.VerifierKey{signersApprovers: &a.approvers, signersHardware: &a.hardware} {
252 body, err := read(file)
253 if err != nil {
254 return nil, err
255 }
256 if *into, err = note.ParseVerifierKeys([]byte(body)); err != nil {
257 return nil, fmt.Errorf("%s in %s does not read: %v", file, p.where, err)
258 }
259 }
260 return a, nil
261}
262
263// unchanged reports whether the host still publishes the tree a was read
264// from.
265func (a *approvalAuthority) unchanged(g git) (bool, error) {
266 now, err := remoteRef(g.restricted(), a.instance, signersRef)
267 return now == a.oid, err
268}
269
270// principal is the one name approval-signers lists pub under, and whether
271// approval-signers-hardware lists pub under that name too. A key listed
272// under two names is refused, as is a key approval-signers-hardware does
273// not list when hardware is required. why is the refusal's reason, short
274// enough for a verdict line.
275func (a *approvalAuthority) principal(pub []byte, hardwareRequired bool) (name string, hardware bool, why string) {
276 names := map[string]bool{}
277 for _, k := range a.approvers {
278 if bytes.Equal(k.Pub, pub) {
279 names[k.Name] = true
280 }
281 }
282 switch len(names) {
283 case 0:
284 return "", false, "approval key is not listed in " + signersApprovers
285 case 1:
286 default:
287 return "", false, "approval key is listed under several principals"
288 }
289 for n := range names {
290 name = n
291 }
292 for _, k := range a.hardware {
293 hardware = hardware || (k.Name == name && bytes.Equal(k.Pub, pub))
294 }
295 if hardwareRequired && !hardware {
296 return "", false, "policy requires a hardware key, and this key is none"
297 }
298 return name, hardware, ""
299}
300
301// signedApproval is the note one approval signed, stored in this
302// repository, and what -v says of it.
303type signedApproval struct {
304 blob, principal string
305 keyhash uint32
306 hardware bool
307}
308
309// prepareSigning reads, before any check runs, what a signed approval is
310// held to: the publication, and for a software key that it lists the key.
311// A PIV key is read when it signs. hardware is whether the policy requires
312// a hardware key.
313func (a *approval) prepareSigning(hardware bool) error {
314 auth, err := readApprovalAuthority(a.g)
315 if err != nil {
316 fmt.Fprintf(a.stderr, "valley: %s\n", oneLine(err.Error()))
317 return a.declined("could not read the published approval keys", act{})
318 }
319 a.auth, a.hardware = auth, hardware
320 if a.key.file == "" {
321 return nil
322 }
323 k, err := a.key.software()
324 if err != nil {
325 fmt.Fprintf(a.stderr, "valley: %s\n", oneLine(err.Error()))
326 return a.declined("could not read the approval key", act{})
327 }
328 if _, _, why := auth.principal(k.Public(), hardware); why != "" {
329 return a.declined(why, act{})
330 }
331 return nil
332}
333
334// sign signs the approval of the version bound, as the statement names it
335// from what approve read, and stores the note in this repository. A
336// signer that cannot sign, or whose note does not verify under its own
337// key, refuses the approval.
338func (a *approval) sign() (*signedApproval, error) {
339 if a.frozenRecord == "" || a.frozenVersion == "" {
340 return nil, a.declined("no recorded version is bound to sign", act{})
341 }
342 project, err := originName(a.g)
343 if err != nil {
344 fmt.Fprintf(a.stderr, "valley: %s\n", oneLine(err.Error()))
345 return nil, a.declined("no project to sign the approval for", act{})
346 }
347 version, _ := strconv.Atoi(a.frozenVersion)
348 signer, closeSigner, err := a.key.open(a, a.stderr)
349 if err != nil {
350 return nil, a.notSigned(err)
351 }
352 defer closeSigner()
353 pub := signer.Public()
354 principal, hardware, why := a.auth.principal(pub, a.hardware)
355 if why != "" {
356 return nil, a.declined(why, act{})
357 }
358 s := approvals.Statement{Instance: a.auth.id, Project: project, Target: recordTarget, Change: a.id,
359 Version: version, Head: change.HeadPrefix + a.bound, Record: change.HeadPrefix + a.frozenRecord,
360 Principal: principal, Issued: time.Now().UTC().Truncate(time.Second)}
361 n, err := approvals.Sign(s, signer)
362 if err != nil {
363 return nil, a.notSigned(err)
364 }
365 blob, err := a.g.input(true, bytes.NewReader(n), "hash-object", "-w", "--stdin")
366 if err != nil {
367 return nil, a.declined("could not store the signed approval", act{})
368 }
369 return &signedApproval{blob: blob, principal: principal, keyhash: note.KeyHash(principal, pub), hardware: hardware}, nil
370}
371
372// notSigned refuses an approval its key did not sign, saying why on a
373// line of its own: a device's refusal, such as a PIN cancelled or no
374// touch, or a signature that does not verify under the signer's key. What
375// a key file or the helper says is held to one line of printable text.
376func (a *approval) notSigned(err error) error {
377 if !a.stopped() {
378 fmt.Fprintf(a.stderr, "valley: %s\n", oneLine(err.Error()))
379 }
380 return a.declined("approval not signed", act{})
381}