gunk-dev/the-valley

attestation_test.go

sourcedee3830391efmain's published tip history
22.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, 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// What a stand-in device can attest that Yubico's would not: no policy at
213// all, a key that is not Ed25519, and a slot certificate that an
214// intermediate signed instead of the device's f9.
215func TestStandInAttestationsThatAreRefused(t *testing.T) {
216 pki := newTestPKI(t)
217 pub, _ := testKey("approver")
218 on := day(t, "2026-10-22")
219
220 if _, err := verifyAttestation(pki.attest(t, pub), pub, on, pki.trust); err == nil ||
221 !strings.Contains(err.Error(), "no PIN and touch policy") {
222 t.Errorf("no policy extension: error = %v", err)
223 }
224
225 ec, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
226 if err != nil {
227 t.Fatal(err)
228 }
229 if _, err := verifyAttestation(pki.attest(t, &ec.PublicKey, policyExtension(3, 2)), pub, on, pki.trust); err == nil ||
230 !strings.Contains(err.Error(), "not an ed25519 one") {
231 t.Errorf("an ECDSA key: error = %v", err)
232 }
233
234 direct := pki.issue(t, pki.intermediate, pki.intermediateKey, leafTemplate(policyExtension(3, 2)), pub)
235 a := attestation{Slot: pemText(direct.Raw), F9: pemText(pki.f9.Raw)}
236 if _, err := verifyAttestation(a, pub, on, pki.trust); err == nil ||
237 !strings.Contains(err.Error(), "without its f9 certificate") {
238 t.Errorf("a slot certificate the intermediate signed: error = %v", err)
239 }
240}
241
242// approvalRegistry exercises every reason a key is or is not in the
243// approval files. founder governs and approves with three keys: an
244// ordinary one, the device's touch-always key, and a stand-in key whose
245// touch is cached. second approves under the grant's first name with a
246// stand-in touch-always key. departed has expired, pusher holds no
247// approve grant, and robot is not a human, so none of their keys appear.
248func approvalRegistry(t *testing.T, pki testPKI) registry {
249 t.Helper()
250 r := governedRegistry()
251 r.Boundaries["approve"] = boundary{Kind: boundaryApprove}
252 r.Boundaries["request"] = boundary{Kind: boundaryRequest}
253 approve := grant{Boundary: "approve"}
254 attestedKey := func(seed string, touch byte) key {
255 pub, line := testKey(seed)
256 a := pki.attest(t, pub, policyExtension(3, touch))
257 return key{Class: sshEd25519, Bound: "hardware", Public: line, Attestation: &a}
258 }
259 plainKey := func(seed string) key {
260 _, line := testKey(seed)
261 return key{Class: sshEd25519, Bound: "host", Public: line}
262 }
263
264 founder := r.Principals["founder"]
265 device := deviceAttestation(t)
266 founder.Keys = append(founder.Keys,
267 key{Class: sshEd25519, Bound: "hardware", Public: deviceKey, Attestation: &device},
268 attestedKey("cached", 3),
269 )
270 founder.Grants["approve"] = approve
271 r.Principals["founder"] = founder
272
273 r.Principals["second"] = principal{
274 Kind: kindHuman,
275 Keys: []key{attestedKey("second", 2)},
276 Grants: map[string]grant{"request": {Boundary: "request"}},
277 }
278 r.Principals["departed"] = principal{
279 Kind: kindHuman,
280 Keys: []key{attestedKey("departed", 2)},
281 Grants: map[string]grant{"approve": approve},
282 Expires: "2026-09-01",
283 }
284 r.Principals["pusher"] = principal{
285 Kind: kindHuman,
286 Keys: []key{plainKey("pusher")},
287 Grants: map[string]grant{"push": {Boundary: "push"}},
288 }
289 r.Principals["robot"] = principal{
290 Kind: "machine",
291 Keys: []key{attestedKey("robot", 2)},
292 Grants: map[string]grant{"approve": approve},
293 Expires: "2027-01-01",
294 }
295 return r
296}
297
298// The whole of both files, byte for byte, with the lines written by the
299// note package rather than by the compiler.
300func TestApprovalFilesListHumanApproversAndTheirHardwareKeys(t *testing.T) {
301 pki := newTestPKI(t)
302 trustBoth(t, pki)
303 r := approvalRegistry(t, pki)
304 a, err := render(r, day(t, "2026-10-22"), nil)
305 if err != nil {
306 t.Fatal(err)
307 }
308
309 line := func(name, public string) string {
310 pub, err := sshEd25519Public(public)
311 if err != nil {
312 t.Fatal(err)
313 }
314 return note.NewVerifierKey(name, pub).String()
315 }
316 _, cached := testKey("cached")
317 _, second := testKey("second")
318 founderPlain := r.Principals["founder"].Keys[0].Public
319 all := []string{line("founder", founderPlain), line("founder", deviceKey), line("founder", cached), line("second", second)}
320 hardware := []string{line("founder", deviceKey), line("second", second)}
321 for _, c := range []struct {
322 name string
323 got []byte
324 count int
325 head string
326 want []string
327 }{
328 {"approval-signers", a.approvalSigners, a.approvers, approvalSignersHeader, all},
329 {"approval-signers-hardware", a.approvalHardware, a.hardware, approvalHardwareHeader, hardware},
330 } {
331 slices.Sort(c.want)
332 want := c.head + strings.Join(c.want, "\n") + "\n"
333 if string(c.got) != want {
334 t.Errorf("%s =\n%s\nwant\n%s", c.name, c.got, want)
335 }
336 if c.count != len(c.want) {
337 t.Errorf("%s: count %d, want %d", c.name, c.count, len(c.want))
338 }
339 }
340
341 // Each attested key of a principal still in force is reported for
342 // review, and the expired one is not.
343 for _, want := range []string{
344 "founder: key 1 is on YubiKey serial " + deviceSerial + ", firmware 5.7.4, PIN policy always, touch policy always; it approves as a hardware key",
345 "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",
346 "robot: key 0 is on YubiKey serial 12345678, firmware 5.7.4, PIN policy always, touch policy always; its principal approves nothing",
347 } {
348 if !slices.Contains(a.notes, want) {
349 t.Errorf("no report %q among %q", want, a.notes)
350 }
351 }
352 for _, n := range a.notes {
353 if strings.HasPrefix(n, "departed: key") {
354 t.Errorf("an expired entry's key was reported: %q", n)
355 }
356 }
357}
358
359// A registry without approvers compiles both files holding only their
360// headers, and the note reader reads each as no keys.
361func TestARegistryWithoutApproversCompilesEmptyFiles(t *testing.T) {
362 a, err := render(governedRegistry(), day(t, "2026-10-22"), nil)
363 if err != nil {
364 t.Fatal(err)
365 }
366 for _, f := range [][]byte{a.approvalSigners, a.approvalHardware} {
367 keys, err := note.ParseVerifierKeys(f)
368 if err != nil || len(keys) != 0 {
369 t.Errorf("%q: %d keys, %v", f, len(keys), err)
370 }
371 }
372 if string(a.approvalSigners) != approvalSignersHeader || string(a.approvalHardware) != approvalHardwareHeader {
373 t.Errorf("the empty files are %q and %q", a.approvalSigners, a.approvalHardware)
374 }
375}
376
377// Rendering is reproducible: the order of principals and keys in the
378// registry does not reach the files.
379func TestApprovalFilesRenderTheSameWhateverTheOrder(t *testing.T) {
380 pki := newTestPKI(t)
381 trustBoth(t, pki)
382 r := approvalRegistry(t, pki)
383 first, err := render(r, day(t, "2026-10-22"), nil)
384 if err != nil {
385 t.Fatal(err)
386 }
387 founder := r.Principals["founder"]
388 slices.Reverse(founder.Keys)
389 r.Principals["founder"] = founder
390 second, err := render(r, day(t, "2026-10-22"), nil)
391 if err != nil {
392 t.Fatal(err)
393 }
394 if !bytes.Equal(first.approvalSigners, second.approvalSigners) || !bytes.Equal(first.approvalHardware, second.approvalHardware) {
395 t.Error("reordering founder's keys changed the approval files")
396 }
397}
398
399// A key that approves belongs to one principal, so the render fails when
400// another principal lists it too, whatever that principal holds.
401func TestAKeyThatApprovesBelongsToOnePrincipal(t *testing.T) {
402 pki := newTestPKI(t)
403 trustBoth(t, pki)
404 for name, holder := range map[string]principal{
405 "another approver": {Kind: kindHuman, Grants: map[string]grant{"approve": {Boundary: "approve"}}},
406 "a principal holding nothing": {Kind: kindHuman, Grants: map[string]grant{}},
407 "a machine": {Kind: "machine", Grants: map[string]grant{}, Expires: "2027-01-01"},
408 } {
409 r := approvalRegistry(t, pki)
410 device := deviceAttestation(t)
411 holder.Keys = []key{{Class: sshEd25519, Bound: "hardware", Public: deviceKey, Attestation: &device}}
412 r.Principals["impostor"] = holder
413 _, err := render(r, day(t, "2026-10-22"), nil)
414 if err == nil || !strings.Contains(err.Error(), "founder: key 1 is also impostor's, and a key that approves belongs to one principal") {
415 t.Errorf("%s holding founder's approval key: error = %v", name, err)
416 }
417 }
418}
419
420// An attestation that is offered and does not verify fails the whole
421// render. It is never read as no attestation, which would compile the key
422// into approval-signers as an ordinary key.
423func TestAnAttestationThatDoesNotVerifyFailsTheRender(t *testing.T) {
424 r := governedRegistry()
425 r.Boundaries["approve"] = boundary{Kind: boundaryApprove}
426 founder := r.Principals["founder"]
427 founder.Grants["approve"] = grant{Boundary: "approve"}
428 // The device's attestation, offered for another key.
429 device := deviceAttestation(t)
430 founder.Keys[0].Attestation = &device
431 r.Principals["founder"] = founder
432 _, err := render(r, day(t, "2026-10-22"), nil)
433 if err == nil || !strings.Contains(err.Error(), "founder: key 0: the slot certificate attests a different key") {
434 t.Errorf("render error = %v", err)
435 }
436}
437
438// The device's own signature, made with a touch, opens against both files
439// the device's registry entry compiles to. The same key without its
440// attestation is in approval-signers alone, and the signature does not
441// open against the hardware file.
442func TestTheDeviceSignatureOpensAgainstTheCompiledFiles(t *testing.T) {
443 text := []byte(testdata(t, "spike.txt"))
444 sig, err := base64.StdEncoding.DecodeString(strings.TrimSpace(testdata(t, "spike.sig.b64")))
445 if err != nil {
446 t.Fatal(err)
447 }
448 signed := func(name string) []byte {
449 blob := binary.BigEndian.AppendUint32(nil, note.KeyHash(name, devicePublic(t)))
450 return append(append(append([]byte{}, text...), '\n'),
451 note.Mark+name+" "+base64.StdEncoding.EncodeToString(append(blob, sig...))+"\n"...)
452 }
453 compiled := func(attested bool) artifacts {
454 r := governedRegistry()
455 r.Boundaries["approve"] = boundary{Kind: boundaryApprove}
456 founder := r.Principals["founder"]
457 founder.Grants["approve"] = grant{Boundary: "approve"}
458 k := key{Class: sshEd25519, Bound: "hardware", Public: deviceKey}
459 if attested {
460 device := deviceAttestation(t)
461 k.Attestation = &device
462 }
463 founder.Keys = append(founder.Keys, k)
464 r.Principals["founder"] = founder
465 a, err := render(r, day(t, "2026-10-22"), nil)
466 if err != nil {
467 t.Fatal(err)
468 }
469 return a
470 }
471 opens := func(file []byte) bool {
472 keys, err := note.ParseVerifierKeys(file)
473 if err != nil {
474 t.Fatal(err)
475 }
476 _, _, err = note.Open(signed("founder"), keys)
477 return err == nil
478 }
479
480 a := compiled(true)
481 if !opens(a.approvalSigners) || !opens(a.approvalHardware) {
482 t.Error("the device's signature does not open against the files its attested key compiles to")
483 }
484 a = compiled(false)
485 if !opens(a.approvalSigners) {
486 t.Error("the device's signature does not open against approval-signers without the attestation")
487 }
488 if opens(a.approvalHardware) {
489 t.Error("the device's key is in the hardware file without its attestation")
490 }
491}
492
493// ----------------------------------------------------------------------
494// A stand-in for Yubico's PKI: a root, one intermediate beneath it, and
495// one device whose f9 certificate the intermediate signed. It attests
496// whatever key and policy a test asks for, which a real YubiKey only does
497// for the keys it holds.
498
499type testPKI struct {
500 trust trust
501 root *x509.Certificate
502 intermediate *x509.Certificate
503 intermediateKey ed25519.PrivateKey
504 f9 *x509.Certificate
505 f9Key ed25519.PrivateKey
506}
507
508func newTestPKI(t *testing.T) testPKI {
509 t.Helper()
510 var p testPKI
511 rootPub, rootKey, _ := ed25519.GenerateKey(rand.Reader)
512 p.root = p.issue(t, nil, rootKey, caTemplate("Test Attestation Root", 2), rootPub)
513 interPub, interKey, _ := ed25519.GenerateKey(rand.Reader)
514 p.intermediate = p.issue(t, p.root, rootKey, caTemplate("Test PIV Attestation", 1), interPub)
515 p.intermediateKey = interKey
516 f9Pub, f9Key, _ := ed25519.GenerateKey(rand.Reader)
517 f9 := caTemplate("YubiKey PIV Attestation", 0)
518 f9.MaxPathLenZero = true
519 p.f9 = p.issue(t, p.intermediate, interKey, f9, f9Pub)
520 p.f9Key = f9Key
521 p.trust = trust{roots: x509.NewCertPool(), intermediates: x509.NewCertPool()}
522 p.trust.roots.AddCert(p.root)
523 p.trust.intermediates.AddCert(p.intermediate)
524 return p
525}
526
527// attest is the stand-in device's attestation of a key in a slot.
528func (p testPKI) attest(t *testing.T, pub any, extensions ...pkix.Extension) attestation {
529 t.Helper()
530 slot := p.issue(t, p.f9, p.f9Key, leafTemplate(extensions...), pub)
531 return attestation{Slot: pemText(slot.Raw), F9: pemText(p.f9.Raw)}
532}
533
534func (testPKI) issue(t *testing.T, parent *x509.Certificate, parentKey ed25519.PrivateKey, template *x509.Certificate, pub any) *x509.Certificate {
535 t.Helper()
536 if parent == nil {
537 parent = template
538 }
539 der, err := x509.CreateCertificate(rand.Reader, template, parent, pub, parentKey)
540 if err != nil {
541 t.Fatal(err)
542 }
543 cert, err := x509.ParseCertificate(der)
544 if err != nil {
545 t.Fatal(err)
546 }
547 return cert
548}
549
550func caTemplate(name string, pathLen int) *x509.Certificate {
551 return &x509.Certificate{
552 SerialNumber: big.NewInt(1),
553 Subject: pkix.Name{CommonName: name},
554 NotBefore: time.Date(2024, 12, 1, 0, 0, 0, 0, time.UTC),
555 NotAfter: time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC),
556 IsCA: true,
557 BasicConstraintsValid: true,
558 MaxPathLen: pathLen,
559 KeyUsage: x509.KeyUsageCertSign,
560 }
561}
562
563// leafTemplate is a slot certificate as a YubiKey writes one: firmware
564// 5.7.4, serial 12345678, and the extensions given.
565func leafTemplate(extensions ...pkix.Extension) *x509.Certificate {
566 serial, _ := asn1.Marshal(big.NewInt(12345678))
567 return &x509.Certificate{
568 SerialNumber: big.NewInt(2),
569 Subject: pkix.Name{CommonName: "YubiKey PIV Attestation 9c"},
570 NotBefore: time.Date(2024, 12, 1, 0, 0, 0, 0, time.UTC),
571 NotAfter: time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC),
572 ExtraExtensions: append([]pkix.Extension{
573 {Id: extFirmware, Value: []byte{5, 7, 4}},
574 {Id: extSerial, Value: serial},
575 }, extensions...),
576 }
577}
578
579func policyExtension(pin, touch byte) pkix.Extension {
580 return pkix.Extension{Id: extPolicy, Value: []byte{pin, touch}}
581}
582
583// trustBoth has the render trust the stand-in PKI beside Yubico's, so one
584// registry can hold the device's real attestation and stand-in ones.
585func trustBoth(t *testing.T, p testPKI) {
586 t.Helper()
587 pinned := yubico
588 t.Cleanup(func() { yubico = pinned })
589 yubico = trust{roots: pinned.roots.Clone(), intermediates: pinned.intermediates.Clone()}
590 yubico.roots.AddCert(p.root)
591 yubico.intermediates.AddCert(p.intermediate)
592}
593
594// testKey is an Ed25519 public key made from a seed, and its registry
595// line.
596func testKey(seed string) (ed25519.PublicKey, string) {
597 s := sha256.Sum256([]byte(seed))
598 pub := ed25519.NewKeyFromSeed(s[:]).Public().(ed25519.PublicKey)
599 var blob []byte
600 for _, f := range [][]byte{[]byte(sshEd25519), pub} {
601 blob = binary.BigEndian.AppendUint32(blob, uint32(len(f)))
602 blob = append(blob, f...)
603 }
604 return pub, sshEd25519 + " " + base64.StdEncoding.EncodeToString(blob)
605}
606
607func pemText(der []byte) string {
608 return string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}))
609}
610
611func pemBytes(t *testing.T, text string) []byte {
612 t.Helper()
613 block, _ := pem.Decode([]byte(text))
614 if block == nil {
615 t.Fatal("not PEM")
616 }
617 return block.Bytes
618}
619
620// flipLast changes the last byte of a certificate: a bit of its signature.
621func flipLast(der []byte) []byte {
622 out := slices.Clone(der)
623 out[len(out)-1] ^= 1
624 return out
625}