-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathcommand_set.go
More file actions
923 lines (784 loc) · 28.2 KB
/
Copy pathcommand_set.go
File metadata and controls
923 lines (784 loc) · 28.2 KB
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
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
package keycard
import (
"crypto/rand"
"crypto/sha256"
"errors"
"fmt"
"github.com/keycard-tech/keycard-go/v4/apdu"
"github.com/keycard-tech/keycard-go/v4/crypto"
"github.com/keycard-tech/keycard-go/v4/derivationpath"
"github.com/keycard-tech/keycard-go/v4/globalplatform"
"github.com/keycard-tech/keycard-go/v4/identifiers"
"github.com/keycard-tech/keycard-go/v4/types"
)
var ErrNoAvailablePairingSlots = errors.New("no available pairing slots")
var ErrBadChecksumSize = errors.New("bad checksum size")
// WrongPINError is returned when a PIN verification fails.
type WrongPINError struct {
RemainingAttempts int
}
func (e *WrongPINError) Error() string {
return fmt.Sprintf("wrong pin. remaining attempts: %d", e.RemainingAttempts)
}
// WrongPUKError is returned when a PUK verification fails.
type WrongPUKError struct {
RemainingAttempts int
}
func (e *WrongPUKError) Error() string {
return fmt.Sprintf("wrong puk. remaining attempts: %d", e.RemainingAttempts)
}
// CommandSet is the main API for interacting with a Status Keycard.
//
// The secure channel version (V1 or V2) is auto-detected based on the applet
// version after the first Select() call.
type CommandSet struct {
c types.Channel
sc SecureChannel
ApplicationInfo *types.ApplicationInfo
caPublicKeys [][33]byte
whitelistedKeys [][33]byte
}
// NewCommandSet creates a CommandSet using the given APDU channel.
//
// Uses the default Status CA public key for V2 certificate verification.
func NewCommandSet(c types.Channel) *CommandSet {
return NewCommandSetWithCA(c, DefaultCAPublicKey)
}
// NewCommandSetWithCA creates a CommandSet with a single trusted CA public key.
func NewCommandSetWithCA(c types.Channel, caPublicKey [33]byte) *CommandSet {
return NewCommandSetWithCAs(c, [][33]byte{caPublicKey}, nil)
}
// NewCommandSetWithCAs creates a CommandSet with custom trusted CA keys and
// optionally whitelisted card identity keys.
func NewCommandSetWithCAs(c types.Channel, caPublicKeys, whitelistedCardKeys [][33]byte) *CommandSet {
return &CommandSet{
c: c,
sc: NewSecureChannelV2(caPublicKeys, whitelistedCardKeys),
ApplicationInfo: &types.ApplicationInfo{},
caPublicKeys: caPublicKeys,
whitelistedKeys: whitelistedCardKeys,
}
}
// Select selects the default instance (index 1) of the Keycard applet.
//
// Parses the response as ApplicationInfo and auto-selects the correct
// secure channel version (V1 or V2) based on applet version.
func (cs *CommandSet) Select() error {
return cs.selectWithIndex(uint8(identifiers.KeycardDefaultInstanceIndex))
}
func (cs *CommandSet) selectWithIndex(instanceIdx uint8) error {
instanceAID, err := identifiers.KeycardInstanceAID(int(instanceIdx))
if err != nil {
return err
}
cmd := globalplatform.NewCommandSelect(instanceAID)
cmd.SetLe(0)
resp, err := cs.c.Send(cmd)
if err = apdu.CheckOK(resp, err); err != nil {
return err
}
appInfo, err := types.ParseApplicationInfo(resp.Data)
if err != nil {
return err
}
cs.ApplicationInfo = appInfo
if cs.ApplicationInfo.HasSecureChannelCapability() {
if cs.isSecureChannelV2() {
// V2: create new SecureChannelV2
scV2 := NewSecureChannelV2(cs.caPublicKeys, cs.whitelistedKeys)
if len(appInfo.CertData) > 0 {
if err := scV2.SetCardCertificate(appInfo.CertData); err != nil {
return fmt.Errorf("failed to set card certificate: %w", err)
}
}
cs.sc = scV2
} else {
// V1: create new SecureChannelV1 and generate ECDH secret
scV1 := NewSecureChannel(cs.c)
if err := scV1.GenerateSecret(cs.ApplicationInfo.SecureChannelPublicKey); err != nil {
return err
}
scV1.Reset()
cs.sc = scV1
}
}
return nil
}
// isSecureChannelV2 returns true if the applet uses Secure Channel V2
// (app version >= 4.0).
func (cs *CommandSet) isSecureChannelV2() bool {
return cs.ApplicationInfo.AppVersion() >= 0x0400
}
// sendProtected wraps data in the secure channel (CLA 0x80) and transmits it.
func (cs *CommandSet) sendProtected(ins, p1, p2 uint8, data []byte) (*apdu.Response, error) {
cmd, err := cs.sc.ProtectedCommand(globalplatform.ClaGp, ins, p1, p2, data)
if err != nil {
return nil, err
}
return cs.sc.Transmit(cs.c, cmd)
}
// Init initializes the card with the given secrets.
//
// For V1 cards, uses OneShotEncrypt (encrypt with ECDH secret, send as raw command).
// For V2 cards, opens the secure channel first then sends INIT as an encrypted command.
func (cs *CommandSet) Init(secrets *Secrets) error {
// V1: use OneShotEncrypt (legacy flow)
if scV1, ok := cs.sc.(*SecureChannelV1); ok {
data, err := scV1.OneShotEncrypt(secrets)
if err != nil {
return err
}
initCmd := NewCommandInit(data)
resp, err := cs.c.Send(initCmd)
return apdu.CheckOK(resp, err)
}
// V2: open secure channel first, then send INIT as protected command
if err := cs.sc.AutoOpen(cs.c); err != nil {
return err
}
initData := cs.buildInitData(secrets.Pin(), secrets.Puk(), secrets.PairingToken(), nil, 0, 0)
resp, err := cs.sendProtected(InsInit, 0, 0, initData)
return apdu.CheckOK(resp, err)
}
// InitWithSecret initializes the card with a raw shared secret.
func (cs *CommandSet) InitWithSecret(pin, puk string, sharedSecret []byte) error {
return cs.initWithSecret(pin, nil, puk, sharedSecret, 0, 0)
}
// InitV2 initializes the card without a pairing password (V2 only).
//
// Secure Channel V2 does not use a shared secret for pairing, so this
// convenience method initializes the card with an empty shared secret.
// For V1 cards, use Init or InitWithSecret instead.
func (cs *CommandSet) InitV2(pin, puk string) error {
return cs.initWithSecret(pin, nil, puk, []byte{}, 0, 0)
}
// InitWithOptionsV2 initializes the card with optional alt PIN and retry counts.
func (cs *CommandSet) InitWithOptionsV2(pin, altPin, puk string, pinRetries, pukRetries uint8) error {
return cs.initWithSecret(pin, &altPin, puk, []byte{}, pinRetries, pukRetries)
}
// InitWithOptions initializes the card with optional alt PIN and retry counts.
func (cs *CommandSet) InitWithOptions(pin, altPin, puk, pairingPass string, pinRetries, pukRetries uint8) error {
sharedSecret := PairingPasswordToSecret(pairingPass)
return cs.initWithSecret(pin, &altPin, puk, sharedSecret, pinRetries, pukRetries)
}
func (cs *CommandSet) initWithSecret(pin string, altPin *string, puk string, sharedSecret []byte, pinRetries, pukRetries uint8) error {
initData := cs.buildInitData(pin, puk, sharedSecret, altPin, pinRetries, pukRetries)
// V2: open secure channel first, then send INIT as encrypted command
if _, ok := cs.sc.(*SecureChannelV2); ok {
if err := cs.sc.AutoOpen(cs.c); err != nil {
return err
}
resp, err := cs.sendProtected(InsInit, 0, 0, initData)
return apdu.CheckOK(resp, err)
}
// V1: use OneShotEncrypt
scV1, ok := cs.sc.(*SecureChannelV1)
if !ok {
return errors.New("expected SecureChannelV1 for init with secret")
}
encrypted, err := scV1.encryptedInitPayload(initData)
if err != nil {
return err
}
initCmd := NewCommandInit(encrypted)
resp, err := cs.c.Send(initCmd)
return apdu.CheckOK(resp, err)
}
// buildInitData builds the init payload: PIN || PUK || shared_secret || [pin_retries, puk_retries] || [alt_pin]
func (cs *CommandSet) buildInitData(pin, puk string, sharedSecret []byte, altPin *string, pinRetries, pukRetries uint8) []byte {
baseLen := len(pin) + len(puk) + len(sharedSecret)
extLen := 0
if altPin != nil && *altPin != "" {
extLen = 2 + len(*altPin)
} else if pinRetries != 0 || pukRetries != 0 {
extLen = 2
}
initData := make([]byte, 0, baseLen+extLen)
initData = append(initData, []byte(pin)...)
initData = append(initData, []byte(puk)...)
initData = append(initData, sharedSecret...)
if extLen > 0 {
initData = append(initData, pinRetries, pukRetries)
if altPin != nil && *altPin != "" {
initData = append(initData, []byte(*altPin)...)
}
}
return initData
}
// Pair pairs the card using a pairing password (V1 only, legacy PBKDF2-based flow).
//
// Deprecated: use AutoPairWithMode for new code.
func (cs *CommandSet) Pair(pairingPass string) error {
challenge := make([]byte, 32)
if _, err := rand.Read(challenge); err != nil {
return err
}
cmd := NewCommandPairFirstStep(challenge)
resp, err := cs.c.Send(cmd)
if resp != nil && resp.Sw == SwNoAvailablePairingSlots {
return ErrNoAvailablePairingSlots
}
if err = apdu.CheckOK(resp, err); err != nil {
return err
}
cardCryptogram := resp.Data[:32]
cardChallenge := resp.Data[32:]
secretHash, err := crypto.VerifyCryptogram(challenge, pairingPass, cardCryptogram)
if err != nil {
return err
}
h := sha256.New()
h.Write(secretHash[:])
h.Write(cardChallenge)
cmd = NewCommandPairFinalStep(h.Sum(nil))
resp, err = cs.c.Send(cmd)
if err = apdu.CheckOK(resp, err); err != nil {
return err
}
h.Reset()
h.Write(secretHash[:])
h.Write(resp.Data[1:])
pairingKey := h.Sum(nil)
pairingIndex := resp.Data[0]
var keyArr [32]byte
copy(keyArr[:], pairingKey)
cs.sc.SetPairing(types.NewPairing(keyArr, pairingIndex))
return nil
}
// AutoPairWithMode pairs the card using a pairing password with explicit mode.
func (cs *CommandSet) AutoPairWithMode(pairingPass string, mode uint8) error {
secret := PairingPasswordToSecret(pairingPass)
return cs.AutoPairWithSecretAndMode(secret, mode)
}
// AutoPairWithSecret pairs the card using a raw binary shared secret.
func (cs *CommandSet) AutoPairWithSecret(sharedSecret []byte) error {
return cs.AutoPairWithSecretAndMode(sharedSecret, P2PairAny)
}
// AutoPairWithSecretAndMode pairs the card using a raw binary shared secret with explicit mode.
func (cs *CommandSet) AutoPairWithSecretAndMode(sharedSecret []byte, mode uint8) error {
if err := cs.sc.AutoPair(cs.c, mode, sharedSecret); err != nil {
return err
}
return nil
}
// Unpair removes a pairing by index (V1 only).
func (cs *CommandSet) Unpair(index uint8) error {
_, err := cs.sc.Unpair(cs.c, index)
return err
}
// UnpairOthers unpairs all other clients (V1 only).
func (cs *CommandSet) UnpairOthers() error {
return cs.sc.UnpairOthers(cs.c)
}
// Identify sends an IDENTIFY CARD command and verifies the card's identity.
func (cs *CommandSet) Identify() ([]byte, error) {
challenge := make([]byte, 32)
if _, err := rand.Read(challenge); err != nil {
return nil, err
}
resp, err := cs.sendProtected(InsIdentify, 0, 0, challenge)
if err = apdu.CheckOK(resp, err); err != nil {
return nil, err
}
return types.VerifyIdentity(challenge, resp.Data)
}
// OpenSecureChannel opens the secure channel using V1 pairing-based flow.
//
// For V2 cards, use AutoOpenSecureChannel instead.
func (cs *CommandSet) OpenSecureChannel() error {
if cs.ApplicationInfo == nil {
return errors.New("cannot open secure channel without application info")
}
// V1 flow
scV1, ok := cs.sc.(*SecureChannelV1)
if !ok {
return errors.New("OpenSecureChannel is for V1 cards; use AutoOpenSecureChannel for V2")
}
pairing := cs.sc.Pairing()
if pairing == nil {
return errors.New("cannot open secure channel without pairing")
}
cmd := NewCommandOpenSecureChannel(pairing.Index(), scV1.RawPublicKey())
resp, err := cs.c.Send(cmd)
if err = apdu.CheckOK(resp, err); err != nil {
return err
}
pairingKey := pairing.Key()
encKey, macKey, iv := crypto.DeriveSessionKeys(scV1.Secret(), pairingKey[:], resp.Data)
scV1.Init(iv, encKey, macKey)
err = cs.mutualAuthenticate()
if err != nil {
return err
}
return nil
}
// AutoOpenSecureChannel opens the secure channel using the auto-detected version.
func (cs *CommandSet) AutoOpenSecureChannel() error {
return cs.sc.AutoOpen(cs.c)
}
// GetStatus returns the application status for the given info type.
func (cs *CommandSet) GetStatus(info uint8) (*types.ApplicationStatus, error) {
resp, err := cs.sendProtected(InsGetStatus, info, 0, nil)
if err = apdu.CheckOK(resp, err); err != nil {
return nil, err
}
return types.ParseApplicationStatus(resp.Data)
}
// GetStatusApplication returns the application-level status.
func (cs *CommandSet) GetStatusApplication() (*types.ApplicationStatus, error) {
return cs.GetStatus(P1GetStatusApplication)
}
// GetStatusKeyPath returns the key-path status.
func (cs *CommandSet) GetStatusKeyPath() (*types.ApplicationStatus, error) {
return cs.GetStatus(P1GetStatusKeyPath)
}
// VerifyPIN verifies the user PIN.
func (cs *CommandSet) VerifyPIN(pin string) error {
resp, err := cs.sendProtected(InsVerifyPIN, 0, 0, []byte(pin))
if err = apdu.CheckOK(resp, err); err != nil {
if resp != nil && ((resp.Sw & 0x63C0) == 0x63C0) {
remainingAttempts := resp.Sw & 0x000F
return &WrongPINError{
RemainingAttempts: int(remainingAttempts),
}
}
return err
}
return nil
}
// ChangePIN changes the user PIN.
func (cs *CommandSet) ChangePIN(pin string) error {
resp, err := cs.sendProtected(InsChangePIN, P1ChangePinPIN, 0, []byte(pin))
return apdu.CheckOK(resp, err)
}
// UnblockPIN unblocks the PIN using the PUK and a new PIN.
func (cs *CommandSet) UnblockPIN(puk string, newPIN string) error {
data := append([]byte(puk), []byte(newPIN)...)
resp, err := cs.sendProtected(InsUnblockPIN, 0, 0, data)
if err = apdu.CheckOK(resp, err); err != nil {
if resp != nil && ((resp.Sw & 0x63C0) == 0x63C0) {
remainingAttempts := resp.Sw & 0x000F
return &WrongPUKError{
RemainingAttempts: int(remainingAttempts),
}
}
return err
}
return nil
}
// ChangePUK changes the PUK.
func (cs *CommandSet) ChangePUK(puk string) error {
resp, err := cs.sendProtected(InsChangePIN, P1ChangePinPUK, 0, []byte(puk))
return apdu.CheckOK(resp, err)
}
// ChangePairingSecret changes the pairing secret (legacy, uses PBKDF2 from secrets.go).
//
// Deprecated: use ChangePairingPassword instead.
func (cs *CommandSet) ChangePairingSecret(password string) error {
secret := generatePairingToken(password)
resp, err := cs.sendProtected(InsChangePIN, P1ChangePinPairingSecret, 0, secret)
return apdu.CheckOK(resp, err)
}
// ChangePairingPassword changes the pairing password.
func (cs *CommandSet) ChangePairingPassword(password string) error {
secret := PairingPasswordToSecret(password)
resp, err := cs.sendProtected(InsChangePIN, P1ChangePinPairingSecret, 0, secret)
return apdu.CheckOK(resp, err)
}
// GenerateKey generates a new key on the card.
func (cs *CommandSet) GenerateKey() ([]byte, error) {
resp, err := cs.sendProtected(InsGenerateKey, 0, 0, nil)
if err = apdu.CheckOK(resp, err); err != nil {
return nil, err
}
return resp.Data, nil
}
// GenerateMnemonic generates a mnemonic on the card.
func (cs *CommandSet) GenerateMnemonic(checksumSize int) ([]int, error) {
if checksumSize < 4 || checksumSize > 8 {
return nil, ErrBadChecksumSize
}
resp, err := cs.sendProtected(InsGenerateMnemonic, byte(checksumSize), 0, nil)
if err = apdu.CheckOK(resp, err); err != nil {
return nil, err
}
return parseMnemonicResponse(resp.Data)
}
func parseMnemonicResponse(data []byte) ([]int, error) {
indexes := make([]int, 0, len(data)/2)
for i := 0; i+1 < len(data); i += 2 {
index := int(data[i])<<8 | int(data[i+1])
indexes = append(indexes, index)
}
return indexes, nil
}
// RemoveKey removes the current key from the card.
func (cs *CommandSet) RemoveKey() error {
resp, err := cs.sendProtected(InsRemoveKey, 0, 0, nil)
return apdu.CheckOK(resp, err)
}
// DeriveKey derives a key at the given BIP32 path.
func (cs *CommandSet) DeriveKey(path string) error {
kp, err := derivationpath.KeyPathFromString(path)
if err != nil {
return err
}
resp, err := cs.sendProtected(InsDeriveKey, uint8(kp.Source()), 0, kp.Data())
return apdu.CheckOK(resp, err)
}
// LoadSeed loads a BIP32 seed onto the card.
func (cs *CommandSet) LoadSeed(seed []byte) ([]byte, error) {
resp, err := cs.sendProtected(InsLoadKey, P1LoadKeySeed, 0, seed)
if err = apdu.CheckOK(resp, err); err != nil {
return nil, err
}
return resp.Data, nil
}
// LoadKeyBIP32 loads a BIP32 keypair onto the card (includes public key).
func (cs *CommandSet) LoadKeyBIP32(keyPair *types.Bip32KeyPair) error {
return cs.loadKeyBIP32Inner(keyPair, false)
}
// LoadKeyBIP32OmitPublic loads a BIP32 keypair onto the card (omits public key).
func (cs *CommandSet) LoadKeyBIP32OmitPublic(keyPair *types.Bip32KeyPair) error {
return cs.loadKeyBIP32Inner(keyPair, true)
}
func (cs *CommandSet) loadKeyBIP32Inner(keyPair *types.Bip32KeyPair, omitPublic bool) error {
includePublic := !omitPublic
p1 := uint8(P1LoadKeyEC)
if keyPair.IsExtended() {
p1 = P1LoadKeyECExtended
}
keyTLV := keyPair.ToTLV(includePublic)
resp, err := cs.sendProtected(InsLoadKey, p1, 0, keyTLV)
return apdu.CheckOK(resp, err)
}
// LoadLEEKey loads an LEE seed onto the card.
func (cs *CommandSet) LoadLEEKey(seed []byte) error {
resp, err := cs.sendProtected(InsLoadKey, P1LoadKeyLEE, 0, seed)
return apdu.CheckOK(resp, err)
}
// ExportKey exports a key at the given path.
//
// Deprecated: use ExportKeyExtended for the new API.
func (cs *CommandSet) ExportKey(derive bool, makeCurrent bool, onlyPublic bool, path string) ([]byte, []byte, error) {
var p2 uint8
if onlyPublic {
p2 = P2ExportKeyPublicOnly
} else {
p2 = P2ExportKeyPrivateAndPublic
}
key, err := cs.ExportKeyExtended(derive, makeCurrent, p2, path)
if err != nil {
return nil, nil, err
}
return key.PrivKey(), key.PubKey(), nil
}
// ExportKeyExtended exports a key at the given path with explicit P2.
func (cs *CommandSet) ExportKeyExtended(derive bool, makeCurrent bool, p2 uint8, path string) (*types.ExportedKey, error) {
return cs.ExportKeyWithP2(derive, makeCurrent, p2, path)
}
// ExportCurrentKey exports the current key.
func (cs *CommandSet) ExportCurrentKey(publicOnly bool) (*types.ExportedKey, error) {
p2 := uint8(P2ExportKeyPrivateAndPublic)
if publicOnly {
p2 = P2ExportKeyPublicOnly
}
resp, err := cs.sendProtected(InsExportKey, P1ExportKeyCurrent, p2, nil)
if err = apdu.CheckOK(resp, err); err != nil {
return nil, err
}
return types.ParseExportKeyResponse(resp.Data)
}
// ExportKeyWithP2 exports a key at the given path with explicit P2.
func (cs *CommandSet) ExportKeyWithP2(derive, makeCurrent bool, p2 uint8, path string) (*types.ExportedKey, error) {
kp, err := derivationpath.KeyPathFromString(path)
if err != nil {
return nil, err
}
p1 := kp.Source()
if derive {
if makeCurrent {
p1 |= P1ExportKeyDeriveAndMakeCurrent
} else {
p1 |= P1ExportKeyDerive
}
}
resp, err := cs.sendProtected(InsExportKey, p1, p2, kp.Data())
if err = apdu.CheckOK(resp, err); err != nil {
return nil, err
}
return types.ParseExportKeyResponse(resp.Data)
}
// ExportLEEKey exports an LEE key at the given BIP32 path.
func (cs *CommandSet) ExportLEEKey(keypath string) ([]byte, error) {
kp, err := derivationpath.KeyPathFromString(keypath)
if err != nil {
return nil, err
}
resp, err := cs.sendProtected(InsExportLEE, kp.Source(), 0, kp.Data())
if err = apdu.CheckOK(resp, err); err != nil {
return nil, err
}
return resp.Data, nil
}
// ExportLEEKeyParsed exports an LEE key at the given BIP32 path and parses the
// response into a types.LeeKey.
func (cs *CommandSet) ExportLEEKeyParsed(keypath string) (*types.LeeKey, error) {
data, err := cs.ExportLEEKey(keypath)
if err != nil {
return nil, err
}
return types.ParseLeeKey(data)
}
// ECDH computes an ECDH shared secret between the key derived at the given
// path and a peer public key.
//
// The card only permits derivation under the NIP-44 (m/44'/1237') and
// EIP-1581 (m/43'/60'/1581') prefixes at a depth of at least 5 components;
// any other path is refused by the card.
//
// The returned data is the raw x-coordinate of the resulting point (32 bytes),
// not an encryption key. Protocols are expected to run it through a KDF
// host-side (NIP-44 uses HKDF-extract with salt "nip44-v2").
func (cs *CommandSet) ECDH(peerPublicKey []byte, keypath string) ([]byte, error) {
kp, err := derivationpath.KeyPathFromString(keypath)
if err != nil {
return nil, err
}
if kp.Source() != derivationpath.SourceMaster {
return nil, fmt.Errorf("ECDH requires an absolute path derived from the master key")
}
return cs.ECDHRaw(peerPublicKey, kp.Data())
}
// ECDHRaw computes an ECDH shared secret using raw path bytes.
//
// The peer public key must be an uncompressed secp256k1 point (0x04 || X || Y,
// 65 bytes) and the path is appended verbatim.
func (cs *CommandSet) ECDHRaw(peerPublicKey []byte, path []byte) ([]byte, error) {
if len(peerPublicKey) != Secp256k1UncompressedPubKeySize ||
peerPublicKey[0] != UncompressedPointTag {
return nil, fmt.Errorf(
"peer public key must be a %d byte uncompressed point (0x04 || X || Y), got %d bytes",
Secp256k1UncompressedPubKeySize, len(peerPublicKey),
)
}
data := make([]byte, 0, len(peerPublicKey)+len(path))
data = append(data, peerPublicKey...)
data = append(data, path...)
// P1 is always P1SignDerive (0x01) and P2 is always P2ECDHRawSecret.
resp, err := cs.sendProtected(InsECDH, P1SignDerive, P2ECDHRawSecret, data)
if err = apdu.CheckOK(resp, err); err != nil {
return nil, err
}
return resp.Data, nil
}
// ExportBIP85 exports a BIP85 derived key at the given path.
func (cs *CommandSet) ExportBIP85(keypath string, length uint8) ([]byte, error) {
kp, err := derivationpath.KeyPathFromString(keypath)
if err != nil {
return nil, err
}
resp, err := cs.sendProtected(InsExportBIP85, length, 0, kp.Data())
if err = apdu.CheckOK(resp, err); err != nil {
return nil, err
}
return resp.Data, nil
}
// SetPinlessPath sets the pinless signing path.
func (cs *CommandSet) SetPinlessPath(path string) error {
kp, err := derivationpath.KeyPathFromString(path)
if err != nil {
return err
}
if kp.Source() != derivationpath.SourceMaster {
return errors.New("pinless path must be set with an absolute path")
}
resp, err := cs.sendProtected(InsSetPinlessPath, 0, 0, kp.Data())
return apdu.CheckOK(resp, err)
}
// ResetPinlessPath clears the pinless signing path.
func (cs *CommandSet) ResetPinlessPath() error {
resp, err := cs.sendProtected(InsSetPinlessPath, 0, 0, nil)
return apdu.CheckOK(resp, err)
}
// Sign signs a 32-byte hash with the current key (ECDSA).
func (cs *CommandSet) Sign(data []byte) (*types.Signature, error) {
resp, err := cs.sendProtected(InsSign, P1SignCurrentKey, P2SignECDSA, data)
if err = apdu.CheckOK(resp, err); err != nil {
return nil, err
}
return types.ParseSignature(data, resp.Data)
}
// SignWithPath signs a 32-byte hash with a derived key path (ECDSA).
func (cs *CommandSet) SignWithPath(data []byte, path string) (*types.Signature, error) {
return cs.SignWithPathAndAlgo(data, path, P2SignECDSA)
}
func (cs *CommandSet) SignBIP341Schnorr(hash []byte, tweak []byte, path string) (*types.Signature, error) {
if len(hash) != 32 {
return nil, fmt.Errorf("hash length must be 32, got %d", len(hash))
}
if len(tweak) != 32 {
return nil, fmt.Errorf("tweak length must be 32, got %d", len(tweak))
}
data := make([]byte, 0, len(hash)+len(tweak))
data = append(data, hash...)
data = append(data, tweak...)
return cs.SignWithPathAndAlgo(data, path, P2SignBIP340Schnorr)
}
// SignWithPathAndAlgo signs a 32-byte hash with a derived key path and explicit algorithm.
func (cs *CommandSet) SignWithPathAndAlgo(data []byte, path string, algo uint8) (*types.Signature, error) {
if algo == P2SignBIP340Schnorr {
if len(data) == 32 {
data = append(data, make([]byte, 32)...)
} else if len(data) != 64 {
return nil, fmt.Errorf("data length must be 32 or 64 when using Schnorr, got %d", len(data))
}
} else {
if len(data) != 32 {
return nil, fmt.Errorf("data length must be 32, got %d", len(data))
}
}
kp, err := derivationpath.KeyPathFromString(path)
if err != nil {
return nil, err
}
// Build data: hash || path_data
cmdData := make([]byte, 0, len(data)+len(kp.Data()))
cmdData = append(cmdData, data...)
cmdData = append(cmdData, kp.Data()...)
p1 := uint8(kp.Source()) | P1SignDerive
resp, err := cs.sendProtected(InsSign, p1, algo, cmdData)
if err = apdu.CheckOK(resp, err); err != nil {
return nil, err
}
return types.ParseSignature(data, resp.Data)
}
// SignPinless signs using the pinless path (no secure channel needed).
func (cs *CommandSet) SignPinless(data []byte) (*types.Signature, error) {
if len(data) != 32 {
return nil, fmt.Errorf("data length must be 32, got %d", len(data))
}
cmd := apdu.NewCommand(globalplatform.ClaGp, InsSign, P1SignPinless, P2SignECDSA, data)
resp, err := cs.c.Send(cmd)
if err = apdu.CheckOK(resp, err); err != nil {
return nil, err
}
return types.ParseSignature(data, resp.Data)
}
// GetData retrieves stored data by type.
func (cs *CommandSet) GetData(typ uint8) ([]byte, error) {
resp, err := cs.sendProtected(InsGetData, typ, 0, nil)
if err = apdu.CheckOK(resp, err); err != nil {
return nil, err
}
return resp.Data, nil
}
// StoreData stores data by type at offset 0.
func (cs *CommandSet) StoreData(typ uint8, data []byte) error {
resp, err := cs.sendProtected(InsStoreData, typ, 0, data)
return apdu.CheckOK(resp, err)
}
// StoreDataWithOffset stores data by type at an explicit offset.
// Offset must be a multiple of 4.
func (cs *CommandSet) StoreDataWithOffset(typ uint8, data []byte, offset uint16) error {
resp, err := cs.sendProtected(InsStoreData, typ, byte(offset/4), data)
return apdu.CheckOK(resp, err)
}
// SetNDEF sets the NDEF message on the card.
//
// For app version > 2.x, data is chunked and stored via STORE_DATA.
// For app version <= 2.x, data is sent directly via the legacy SET_NDEF command.
func (cs *CommandSet) SetNDEF(ndef []byte) error {
appMajor := uint8(0)
if cs.ApplicationInfo != nil {
appMajor = uint8(cs.ApplicationInfo.AppVersion() >> 8)
}
if appMajor > 2 {
// Ensure 2-byte length prefix
data := make([]byte, len(ndef))
copy(data, ndef)
hasPrefix := len(data) >= 2
if hasPrefix {
expectedLen := int(data[0])<<8 | int(data[1])
if expectedLen != len(data)-2 {
hasPrefix = false
}
}
if !hasPrefix {
prefixed := make([]byte, 2+len(ndef))
prefixed[0] = byte(len(ndef) >> 8)
prefixed[1] = byte(len(ndef) & 0xFF)
copy(prefixed[2:], ndef)
data = prefixed
}
off := 0
remaining := len(data)
for remaining > 0 {
chunkSize := NDEFMaxChunkSize
if remaining < chunkSize {
chunkSize = remaining
}
chunk := data[off : off+chunkSize]
if err := cs.StoreDataWithOffset(P1StoreDataNDEF, chunk, uint16(off)); err != nil {
return err
}
off += chunkSize
remaining -= chunkSize
}
return nil
}
// Legacy SET_NDEF (app version <= 2.x)
resp, err := cs.sendProtected(InsSetNDEF, 0, 0, ndef)
return apdu.CheckOK(resp, err)
}
// GetChallenge requests a random challenge from the card.
func (cs *CommandSet) GetChallenge(length uint8) ([]byte, error) {
resp, err := cs.sendProtected(InsGetChallenge, length, 0, nil)
if err = apdu.CheckOK(resp, err); err != nil {
return nil, err
}
return resp.Data, nil
}
// FactoryReset sends the FACTORY RESET command (unencrypted).
func (cs *CommandSet) FactoryReset() error {
cmd := NewCommandFactoryReset()
resp, err := cs.c.Send(cmd)
return apdu.CheckOK(resp, err)
}
// -----------------------------------------------------------------------
// Accessors
// -----------------------------------------------------------------------
// AppInfo returns the application info from the last SELECT command.
func (cs *CommandSet) AppInfo() *types.ApplicationInfo {
return cs.ApplicationInfo
}
// SecureChannelVersion returns the secure channel version in use.
//
// Returns (VersionV1, true) or (VersionV2, true) if secure channel is
// supported, or (VersionV1, false) if the applet has not been selected yet.
func (cs *CommandSet) SecureChannelVersion() (SecureChannelVersion, bool) {
if cs.ApplicationInfo == nil || !cs.ApplicationInfo.HasSecureChannelCapability() {
return VersionV1, false
}
return cs.sc.Version(), true
}
// Pairing returns the current pairing data (V1 only, nil for V2).
func (cs *CommandSet) Pairing() *types.Pairing {
return cs.sc.Pairing()
}
// SetPairing sets the pairing data (V1 only, no-op for V2).
func (cs *CommandSet) SetPairing(p *types.Pairing) {
cs.sc.SetPairing(p)
}
// PairingPasswordToSecret converts a pairing password to a binary pairing
// secret via PBKDF2-HMAC-SHA256.
func PairingPasswordToSecret(password string) []byte {
return generatePairingToken(password)
}
// -----------------------------------------------------------------------
// Internal helpers
// -----------------------------------------------------------------------
func (cs *CommandSet) mutualAuthenticate() error {
resp, err := cs.sendProtected(InsMutuallyAuthenticate, 0, 0, nil)
return apdu.CheckOK(resp, err)
}