gunk-dev/the-valley

attestation_test.go

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