-
Notifications
You must be signed in to change notification settings - Fork 65
/
piv.go
851 lines (778 loc) · 22.4 KB
/
piv.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package piv
import (
"bytes"
"crypto/des"
"crypto/rand"
"encoding/asn1"
"encoding/binary"
"errors"
"fmt"
"io"
"math/big"
)
var (
// DefaultPIN for the PIV applet. The PIN is used to change the Management Key,
// and slots can optionally require it to perform signing operations.
DefaultPIN = "123456"
// DefaultPUK for the PIV applet. The PUK is only used to reset the PIN when
// the card's PIN retries have been exhausted.
DefaultPUK = "12345678"
// DefaultManagementKey for the PIV applet. The Management Key is a Triple-DES
// key required for slot actions such as generating keys, setting certificates,
// and signing.
DefaultManagementKey = [24]byte{
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
}
)
// Cards lists all smart cards available via PC/SC interface. Card names are
// strings describing the key, such as "Yubico Yubikey NEO OTP+U2F+CCID 00 00".
//
// Card names depend on the operating system and what port a card is plugged
// into. To uniquely identify a card, use its serial number.
//
// See: https://ludovicrousseau.blogspot.com/2010/05/what-is-in-pcsc-reader-name.html
func Cards() ([]string, error) {
var c client
return c.Cards()
}
const (
// https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-78-4.pdf#page=17
algTag = 0x80
alg3DES = 0x03
algRSA1024 = 0x06
algRSA2048 = 0x07
algECCP256 = 0x11
algECCP384 = 0x14
// non-standard; as implemented by SoloKeys. Chosen for low probability of eventual
// clashes, if and when PIV standard adds Ed25519 support
algEd25519 = 0x22
// https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-78-4.pdf#page=16
keyAuthentication = 0x9a
keyCardManagement = 0x9b
keySignature = 0x9c
keyKeyManagement = 0x9d
keyCardAuthentication = 0x9e
keyAttestation = 0xf9
insVerify = 0x20
insChangeReference = 0x24
insResetRetry = 0x2c
insGenerateAsymmetric = 0x47
insAuthenticate = 0x87
insGetData = 0xcb
insPutData = 0xdb
insSelectApplication = 0xa4
insGetResponseAPDU = 0xc0
// https://github.com/Yubico/yubico-piv-tool/blob/yubico-piv-tool-1.7.0/lib/ykpiv.h#L656
insSetMGMKey = 0xff
insImportKey = 0xfe
insGetVersion = 0xfd
insReset = 0xfb
insSetPINRetries = 0xfa
insAttest = 0xf9
insGetSerial = 0xf8
)
// YubiKey is an exclusive open connection to a YubiKey smart card. While open,
// no other process can query the given card.
//
// To release the connection, call the Close method.
type YubiKey struct {
ctx *scContext
h *scHandle
tx *scTx
rand io.Reader
// Used to determine how to access certain functionality.
//
// TODO: It's not clear what this actually communicates. Is this the
// YubiKey's version or PIV version? A NEO reports v1.0.4. Figure this out
// before exposing an API.
version *version
}
// Close releases the connection to the smart card.
func (yk *YubiKey) Close() error {
err1 := yk.h.Close()
err2 := yk.ctx.Close()
if err1 == nil {
return err2
}
return err1
}
// Open connects to a YubiKey smart card.
func Open(card string) (*YubiKey, error) {
var c client
return c.Open(card)
}
// client is a smart card client and may be exported in the future to allow
// configuration for the top level Open() and Cards() APIs.
type client struct {
// Rand is a cryptographic source of randomness used for card challenges.
//
// If nil, defaults to crypto.Rand.
Rand io.Reader
}
func (c *client) Cards() ([]string, error) {
ctx, err := newSCContext()
if err != nil {
return nil, fmt.Errorf("connecting to pscs: %w", err)
}
defer ctx.Close()
return ctx.ListReaders()
}
func (c *client) Open(card string) (*YubiKey, error) {
ctx, err := newSCContext()
if err != nil {
return nil, fmt.Errorf("connecting to smart card daemon: %w", err)
}
h, err := ctx.Connect(card)
if err != nil {
ctx.Close()
return nil, fmt.Errorf("connecting to smart card: %w", err)
}
tx, err := h.Begin()
if err != nil {
return nil, fmt.Errorf("beginning smart card transaction: %w", err)
}
if err := ykSelectApplication(tx, aidPIV[:]); err != nil {
tx.Close()
return nil, fmt.Errorf("selecting piv applet: %w", err)
}
yk := &YubiKey{ctx: ctx, h: h, tx: tx}
v, err := ykVersion(yk.tx)
if err != nil {
yk.Close()
return nil, fmt.Errorf("getting yubikey version: %w", err)
}
yk.version = v
if c.Rand != nil {
yk.rand = c.Rand
} else {
yk.rand = rand.Reader
}
return yk, nil
}
// Version returns the version as reported by the PIV applet. For newer
// YubiKeys (>=4.0.0) this corresponds to the version of the YubiKey itself.
//
// Older YubiKeys return values that aren't directly related to the YubiKey
// version. For example, 3rd generation YubiKeys report 1.0.X.
func (yk *YubiKey) Version() Version {
return Version{
Major: int(yk.version.major),
Minor: int(yk.version.minor),
Patch: int(yk.version.patch),
}
}
// Serial returns the YubiKey's serial number.
func (yk *YubiKey) Serial() (uint32, error) {
return ykSerial(yk.tx, yk.version)
}
func encodePIN(pin string) ([]byte, error) {
data := []byte(pin)
if len(data) == 0 {
return nil, fmt.Errorf("pin cannot be empty")
}
if len(data) > 8 {
return nil, fmt.Errorf("pin longer than 8 bytes")
}
// apply padding
for i := len(data); i < 8; i++ {
data = append(data, 0xff)
}
return data, nil
}
// authPIN attempts to authenticate against the card with the provided PIN.
// The PIN is required to use and modify certain slots.
//
// After a specific number of authentication attemps with an invalid PIN,
// usually 3, the PIN will become block and refuse further attempts. At that
// point the PUK must be used to unblock the PIN.
//
// Use DefaultPIN if the PIN hasn't been set.
func (yk *YubiKey) authPIN(pin string) error {
return ykLogin(yk.tx, pin)
}
func ykLogin(tx *scTx, pin string) error {
data, err := encodePIN(pin)
if err != nil {
return err
}
// https://csrc.nist.gov/CSRC/media/Publications/sp/800-73/4/archive/2015-05-29/documents/sp800_73-4_pt2_draft.pdf#page=20
cmd := apdu{instruction: insVerify, param2: 0x80, data: data}
if _, err := tx.Transmit(cmd); err != nil {
return fmt.Errorf("verify pin: %w", err)
}
return nil
}
func ykLoginNeeded(tx *scTx) bool {
cmd := apdu{instruction: insVerify, param2: 0x80}
_, err := tx.Transmit(cmd)
return err != nil
}
// Retries returns the number of attempts remaining to enter the correct PIN.
func (yk *YubiKey) Retries() (int, error) {
return ykPINRetries(yk.tx)
}
func ykPINRetries(tx *scTx) (int, error) {
cmd := apdu{instruction: insVerify, param2: 0x80}
_, err := tx.Transmit(cmd)
if err == nil {
return 0, fmt.Errorf("expected error code from empty pin")
}
var e AuthErr
if errors.As(err, &e) {
return e.Retries, nil
}
return 0, fmt.Errorf("invalid response: %w", err)
}
// Reset resets the YubiKey PIV applet to its factory settings, wiping all slots
// and resetting the PIN, PUK, and Management Key to their default values. This
// does NOT affect data on other applets, such as GPG or U2F.
func (yk *YubiKey) Reset() error {
return ykReset(yk.tx, yk.rand)
}
func ykReset(tx *scTx, r io.Reader) error {
// Reset only works if both the PIN and PUK are blocked. Before resetting,
// try the wrong PIN and PUK multiple times to block them.
maxPIN := big.NewInt(100_000_000)
pinInt, err := rand.Int(r, maxPIN)
if err != nil {
return fmt.Errorf("generating random pin: %v", err)
}
pukInt, err := rand.Int(r, maxPIN)
if err != nil {
return fmt.Errorf("generating random puk: %v", err)
}
pin := pinInt.String()
puk := pukInt.String()
for {
err := ykLogin(tx, pin)
if err == nil {
// TODO: do we care about a 1/100million chance?
return fmt.Errorf("expected error with random pin")
}
var e AuthErr
if !errors.As(err, &e) {
return fmt.Errorf("blocking pin: %w", err)
}
if e.Retries == 0 {
break
}
}
for {
err := ykChangePUK(tx, puk, puk)
if err == nil {
// TODO: do we care about a 1/100million chance?
return fmt.Errorf("expected error with random puk")
}
var e AuthErr
if !errors.As(err, &e) {
return fmt.Errorf("blocking puk: %w", err)
}
if e.Retries == 0 {
break
}
}
cmd := apdu{instruction: insReset}
if _, err := tx.Transmit(cmd); err != nil {
return fmt.Errorf("reseting yubikey: %w", err)
}
return nil
}
type version struct {
major byte
minor byte
patch byte
}
// authManagementKey attempts to authenticate against the card with the provided
// management key. The management key is required to generate new keys or add
// certificates to slots.
//
// Use DefaultManagementKey if the management key hasn't been set.
func (yk *YubiKey) authManagementKey(key [24]byte) error {
return ykAuthenticate(yk.tx, key, yk.rand)
}
var (
// Smartcard Application IDs for YubiKeys.
//
// https://github.com/Yubico/yubico-piv-tool/blob/yubico-piv-tool-1.7.0/lib/ykpiv.c#L1877
// https://github.com/Yubico/yubico-piv-tool/blob/yubico-piv-tool-1.7.0/lib/ykpiv.c#L108-L110
// https://github.com/Yubico/yubico-piv-tool/blob/yubico-piv-tool-1.7.0/lib/ykpiv.c#L1117
aidManagement = [...]byte{0xa0, 0x00, 0x00, 0x05, 0x27, 0x47, 0x11, 0x17}
aidPIV = [...]byte{0xa0, 0x00, 0x00, 0x03, 0x08}
aidYubiKey = [...]byte{0xa0, 0x00, 0x00, 0x05, 0x27, 0x20, 0x01, 0x01}
)
func ykAuthenticate(tx *scTx, key [24]byte, rand io.Reader) error {
// https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-73-4.pdf#page=92
// https://tsapps.nist.gov/publication/get_pdf.cfm?pub_id=918402#page=114
// request a witness
cmd := apdu{
instruction: insAuthenticate,
param1: alg3DES,
param2: keyCardManagement,
data: []byte{
0x7c, // Dynamic Authentication Template tag
0x02, // Length of object
0x80, // 'Witness'
0x00, // Return encrypted random
},
}
resp, err := tx.Transmit(cmd)
if err != nil {
return fmt.Errorf("get auth challenge: %w", err)
}
if n := len(resp); n < 12 {
return fmt.Errorf("challenge didn't return enough bytes: %d", n)
}
if !bytes.Equal(resp[:4], []byte{
0x7c,
0x0a,
0x80, // 'Witness'
0x08, // Tag length
}) {
return fmt.Errorf("invalid authentication object header: %x", resp[:4])
}
cardChallenge := resp[4 : 4+8]
cardResponse := make([]byte, 8)
block, err := des.NewTripleDESCipher(key[:])
if err != nil {
return fmt.Errorf("creating triple des block cipher: %v", err)
}
block.Decrypt(cardResponse, cardChallenge)
challenge := make([]byte, 8)
if _, err := io.ReadFull(rand, challenge); err != nil {
return fmt.Errorf("reading rand data: %v", err)
}
response := make([]byte, 8)
block.Encrypt(response, challenge)
data := append([]byte{
0x7c, // Dynamic Authentication Template tag
20, // 2+8+2+8
0x80, // 'Witness'
0x08, // Tag length
})
data = append(data, cardResponse...)
data = append(data,
0x81, // 'Challenge'
0x08, // Tag length
)
data = append(data, challenge...)
cmd = apdu{
instruction: insAuthenticate,
param1: alg3DES,
param2: keyCardManagement,
data: data,
}
resp, err = tx.Transmit(cmd)
if err != nil {
return fmt.Errorf("auth challenge: %w", err)
}
if n := len(resp); n < 12 {
return fmt.Errorf("challenge response didn't return enough bytes: %d", n)
}
if !bytes.Equal(resp[:4], []byte{
0x7c,
0x0a,
0x82, // 'Response'
0x08,
}) {
return fmt.Errorf("response invalid authentication object header: %x", resp[:4])
}
if !bytes.Equal(resp[4:4+8], response) {
return fmt.Errorf("challenge failed")
}
return nil
}
// SetManagementKey updates the management key to a new key. Management keys
// are triple-des keys, however padding isn't verified. To generate a new key,
// generate 24 random bytes.
//
// var newKey [24]byte
// if _, err := io.ReadFull(rand.Reader, newKey[:]); err != nil {
// // ...
// }
// if err := yk.SetManagementKey(piv.DefaultManagementKey, newKey); err != nil {
// // ...
// }
//
//
func (yk *YubiKey) SetManagementKey(oldKey, newKey [24]byte) error {
if err := ykAuthenticate(yk.tx, oldKey, yk.rand); err != nil {
return fmt.Errorf("authenticating with old key: %w", err)
}
if err := ykSetManagementKey(yk.tx, newKey, false); err != nil {
return err
}
return nil
}
// ykSetManagementKey updates the management key to a new key. This requires
// authenticating with the existing management key.
func ykSetManagementKey(tx *scTx, key [24]byte, touch bool) error {
cmd := apdu{
instruction: insSetMGMKey,
param1: 0xff,
param2: 0xff,
data: append([]byte{
alg3DES, keyCardManagement, 24,
}, key[:]...),
}
if touch {
cmd.param2 = 0xfe
}
if _, err := tx.Transmit(cmd); err != nil {
return fmt.Errorf("command failed: %w", err)
}
return nil
}
// SetPIN updates the PIN to a new value. For compatibility, PINs should be 1-8
// numeric characters.
//
// To generate a new PIN, use the crypto/rand package.
//
// // Generate a 6 character PIN.
// newPINInt, err := rand.Int(rand.Reader, bit.NewInt(1_000_000))
// if err != nil {
// // ...
// }
// // Format with leading zeros.
// newPIN := fmt.Sprintf("%06d", newPINInt)
// if err := yk.SetPIN(piv.DefaultPIN, newPIN); err != nil {
// // ...
// }
//
func (yk *YubiKey) SetPIN(oldPIN, newPIN string) error {
return ykChangePIN(yk.tx, oldPIN, newPIN)
}
func ykChangePIN(tx *scTx, oldPIN, newPIN string) error {
oldPINData, err := encodePIN(oldPIN)
if err != nil {
return fmt.Errorf("encoding old pin: %v", err)
}
newPINData, err := encodePIN(newPIN)
if err != nil {
return fmt.Errorf("encoding new pin: %v", err)
}
cmd := apdu{
instruction: insChangeReference,
param2: 0x80,
data: append(oldPINData, newPINData...),
}
_, err = tx.Transmit(cmd)
return err
}
// Unblock unblocks the PIN, setting it to a new value.
func (yk *YubiKey) Unblock(puk, newPIN string) error {
return ykUnblockPIN(yk.tx, puk, newPIN)
}
func ykUnblockPIN(tx *scTx, puk, newPIN string) error {
pukData, err := encodePIN(puk)
if err != nil {
return fmt.Errorf("encoding puk: %v", err)
}
newPINData, err := encodePIN(newPIN)
if err != nil {
return fmt.Errorf("encoding new pin: %v", err)
}
cmd := apdu{
instruction: insResetRetry,
param2: 0x80,
data: append(pukData, newPINData...),
}
_, err = tx.Transmit(cmd)
return err
}
// SetPUK updates the PUK to a new value. For compatibility, PUKs should be 1-8
// numeric characters.
//
// To generate a new PUK, use the crypto/rand package.
//
// // Generate a 8 character PUK.
// newPUKInt, err := rand.Int(rand.Reader, bit.NewInt(100_000_000))
// if err != nil {
// // ...
// }
// // Format with leading zeros.
// newPUK := fmt.Sprintf("%08d", newPUKInt)
// if err := yk.SetPIN(piv.DefaultPUK, newPUK); err != nil {
// // ...
// }
//
func (yk *YubiKey) SetPUK(oldPUK, newPUK string) error {
return ykChangePUK(yk.tx, oldPUK, newPUK)
}
func ykChangePUK(tx *scTx, oldPUK, newPUK string) error {
oldPUKData, err := encodePIN(oldPUK)
if err != nil {
return fmt.Errorf("encoding old puk: %v", err)
}
newPUKData, err := encodePIN(newPUK)
if err != nil {
return fmt.Errorf("encoding new puk: %v", err)
}
cmd := apdu{
instruction: insChangeReference,
param2: 0x81,
data: append(oldPUKData, newPUKData...),
}
_, err = tx.Transmit(cmd)
return err
}
func ykSelectApplication(tx *scTx, id []byte) error {
cmd := apdu{
instruction: insSelectApplication,
param1: 0x04,
data: id[:],
}
if _, err := tx.Transmit(cmd); err != nil {
return fmt.Errorf("command failed: %w", err)
}
return nil
}
func ykVersion(tx *scTx) (*version, error) {
cmd := apdu{
instruction: insGetVersion,
}
resp, err := tx.Transmit(cmd)
if err != nil {
return nil, fmt.Errorf("command failed: %w", err)
}
if n := len(resp); n != 3 {
return nil, fmt.Errorf("expected response to have 3 bytes, got: %d", n)
}
return &version{resp[0], resp[1], resp[2]}, nil
}
func ykSerial(tx *scTx, v *version) (uint32, error) {
cmd := apdu{instruction: insGetSerial}
if v.major < 5 {
// Earlier versions of YubiKeys required using the yubikey applet to get
// the serial number. Newer ones have this built into the PIV applet.
if err := ykSelectApplication(tx, aidYubiKey[:]); err != nil {
return 0, fmt.Errorf("selecting yubikey applet: %w", err)
}
defer ykSelectApplication(tx, aidPIV[:])
cmd = apdu{instruction: 0x01, param1: 0x10}
}
resp, err := tx.Transmit(cmd)
if err != nil {
return 0, fmt.Errorf("smart card command: %w", err)
}
if n := len(resp); n != 4 {
return 0, fmt.Errorf("expected 4 byte serial number, got %d", n)
}
return binary.BigEndian.Uint32(resp), nil
}
// ykChangeManagementKey sets the Management Key to the new key provided. The
// user must have authenticated with the existing key first.
func ykChangeManagementKey(tx *scTx, key [24]byte) error {
cmd := apdu{
instruction: insSetMGMKey,
param1: 0xff,
param2: 0xff, // TODO: support touch policy
data: append([]byte{
alg3DES, keyCardManagement, 24,
}, key[:]...),
}
if _, err := tx.Transmit(cmd); err != nil {
return fmt.Errorf("command failed: %w", err)
}
return nil
}
func unmarshalDERField(b []byte, tag uint64) (obj []byte, err error) {
var prefix []byte
for tag > 0 {
prefix = append(prefix, byte(tag))
tag = tag >> 8
}
for i, j := 0, len(prefix)-1; i < j; i, j = i+1, j-1 {
prefix[i], prefix[j] = prefix[j], prefix[i]
}
hasPrefix := bytes.HasPrefix(b, prefix)
for len(b) > 0 {
var v asn1.RawValue
b, err = asn1.Unmarshal(b, &v)
if err != nil {
return nil, err
}
if hasPrefix {
return v.Bytes, nil
}
}
return nil, fmt.Errorf("no der value with tag 0x%x", prefix)
}
// Metadata returns protected data stored on the card. This can be used to
// retrieve PIN protected management keys.
func (yk *YubiKey) Metadata(pin string) (*Metadata, error) {
m, err := ykGetProtectedMetadata(yk.tx, pin)
if err != nil {
if errors.Is(err, ErrNotFound) {
return &Metadata{}, nil
}
return nil, err
}
return m, nil
}
// SetMetadata sets PIN protected metadata on the key. This is primarily to
// store the management key on the smart card instead of managing the PIN and
// management key seperately.
func (yk *YubiKey) SetMetadata(key [24]byte, m *Metadata) error {
return ykSetProtectedMetadata(yk.tx, key, m)
}
// Metadata holds protected metadata. This is primarily used by YubiKey manager
// to implement PIN protect management keys, storing management keys on the card
// guarded by the PIN.
type Metadata struct {
// ManagementKey is the management key stored directly on the YubiKey.
ManagementKey *[24]byte
// raw, if not nil, is the full bytes
raw []byte
}
func (m *Metadata) marshal() ([]byte, error) {
if m.raw == nil {
if m.ManagementKey == nil {
return []byte{0x88, 0x00}, nil
}
return append([]byte{
0x88,
26,
0x89,
24,
}, m.ManagementKey[:]...), nil
}
if m.ManagementKey == nil {
return m.raw, nil
}
var metadata asn1.RawValue
if _, err := asn1.Unmarshal(m.raw, &metadata); err != nil {
return nil, fmt.Errorf("updating metadata: %v", err)
}
if !bytes.HasPrefix(metadata.FullBytes, []byte{0x88}) {
return nil, fmt.Errorf("expected tag: 0x88")
}
raw := metadata.Bytes
metadata.Bytes = nil
metadata.FullBytes = nil
for len(raw) > 0 {
var (
err error
v asn1.RawValue
)
raw, err = asn1.Unmarshal(raw, &v)
if err != nil {
return nil, fmt.Errorf("unmarshal metadata field: %v", err)
}
if bytes.HasPrefix(v.FullBytes, []byte{0x89}) {
continue
}
metadata.Bytes = append(metadata.Bytes, v.FullBytes...)
}
metadata.Bytes = append(metadata.Bytes, 0x89, 24)
metadata.Bytes = append(metadata.Bytes, m.ManagementKey[:]...)
return asn1.Marshal(metadata)
}
func (m *Metadata) unmarshal(b []byte) error {
m.raw = b
var md asn1.RawValue
if _, err := asn1.Unmarshal(b, &md); err != nil {
return err
}
if !bytes.HasPrefix(md.FullBytes, []byte{0x88}) {
return fmt.Errorf("expected tag: 0x88")
}
d := md.Bytes
for len(d) > 0 {
var (
err error
v asn1.RawValue
)
d, err = asn1.Unmarshal(d, &v)
if err != nil {
return fmt.Errorf("unmarshal metadata field: %v", err)
}
if !bytes.HasPrefix(v.FullBytes, []byte{0x89}) {
continue
}
// 0x89 indicates key
if len(v.Bytes) != 24 {
return fmt.Errorf("invalid management key length: %d", len(v.Bytes))
}
var key [24]byte
for i := 0; i < len(v.Bytes); i++ {
key[i] = v.Bytes[i]
}
m.ManagementKey = &key
}
return nil
}
func ykGetProtectedMetadata(tx *scTx, pin string) (*Metadata, error) {
// NOTE: for some reason this action requires the PIN to be authenticated on
// the same transaction. It doesn't work otherwise.
if err := ykLogin(tx, pin); err != nil {
return nil, fmt.Errorf("authenticating with pin: %w", err)
}
cmd := apdu{
instruction: insGetData,
param1: 0x3f,
param2: 0xff,
data: []byte{
0x5c, // Tag list
0x03,
0x5f,
0xc1,
0x09,
},
}
resp, err := tx.Transmit(cmd)
if err != nil {
return nil, fmt.Errorf("command failed: %w", err)
}
obj, _, err := unmarshalASN1(resp, 1, 0x13) // tag 0x53
if err != nil {
return nil, fmt.Errorf("unmarshaling response: %v", err)
}
var m Metadata
if err := m.unmarshal(obj); err != nil {
return nil, fmt.Errorf("unmarshal protected metadata: %v", err)
}
return &m, nil
}
func ykSetProtectedMetadata(tx *scTx, key [24]byte, m *Metadata) error {
data, err := m.marshal()
if err != nil {
return fmt.Errorf("encoding metadata: %v", err)
}
data = append([]byte{
0x5c, // Tag list
0x03,
0x5f,
0xc1,
0x09,
}, marshalASN1(0x53, data)...)
cmd := apdu{
instruction: insPutData,
param1: 0x3f,
param2: 0xff,
data: data,
}
// NOTE: for some reason this action requires the management key authenticated
// on the same transaction. It doesn't work otherwise.
if err := ykAuthenticate(tx, key, rand.Reader); err != nil {
return fmt.Errorf("authenticating with key: %w", err)
}
if _, err := tx.Transmit(cmd); err != nil {
return fmt.Errorf("command failed: %w", err)
}
return nil
}