gunk-dev/the-valley

attestation_test.go

source87ce0621d5ddmain's published tip history
31.5 KiB
1package main
2
3import (
4 "bytes"
5 "crypto/ecdsa"
6 "crypto/ed25519"
7 "crypto/elliptic"
8 "crypto/rand"
9 "crypto/sha256"
10 "crypto/x509"
11 "crypto/x509/pkix"
12 "encoding/asn1"
13 "encoding/base64"
14 "encoding/binary"
15 "encoding/hex"
16 "encoding/pem"
17 "math/big"
18 "os"
19 "slices"
20 "strings"
21 "testing"
22 "time"
23
24 "the-valley/note"
25)
26
27// The device fixtures are the-valley operator's own approval key, from a
28// YubiKey 5C (firmware 5.7.4): an Ed25519 key generated in PIV slot 9c
29// with PIN policy always and touch policy always, the slot certificate the
30// YubiKey wrote for it, its f9 certificate, and a 2075-byte text the key
31// signed with a touch (`yubico-piv-tool -a verify-pin --sign -A ED25519 -s
32// 9c`). They are test vectors and stay in testdata/ (testdata/README.md):
33// only a real device's chain verifies to Yubico's root.
34
35func testdata(t *testing.T, name string) string {
36 t.Helper()
37 b, err := os.ReadFile("testdata/" + name)
38 if err != nil {
39 t.Fatal(err)
40 }
41 return string(b)
42}
43
44// deviceKey is the device key's registry line.
45func deviceKey(t *testing.T) string {
46 return strings.TrimSpace(testdata(t, "valley-approve.pub"))
47}
48
49// deviceReport is what the compiler reports for the device's attestation.
50func deviceReport(t *testing.T) string {
51 return strings.TrimSpace(testdata(t, "valley-approve.report"))
52}
53
54func deviceAttestation(t *testing.T) attestation {
55 return attestation{Slot: testdata(t, "valley-approve.attest.pem"), F9: testdata(t, "yubico-f9.pem")}
56}
57
58func devicePublic(t *testing.T) ed25519.PublicKey {
59 t.Helper()
60 pub, err := sshEd25519Public(deviceKey(t))
61 if err != nil {
62 t.Fatal(err)
63 }
64 return pub
65}
66
67// The registry's ssh-ed25519 line and the PEM public key the YubiKey
68// exported are one key.
69func TestTheDeviceKeyIsTheExportedKey(t *testing.T) {
70 block, _ := pem.Decode([]byte(testdata(t, "valley-approve.pub.pem")))
71 exported, err := x509.ParsePKIXPublicKey(block.Bytes)
72 if err != nil {
73 t.Fatal(err)
74 }
75 if !devicePublic(t).Equal(exported) {
76 t.Fatalf("%s is not the exported key", deviceKey(t))
77 }
78}
79
80// The pinned root is the one Yubico publishes, by the fingerprint Yubico
81// publishes for it, and each pinned intermediate is a PIV one beneath it.
82func TestThePinnedCertificatesAreYubicosPIVChain(t *testing.T) {
83 const fingerprint = "62:76:0C:6A:6E:F9:16:79:F4:54:C8:90:2B:80:FD:00:98:25:B3:F2:5D:A9:0F:1F:BA:CE:2E:C6:58:6C:D5:A8"
84 block, _ := pem.Decode(yubicoRootPEM)
85 sum := sha256.Sum256(block.Bytes)
86 got := strings.ToUpper(hex.EncodeToString(sum[:]))
87 if got != strings.ReplaceAll(fingerprint, ":", "") {
88 t.Errorf("the pinned root's SHA-256 is %s, not Yubico Attestation Root 1's", got)
89 }
90 root, err := x509.ParseCertificate(block.Bytes)
91 if err != nil {
92 t.Fatal(err)
93 }
94 if root.Subject.CommonName != "Yubico Attestation Root 1" {
95 t.Errorf("the pinned root is %q", root.Subject.CommonName)
96 }
97
98 var names []string
99 for rest := yubicoIntermediatesPEM; ; {
100 var block *pem.Block
101 if block, rest = pem.Decode(rest); block == nil {
102 break
103 }
104 cert, err := x509.ParseCertificate(block.Bytes)
105 if err != nil {
106 t.Fatal(err)
107 }
108 names = append(names, cert.Subject.CommonName)
109 if _, err := cert.Verify(x509.VerifyOptions{
110 Roots: yubico.roots, Intermediates: yubico.intermediates,
111 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
112 }); err != nil {
113 t.Errorf("the pinned %s does not verify to the root: %v", cert.Subject.CommonName, err)
114 }
115 }
116 want := []string{
117 "Yubico Attestation Intermediate A 1",
118 "Yubico Attestation Intermediate B 1",
119 "Yubico PIV Attestation A 1",
120 "Yubico PIV Attestation B 1",
121 "Yubico PIV Attestation B2 1",
122 }
123 if !slices.Equal(names, want) {
124 t.Errorf("the pinned intermediates are %q, want %q", names, want)
125 }
126}
127
128// The real device's attestation verifies with Go's crypto/x509, through
129// its f9 certificate, Yubico PIV Attestation B 1 and Yubico Attestation
130// Intermediate B 1, to the pinned root, and says what the device spike
131// observed.
132func TestTheDeviceAttestationVerifies(t *testing.T) {
133 got, err := verifyAttestation(deviceAttestation(t), devicePublic(t), day(t, "2026-10-22"), yubico)
134 if err != nil {
135 t.Fatal(err)
136 }
137 if !got.hardware() {
138 t.Error("the device's touch-always key is not a hardware key")
139 }
140 if want := deviceReport(t); got.String() != want {
141 t.Errorf("reported %q, want %q", got, want)
142 }
143}
144
145// The example registry's attestation (examples/identity/attested/) is a
146// synthetic chain under a test-only root, "the-valley example attestation
147// root, not Yubico". The compiler refuses it under the pinned Yubico
148// roots, so an entry copied from the example compiles only with a real
149// device's certificates. Under the test-only root it verifies, so the root
150// is the one thing wrong with it. The identity-e2e check holds the example
151// to these same certificates and has the compiler refuse it.
152func TestTheExampleAttestationVerifiesOnlyUnderItsTestRoot(t *testing.T) {
153 const exampleKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAID/3+vgQhY5cdQ4AqspQ1A2yW60nn4j1FOyx04WfuQjc"
154 pub, err := sshEd25519Public(exampleKey)
155 if err != nil {
156 t.Fatal(err)
157 }
158 if !testPrivateKey("the-valley example approval key").Public().(ed25519.PublicKey).Equal(pub) {
159 t.Fatal("the example key is not the one derived from its published seed")
160 }
161 example := attestation{Slot: testdata(t, "example-slot.pem"), F9: testdata(t, "example-f9.pem")}
162 on := day(t, "2026-10-23")
163
164 _, err = verifyAttestation(example, pub, on, yubico)
165 if err == nil || !strings.Contains(err.Error(), "does not verify to Yubico Attestation Root 1: x509: certificate signed by unknown authority") {
166 t.Errorf("under the pinned Yubico roots: error = %v", err)
167 }
168
169 root, err := x509.ParseCertificate(pemBytes(t, testdata(t, "example-root.pem")))
170 if err != nil {
171 t.Fatal(err)
172 }
173 if root.Subject.CommonName != "the-valley example attestation root, not Yubico" {
174 t.Fatalf("the test-only root is %q", root.Subject.CommonName)
175 }
176 testOnly := trust{roots: x509.NewCertPool(), intermediates: x509.NewCertPool()}
177 testOnly.roots.AddCert(root)
178 got, err := verifyAttestation(example, pub, on, testOnly)
179 if err != nil {
180 t.Fatalf("under the test-only root: %v", err)
181 }
182 if want := "YubiKey serial 12345678, firmware 5.7.4, PIN policy always, touch policy always"; got.String() != want || !got.hardware() {
183 t.Errorf("under the test-only root: reported %q, hardware %v", got, got.hardware())
184 }
185}
186
187// Each way the device's own attestation can be wrong is refused. None of
188// them leaves a key that is merely not hardware: each is an error.
189func TestAttestationsThatDoNotVerifyAreRefused(t *testing.T) {
190 good := deviceAttestation(t)
191 pub := devicePublic(t)
192 on := day(t, "2026-10-22")
193 other := newTestPKI(t)
194
195 slotDER := pemBytes(t, good.Slot)
196 f9DER := pemBytes(t, good.F9)
197
198 // The touch policy is inside what Yubico's signature covers: the
199 // policy extension's value, 03 02, edited to 03 03 (cached).
200 policy := []byte{0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xc4, 0x0a, 0x03, 0x08, 0x04, 0x02, 0x03, 0x02}
201 if bytes.Count(slotDER, policy) != 1 {
202 t.Fatal("the slot certificate's policy extension is not where this test looks")
203 }
204 cached := bytes.Replace(slotDER, policy, append(policy[:len(policy)-1:len(policy)-1], 0x03), 1)
205
206 for name, c := range map[string]struct {
207 a attestation
208 pub ed25519.PublicKey
209 on time.Time
210 trust trust
211 want string
212 }{
213 "another root": {good, pub, on, other.trust, "does not verify"},
214 "no intermediates": {good, pub, on,
215 trust{roots: yubico.roots, intermediates: x509.NewCertPool()}, "does not verify"},
216 "a slot certificate with its policy edited": {
217 attestation{Slot: pemText(cached), F9: good.F9}, pub, on, yubico, "does not verify"},
218 "a slot certificate with its signature altered": {
219 attestation{Slot: pemText(flipLast(slotDER)), F9: good.F9}, pub, on, yubico, "does not verify"},
220 "an f9 certificate with its signature altered": {
221 attestation{Slot: good.Slot, F9: pemText(flipLast(f9DER))}, pub, on, yubico, "does not verify"},
222 "the slot certificate given as f9": {
223 attestation{Slot: good.Slot, F9: good.Slot}, pub, on, yubico, "does not verify"},
224 "another key": {good, ed25519.PublicKey(make([]byte, ed25519.PublicKeySize)), on, yubico, "a different key"},
225 "a day before the certificates": {good, pub, day(t, "2024-11-30"), yubico, "does not verify"},
226 "a slot that is not PEM": {
227 attestation{Slot: "MIICJzCCAQ+gAwIBAgIQ", F9: good.F9}, pub, on, yubico, "not PEM"},
228 "text beside the PEM": {
229 attestation{Slot: good.Slot + "trailing words\n", F9: good.F9}, pub, on, yubico, "beside its one PEM block"},
230 "text before the PEM": {
231 attestation{Slot: "leading words\n" + good.Slot, F9: good.F9}, pub, on, yubico, "beside its one PEM block"},
232 "two certificates as f9": {
233 attestation{Slot: good.Slot, F9: good.F9 + good.F9}, pub, on, yubico, "beside its one PEM block"},
234 "a public key as the slot": {
235 attestation{Slot: testdata(t, "valley-approve.pub.pem"), F9: good.F9}, pub, on, yubico, "not a plain certificate"},
236 } {
237 _, err := verifyAttestation(c.a, c.pub, c.on, c.trust)
238 if err == nil || !strings.Contains(err.Error(), c.want) {
239 t.Errorf("%s: error = %v, want one saying %q", name, err, c.want)
240 }
241 }
242}
243
244// The touch policy decides: only always makes a hardware key. The device
245// fixture is touch-always, so the other policies are attested here under
246// a stand-in for Yubico's PKI.
247func TestOnlyTouchAlwaysIsHardware(t *testing.T) {
248 pki := newTestPKI(t)
249 pub, _ := testKey("approver")
250 for touch, want := range map[byte]bool{1: false, 2: true, 3: false} {
251 got, err := verifyAttestation(pki.attest(t, pub, policyExtension(3, touch)), pub, day(t, "2026-10-22"), pki.trust)
252 if err != nil {
253 t.Fatalf("touch policy %d: %v", touch, err)
254 }
255 if got.hardware() != want {
256 t.Errorf("touch policy %d: hardware = %v, want %v", touch, got.hardware(), want)
257 }
258 }
259}
260
261// Every signed fault fails the compilation, one fault at a time. Each case
262// is a stand-in attestation of the same key that a key holder could
263// present, correct in every respect but the one its name gives, and
264// signed by the keys its certificates name. The control case, with no
265// fault, compiles the key into the hardware file, so each failure is the
266// fault's alone.
267func TestEachSignedFaultFailsTheCompilation(t *testing.T) {
268 pki := newTestPKI(t)
269 trustBoth(t, pki)
270 pub, line := testKey("approver")
271
272 // device is an f9 certificate the stand-in intermediate signs, with
273 // its template edited first.
274 device := func(edit func(*x509.Certificate)) (*x509.Certificate, ed25519.PrivateKey) {
275 f9Pub, f9Key, _ := ed25519.GenerateKey(rand.Reader)
276 template := f9Template()
277 edit(template)
278 return pki.issue(t, pki.intermediate, pki.intermediateKey, template, f9Pub), f9Key
279 }
280 // slot is f9's attestation of the key, touch policy always, with its
281 // template edited first. It is not parsed here, so it may be one Go
282 // refuses to read.
283 slot := func(f9 *x509.Certificate, f9Key ed25519.PrivateKey, edit func(*x509.Certificate)) attestation {
284 template := leafTemplate(policyExtension(3, 2))
285 edit(template)
286 return attestation{Slot: pemText(sign(t, template, f9, f9Key, pub)), F9: pemText(f9.Raw)}
287 }
288 under := func(edit func(*x509.Certificate)) attestation {
289 f9, f9Key := device(edit)
290 return slot(f9, f9Key, none)
291 }
292 stated := func(edit func(*x509.Certificate)) attestation {
293 return slot(pki.f9, pki.f9Key, edit)
294 }
295 // policy replaces the policy extension's value.
296 policy := func(value ...byte) func(*x509.Certificate) {
297 return func(c *x509.Certificate) { c.ExtraExtensions[2].Value = value }
298 }
299 expired := func(c *x509.Certificate) { c.NotAfter = time.Date(2026, 10, 21, 0, 0, 0, 0, time.UTC) }
300
301 // A slot certificate signed by f9's key under another issuer name.
302 renamed := *pki.f9
303 renamed.RawSubject = nil
304 renamed.Subject = pkix.Name{CommonName: "YubiKey PIV Attestation, another"}
305
306 // An f9 certificate the key holder made: self-signed, or signed by
307 // the holder's own key under the stand-in intermediate's name.
308 ownPub, ownKey, _ := ed25519.GenerateKey(rand.Reader)
309 ownF9 := pki.issue(t, nil, ownKey, f9Template(), ownPub)
310 forger := *pki.intermediate
311 forger.PublicKey = ownPub
312 forgedPub, forgedKey, _ := ed25519.GenerateKey(rand.Reader)
313 forgedF9 := pki.issue(t, &forger, ownKey, f9Template(), forgedPub)
314 // A slot certificate the attested key signed for itself.
315 selfSigned := pki.issue(t, nil, testPrivateKey("approver"), leafTemplate(policyExtension(3, 2)), pub)
316
317 ec, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
318 if err != nil {
319 t.Fatal(err)
320 }
321 ecSlot := pki.issue(t, pki.f9, pki.f9Key, leafTemplate(policyExtension(3, 2)), &ec.PublicKey)
322 direct := pki.issue(t, pki.intermediate, pki.intermediateKey, leafTemplate(policyExtension(3, 2)), pub)
323
324 compile := func(a attestation) (artifacts, error) {
325 r := governedRegistry()
326 r.Boundaries["approve"] = boundary{Kind: boundaryApprove}
327 founder := r.Principals["founder"]
328 founder.Grants["approve"] = grant{Boundary: "approve"}
329 founder.Keys = append(founder.Keys, key{Class: sshEd25519, Bound: "hardware", Public: line, Attestation: &a})
330 r.Principals["founder"] = founder
331 return render(r, day(t, "2026-10-22"), nil)
332 }
333
334 // Three faults keep a signature f9's key made and only break the
335 // chain around it: f9 is no CA, f9 states no basic constraints, or the
336 // slot certificate names another issuer. Each slot certificate is
337 // checked here to verify under its f9 key, so the refusal below is the
338 // fault's and not a bad signature's.
339 nonCA := under(func(c *x509.Certificate) { c.IsCA, c.MaxPathLen, c.MaxPathLenZero = false, 0, false })
340 noConstraints := under(func(c *x509.Certificate) { c.BasicConstraintsValid = false })
341 misnamed := slot(&renamed, pki.f9Key, none)
342 for _, a := range []attestation{nonCA, noConstraints, misnamed} {
343 slotCert, err := x509.ParseCertificate(pemBytes(t, a.Slot))
344 if err != nil {
345 t.Fatal(err)
346 }
347 f9Cert, err := x509.ParseCertificate(pemBytes(t, a.F9))
348 if err != nil {
349 t.Fatal(err)
350 }
351 if err := f9Cert.CheckSignature(slotCert.SignatureAlgorithm, slotCert.RawTBSCertificate, slotCert.Signature); err != nil {
352 t.Fatalf("a slot certificate meant to be signed by its f9 key is not: %v", err)
353 }
354 }
355
356 control, err := compile(stated(none))
357 if err != nil {
358 t.Fatalf("the attestation with no fault: %v", err)
359 }
360 if !strings.Contains(string(control.approvalHardware), note.NewVerifierKey("founder", pub).String()) {
361 t.Fatalf("the attestation with no fault left the key out of the hardware file:\n%s", control.approvalHardware)
362 }
363
364 for _, c := range []struct {
365 name string
366 a attestation
367 want string
368 }{
369 // The chain.
370 {"an expired slot certificate", stated(expired), "has expired"},
371 {"an expired f9 certificate", under(expired), "has expired"},
372 {"an f9 certificate that is not a CA", nonCA, "parent certificate cannot sign"},
373 {"an f9 certificate without basic constraints", noConstraints, "parent certificate cannot sign"},
374 {"an issuer name that is not f9's", misnamed, "signed by unknown authority"},
375 {"a slot certificate the intermediate signed", attestation{Slot: pemText(direct.Raw), F9: pemText(pki.f9.Raw)}, "without its f9 certificate"},
376 // Anchors the key holder supplies.
377 {"a self-signed f9 certificate", slot(ownF9, ownKey, none), "signed by unknown authority"},
378 {"an f9 certificate the holder signed under the intermediate's name", slot(forgedF9, forgedKey, none), "Ed25519 verification failure"},
379 {"a self-signed slot certificate", attestation{Slot: pemText(selfSigned.Raw), F9: pemText(pki.f9.Raw)}, "signed by unknown authority"},
380 // The key.
381 {"an ECDSA key", attestation{Slot: pemText(ecSlot.Raw), F9: pemText(pki.f9.Raw)}, "attests a key of type ECDSA, not Ed25519"},
382 // The policy extension.
383 {"no policy extension", stated(func(c *x509.Certificate) { c.ExtraExtensions = c.ExtraExtensions[:2] }), "states no PIN and touch policy"},
384 {"a critical policy extension", stated(func(c *x509.Certificate) { c.ExtraExtensions[2].Critical = true }), "unhandled critical extension"},
385 {"two policy extensions", stated(func(c *x509.Certificate) {
386 c.ExtraExtensions = append(c.ExtraExtensions, policyExtension(3, 3))
387 }), "duplicate extension"},
388 {"a policy of no bytes", stated(policy()), "PIN and touch policy"},
389 {"a policy of one byte", stated(policy(3)), "is 1 byte(s), not 2"},
390 {"a policy of three bytes", stated(policy(3, 2, 2)), "is 3 byte(s), not 2"},
391 {"PIN policy 0x00", stated(policy(0, 2)), "PIN policy 0x00, which Yubico does not specify"},
392 {"PIN policy 0x04", stated(policy(4, 2)), "PIN policy 0x04, which Yubico does not specify"},
393 {"PIN policy 0xff", stated(policy(0xff, 2)), "PIN policy 0xff, which Yubico does not specify"},
394 {"touch policy 0x00", stated(policy(3, 0)), "touch policy 0x00, which Yubico does not specify"},
395 {"touch policy 0x04", stated(policy(3, 4)), "touch policy 0x04, which Yubico does not specify"},
396 {"touch policy 0xff", stated(policy(3, 0xff)), "touch policy 0xff, which Yubico does not specify"},
397 } {
398 a, err := compile(c.a)
399 if err == nil {
400 t.Errorf("%s: compiled, with hardware file\n%s", c.name, a.approvalHardware)
401 continue
402 }
403 if want := "founder: key 1: "; !strings.Contains(err.Error(), want) || !strings.Contains(err.Error(), c.want) {
404 t.Errorf("%s: error = %v, want one naming founder's key 1 and saying %q", c.name, err, c.want)
405 }
406 }
407}
408
409// none edits nothing.
410func none(*x509.Certificate) {}
411
412// approvalRegistry exercises every reason a key is or is not in the
413// approval files. founder governs and approves with three keys: an
414// ordinary one, the device's touch-always key, and a stand-in key whose
415// touch is cached. second approves under the grant's first name with a
416// stand-in touch-always key. departed has expired, pusher holds no
417// approve grant, and robot is not a human, so none of their keys appear.
418func approvalRegistry(t *testing.T, pki testPKI) registry {
419 t.Helper()
420 r := governedRegistry()
421 r.Boundaries["approve"] = boundary{Kind: boundaryApprove}
422 r.Boundaries["request"] = boundary{Kind: boundaryRequest}
423 approve := grant{Boundary: "approve"}
424 attestedKey := func(seed string, touch byte) key {
425 pub, line := testKey(seed)
426 a := pki.attest(t, pub, policyExtension(3, touch))
427 return key{Class: sshEd25519, Bound: "hardware", Public: line, Attestation: &a}
428 }
429 plainKey := func(seed string) key {
430 _, line := testKey(seed)
431 return key{Class: sshEd25519, Bound: "host", Public: line}
432 }
433
434 founder := r.Principals["founder"]
435 device := deviceAttestation(t)
436 founder.Keys = append(founder.Keys,
437 key{Class: sshEd25519, Bound: "hardware", Public: deviceKey(t), Attestation: &device},
438 attestedKey("cached", 3),
439 )
440 founder.Grants["approve"] = approve
441 r.Principals["founder"] = founder
442
443 r.Principals["second"] = principal{
444 Kind: kindHuman,
445 Keys: []key{attestedKey("second", 2)},
446 Grants: map[string]grant{"request": {Boundary: "request"}},
447 }
448 r.Principals["departed"] = principal{
449 Kind: kindHuman,
450 Keys: []key{attestedKey("departed", 2)},
451 Grants: map[string]grant{"approve": approve},
452 Expires: "2026-09-01",
453 }
454 r.Principals["pusher"] = principal{
455 Kind: kindHuman,
456 Keys: []key{plainKey("pusher")},
457 Grants: map[string]grant{"push": {Boundary: "push"}},
458 }
459 r.Principals["robot"] = principal{
460 Kind: "machine",
461 Keys: []key{attestedKey("robot", 2)},
462 Grants: map[string]grant{"approve": approve},
463 Expires: "2027-01-01",
464 }
465 return r
466}
467
468// The whole of both files, byte for byte, with the lines written by the
469// note package rather than by the compiler.
470func TestApprovalFilesListHumanApproversAndTheirHardwareKeys(t *testing.T) {
471 pki := newTestPKI(t)
472 trustBoth(t, pki)
473 r := approvalRegistry(t, pki)
474 a, err := render(r, day(t, "2026-10-22"), nil)
475 if err != nil {
476 t.Fatal(err)
477 }
478
479 line := func(name, public string) string {
480 pub, err := sshEd25519Public(public)
481 if err != nil {
482 t.Fatal(err)
483 }
484 return note.NewVerifierKey(name, pub).String()
485 }
486 _, cached := testKey("cached")
487 _, second := testKey("second")
488 founderPlain := r.Principals["founder"].Keys[0].Public
489 all := []string{line("founder", founderPlain), line("founder", deviceKey(t)), line("founder", cached), line("second", second)}
490 hardware := []string{line("founder", deviceKey(t)), line("second", second)}
491 for _, c := range []struct {
492 name string
493 got []byte
494 count int
495 head string
496 want []string
497 }{
498 {"approval-signers", a.approvalSigners, a.approvers, approvalSignersHeader, all},
499 {"approval-signers-hardware", a.approvalHardware, a.hardware, approvalHardwareHeader, hardware},
500 } {
501 slices.Sort(c.want)
502 want := c.head + strings.Join(c.want, "\n") + "\n"
503 if string(c.got) != want {
504 t.Errorf("%s =\n%s\nwant\n%s", c.name, c.got, want)
505 }
506 if c.count != len(c.want) {
507 t.Errorf("%s: count %d, want %d", c.name, c.count, len(c.want))
508 }
509 }
510
511 // Each attested key of a principal still in force is reported for
512 // review, and the expired one is not.
513 for _, want := range []string{
514 "founder: key 1 is on " + deviceReport(t) + "; it approves as a hardware key",
515 "founder: key 2 is on YubiKey serial 12345678, firmware 5.7.4, PIN policy always, touch policy cached; it approves, but not as a hardware key, because its touch policy is not always",
516 "robot: key 0 is on YubiKey serial 12345678, firmware 5.7.4, PIN policy always, touch policy always; its principal approves nothing",
517 } {
518 if !slices.Contains(a.notes, want) {
519 t.Errorf("no report %q among %q", want, a.notes)
520 }
521 }
522 for _, n := range a.notes {
523 if strings.HasPrefix(n, "departed: key") {
524 t.Errorf("an expired entry's key was reported: %q", n)
525 }
526 }
527}
528
529// A registry without approvers compiles both files holding only their
530// headers, and the note reader reads each as no keys.
531func TestARegistryWithoutApproversCompilesEmptyFiles(t *testing.T) {
532 a, err := render(governedRegistry(), day(t, "2026-10-22"), nil)
533 if err != nil {
534 t.Fatal(err)
535 }
536 for _, f := range [][]byte{a.approvalSigners, a.approvalHardware} {
537 keys, err := note.ParseVerifierKeys(f)
538 if err != nil || len(keys) != 0 {
539 t.Errorf("%q: %d keys, %v", f, len(keys), err)
540 }
541 }
542 if string(a.approvalSigners) != approvalSignersHeader || string(a.approvalHardware) != approvalHardwareHeader {
543 t.Errorf("the empty files are %q and %q", a.approvalSigners, a.approvalHardware)
544 }
545}
546
547// Rendering is reproducible: the order of principals and keys in the
548// registry does not reach the files.
549func TestApprovalFilesRenderTheSameWhateverTheOrder(t *testing.T) {
550 pki := newTestPKI(t)
551 trustBoth(t, pki)
552 r := approvalRegistry(t, pki)
553 first, err := render(r, day(t, "2026-10-22"), nil)
554 if err != nil {
555 t.Fatal(err)
556 }
557 founder := r.Principals["founder"]
558 slices.Reverse(founder.Keys)
559 r.Principals["founder"] = founder
560 second, err := render(r, day(t, "2026-10-22"), nil)
561 if err != nil {
562 t.Fatal(err)
563 }
564 if !bytes.Equal(first.approvalSigners, second.approvalSigners) || !bytes.Equal(first.approvalHardware, second.approvalHardware) {
565 t.Error("reordering founder's keys changed the approval files")
566 }
567}
568
569// A key that approves belongs to one principal, so the render fails when
570// another principal lists it too, whatever that principal holds.
571func TestAKeyThatApprovesBelongsToOnePrincipal(t *testing.T) {
572 pki := newTestPKI(t)
573 trustBoth(t, pki)
574 for name, holder := range map[string]principal{
575 "another approver": {Kind: kindHuman, Grants: map[string]grant{"approve": {Boundary: "approve"}}},
576 "a principal holding nothing": {Kind: kindHuman, Grants: map[string]grant{}},
577 "a machine": {Kind: "machine", Grants: map[string]grant{}, Expires: "2027-01-01"},
578 } {
579 r := approvalRegistry(t, pki)
580 device := deviceAttestation(t)
581 holder.Keys = []key{{Class: sshEd25519, Bound: "hardware", Public: deviceKey(t), Attestation: &device}}
582 r.Principals["impostor"] = holder
583 _, err := render(r, day(t, "2026-10-22"), nil)
584 if err == nil || !strings.Contains(err.Error(), "founder: key 1 is also impostor's, and a key that approves belongs to one principal") {
585 t.Errorf("%s holding founder's approval key: error = %v", name, err)
586 }
587 }
588}
589
590// An attestation that is offered and does not verify fails the whole
591// render. It is never read as no attestation, which would compile the key
592// into approval-signers as an ordinary key.
593func TestAnAttestationThatDoesNotVerifyFailsTheRender(t *testing.T) {
594 r := governedRegistry()
595 r.Boundaries["approve"] = boundary{Kind: boundaryApprove}
596 founder := r.Principals["founder"]
597 founder.Grants["approve"] = grant{Boundary: "approve"}
598 // The device's attestation, offered for another key.
599 device := deviceAttestation(t)
600 founder.Keys[0].Attestation = &device
601 r.Principals["founder"] = founder
602 _, err := render(r, day(t, "2026-10-22"), nil)
603 if err == nil || !strings.Contains(err.Error(), "founder: key 0: the slot certificate attests a different key") {
604 t.Errorf("render error = %v", err)
605 }
606}
607
608// The device's own signature, made with a touch, opens against both files
609// the device's registry entry compiles to. The same key without its
610// attestation is in approval-signers alone, and the signature does not
611// open against the hardware file.
612func TestTheDeviceSignatureOpensAgainstTheCompiledFiles(t *testing.T) {
613 text := []byte(testdata(t, "spike.txt"))
614 sig, err := base64.StdEncoding.DecodeString(strings.TrimSpace(testdata(t, "spike.sig.b64")))
615 if err != nil {
616 t.Fatal(err)
617 }
618 signed := func(name string) []byte {
619 blob := binary.BigEndian.AppendUint32(nil, note.KeyHash(name, devicePublic(t)))
620 return append(append(append([]byte{}, text...), '\n'),
621 note.Mark+name+" "+base64.StdEncoding.EncodeToString(append(blob, sig...))+"\n"...)
622 }
623 compiled := func(attested bool) artifacts {
624 r := governedRegistry()
625 r.Boundaries["approve"] = boundary{Kind: boundaryApprove}
626 founder := r.Principals["founder"]
627 founder.Grants["approve"] = grant{Boundary: "approve"}
628 k := key{Class: sshEd25519, Bound: "hardware", Public: deviceKey(t)}
629 if attested {
630 device := deviceAttestation(t)
631 k.Attestation = &device
632 }
633 founder.Keys = append(founder.Keys, k)
634 r.Principals["founder"] = founder
635 a, err := render(r, day(t, "2026-10-22"), nil)
636 if err != nil {
637 t.Fatal(err)
638 }
639 return a
640 }
641 opens := func(file []byte) bool {
642 keys, err := note.ParseVerifierKeys(file)
643 if err != nil {
644 t.Fatal(err)
645 }
646 _, _, err = note.Open(signed("founder"), keys)
647 return err == nil
648 }
649
650 a := compiled(true)
651 if !opens(a.approvalSigners) || !opens(a.approvalHardware) {
652 t.Error("the device's signature does not open against the files its attested key compiles to")
653 }
654 a = compiled(false)
655 if !opens(a.approvalSigners) {
656 t.Error("the device's signature does not open against approval-signers without the attestation")
657 }
658 if opens(a.approvalHardware) {
659 t.Error("the device's key is in the hardware file without its attestation")
660 }
661}
662
663// ----------------------------------------------------------------------
664// A stand-in for Yubico's PKI: a root, one intermediate beneath it, and
665// one device whose f9 certificate the intermediate signed. It attests
666// whatever key and policy a test asks for, which a real YubiKey only does
667// for the keys it holds.
668
669type testPKI struct {
670 trust trust
671 root *x509.Certificate
672 intermediate *x509.Certificate
673 intermediateKey ed25519.PrivateKey
674 f9 *x509.Certificate
675 f9Key ed25519.PrivateKey
676}
677
678func newTestPKI(t *testing.T) testPKI {
679 t.Helper()
680 var p testPKI
681 rootPub, rootKey, _ := ed25519.GenerateKey(rand.Reader)
682 p.root = p.issue(t, nil, rootKey, caTemplate("Test Attestation Root", 2), rootPub)
683 interPub, interKey, _ := ed25519.GenerateKey(rand.Reader)
684 p.intermediate = p.issue(t, p.root, rootKey, caTemplate("Test PIV Attestation", 1), interPub)
685 p.intermediateKey = interKey
686 f9Pub, f9Key, _ := ed25519.GenerateKey(rand.Reader)
687 p.f9 = p.issue(t, p.intermediate, interKey, f9Template(), f9Pub)
688 p.f9Key = f9Key
689 p.trust = trust{roots: x509.NewCertPool(), intermediates: x509.NewCertPool()}
690 p.trust.roots.AddCert(p.root)
691 p.trust.intermediates.AddCert(p.intermediate)
692 return p
693}
694
695// attest is the stand-in device's attestation of a key in a slot.
696func (p testPKI) attest(t *testing.T, pub any, extensions ...pkix.Extension) attestation {
697 t.Helper()
698 slot := p.issue(t, p.f9, p.f9Key, leafTemplate(extensions...), pub)
699 return attestation{Slot: pemText(slot.Raw), F9: pemText(p.f9.Raw)}
700}
701
702func (testPKI) issue(t *testing.T, parent *x509.Certificate, parentKey ed25519.PrivateKey, template *x509.Certificate, pub any) *x509.Certificate {
703 t.Helper()
704 cert, err := x509.ParseCertificate(sign(t, template, parent, parentKey, pub))
705 if err != nil {
706 t.Fatal(err)
707 }
708 return cert
709}
710
711// sign makes a certificate and returns its DER unparsed. A nil parent
712// makes it self-signed.
713func sign(t *testing.T, template, parent *x509.Certificate, parentKey ed25519.PrivateKey, pub any) []byte {
714 t.Helper()
715 if parent == nil {
716 parent = template
717 }
718 der, err := x509.CreateCertificate(rand.Reader, template, parent, pub, parentKey)
719 if err != nil {
720 t.Fatal(err)
721 }
722 return der
723}
724
725func caTemplate(name string, pathLen int) *x509.Certificate {
726 return &x509.Certificate{
727 SerialNumber: big.NewInt(1),
728 Subject: pkix.Name{CommonName: name},
729 NotBefore: time.Date(2024, 12, 1, 0, 0, 0, 0, time.UTC),
730 NotAfter: time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC),
731 IsCA: true,
732 BasicConstraintsValid: true,
733 MaxPathLen: pathLen,
734 KeyUsage: x509.KeyUsageCertSign,
735 }
736}
737
738// f9Template is a device's f9 certificate: a CA that signs slot
739// certificates and nothing beneath them.
740func f9Template() *x509.Certificate {
741 f9 := caTemplate("YubiKey PIV Attestation", 0)
742 f9.MaxPathLenZero = true
743 return f9
744}
745
746// leafTemplate is a slot certificate as a YubiKey writes one: firmware
747// 5.7.4, serial 12345678, and the extensions given.
748func leafTemplate(extensions ...pkix.Extension) *x509.Certificate {
749 serial, _ := asn1.Marshal(big.NewInt(12345678))
750 return &x509.Certificate{
751 SerialNumber: big.NewInt(2),
752 Subject: pkix.Name{CommonName: "YubiKey PIV Attestation 9c"},
753 NotBefore: time.Date(2024, 12, 1, 0, 0, 0, 0, time.UTC),
754 NotAfter: time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC),
755 ExtraExtensions: append([]pkix.Extension{
756 {Id: extFirmware, Value: []byte{5, 7, 4}},
757 {Id: extSerial, Value: serial},
758 }, extensions...),
759 }
760}
761
762func policyExtension(pin, touch byte) pkix.Extension {
763 return pkix.Extension{Id: extPolicy, Value: []byte{pin, touch}}
764}
765
766// trustBoth has the render trust the stand-in PKI beside Yubico's, so one
767// registry can hold the device's real attestation and stand-in ones.
768func trustBoth(t *testing.T, p testPKI) {
769 t.Helper()
770 pinned := yubico
771 t.Cleanup(func() { yubico = pinned })
772 yubico = trust{roots: pinned.roots.Clone(), intermediates: pinned.intermediates.Clone()}
773 yubico.roots.AddCert(p.root)
774 yubico.intermediates.AddCert(p.intermediate)
775}
776
777// testKey is an Ed25519 public key made from a seed, and its registry
778// line.
779func testKey(seed string) (ed25519.PublicKey, string) {
780 pub := testPrivateKey(seed).Public().(ed25519.PublicKey)
781 var blob []byte
782 for _, f := range [][]byte{[]byte(sshEd25519), pub} {
783 blob = binary.BigEndian.AppendUint32(blob, uint32(len(f)))
784 blob = append(blob, f...)
785 }
786 return pub, sshEd25519 + " " + base64.StdEncoding.EncodeToString(blob)
787}
788
789// testPrivateKey is the private half of testKey's key.
790func testPrivateKey(seed string) ed25519.PrivateKey {
791 s := sha256.Sum256([]byte(seed))
792 return ed25519.NewKeyFromSeed(s[:])
793}
794
795func pemText(der []byte) string {
796 return string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}))
797}
798
799func pemBytes(t *testing.T, text string) []byte {
800 t.Helper()
801 block, _ := pem.Decode([]byte(text))
802 if block == nil {
803 t.Fatal("not PEM")
804 }
805 return block.Bytes
806}
807
808// flipLast changes the last byte of a certificate: a bit of its signature.
809func flipLast(der []byte) []byte {
810 out := slices.Clone(der)
811 out[len(out)-1] ^= 1
812 return out
813}