-
Notifications
You must be signed in to change notification settings - Fork 17
/
shell.go
1052 lines (834 loc) · 24.7 KB
/
shell.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
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
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bufio"
"bytes"
"encoding/hex"
"errors"
"fmt"
"html/template"
"io"
"log"
"os"
"regexp"
"strconv"
"strings"
"github.com/ethereum/go-ethereum/crypto"
keycard "github.com/status-im/keycard-go"
"github.com/status-im/keycard-go/apdu"
"github.com/status-im/keycard-go/globalplatform"
keycardio "github.com/status-im/keycard-go/io"
"github.com/status-im/keycard-go/types"
)
type shellCommand = func(args ...string) error
type TemplateFuncs struct {
s *Shell
}
func (t *TemplateFuncs) FuncMap() template.FuncMap {
return template.FuncMap{
"env": t.Env,
"session_pairing_key": t.SessionPairingKey,
"session_pairing_index": t.SessionPairingIndex,
"session_pin": t.SessionPIN,
"session_puk": t.SessionPUK,
"session_pairing_password": t.SessionPairingPassword,
}
}
func (t *TemplateFuncs) Env(name string) (string, error) {
value := os.Getenv(name)
if value == "" {
return "", fmt.Errorf("env variable is empty: %s", name)
}
return value, nil
}
func (t *TemplateFuncs) SessionPairingKey() (string, error) {
if t.s.kCmdSet.PairingInfo == nil {
return "", errors.New("pairing key not known")
}
return fmt.Sprintf("%x", t.s.kCmdSet.PairingInfo.Key), nil
}
func (t *TemplateFuncs) SessionPairingIndex() (string, error) {
if t.s.kCmdSet.PairingInfo == nil {
return "", errors.New("pairing index not known")
}
return fmt.Sprintf("%d", t.s.kCmdSet.PairingInfo.Index), nil
}
func (t *TemplateFuncs) SessionPIN() (string, error) {
if t.s.Secrets == nil {
return "", errors.New("pin is not set")
}
return t.s.Secrets.Pin(), nil
}
func (t *TemplateFuncs) SessionPUK() (string, error) {
if t.s.Secrets == nil {
return "", errors.New("puk is not set")
}
return t.s.Secrets.Puk(), nil
}
func (t *TemplateFuncs) SessionPairingPassword() (string, error) {
if t.s.Secrets == nil {
return "", errors.New("pairing password is not set")
}
return t.s.Secrets.PairingPass(), nil
}
type Shell struct {
t keycardio.Transmitter
c types.Channel
Secrets *keycard.Secrets
gpCmdSet *globalplatform.CommandSet
kCmdSet *keycard.CommandSet
cashCmdSet *keycard.CashCommandSet
commands map[string]shellCommand
out *bytes.Buffer
tplFuncMap template.FuncMap
}
func NewShell(t keycardio.Transmitter) *Shell {
c := keycardio.NewNormalChannel(t)
s := &Shell{
t: t,
c: c,
kCmdSet: keycard.NewCommandSet(c),
cashCmdSet: keycard.NewCashCommandSet(c),
gpCmdSet: globalplatform.NewCommandSet(c),
out: new(bytes.Buffer),
}
tplFuncs := &TemplateFuncs{s}
s.tplFuncMap = tplFuncs.FuncMap()
s.commands = map[string]shellCommand{
"echo": s.commandEcho,
"gp-send-apdu": s.commandGPSendAPDU,
"gp-select": s.commandGPSelect,
"gp-open-secure-channel": s.commandGPOpenSecureChannel,
"gp-delete": s.commandGPDelete,
"gp-load": s.commandGPLoad,
"gp-install-for-install": s.commandGPInstallForInstall,
"gp-get-status": s.commandGPGetStatus,
"keycard-init": s.commandKeycardInit,
"keycard-select": s.commandKeycardSelect,
"keycard-pair": s.commandKeycardPair,
"keycard-unpair": s.commandKeycardUnpair,
"keycard-open-secure-channel": s.commandKeycardOpenSecureChannel,
"keycard-get-status": s.commandKeycardGetStatus,
"keycard-set-secrets": s.commandKeycardSetSecrets,
"keycard-set-pairing": s.commandKeycardSetPairing,
"keycard-verify-pin": s.commandKeycardVerifyPIN,
"keycard-change-pin": s.commandKeycardChangePIN,
"keycard-change-puk": s.commandKeycardChangePUK,
"keycard-unblock-pin": s.commandKeycardUnblockPin,
"keycard-change-pairing-secret": s.commandKeycardChangePairingSecret,
"keycard-generate-key": s.commandKeycardGenerateKey,
"keycard-remove-key": s.commandKeycardRemoveKey,
"keycard-derive-key": s.commandKeycardDeriveKey,
"keycard-export-key-private": s.commandKeycardExportKeyPrivate,
"keycard-export-key-public": s.commandKeycardExportKeyPublic,
"keycard-sign": s.commandKeycardSign,
"keycard-sign-with-path": s.commandKeycardSignWithPath,
"keycard-sign-message": s.commandKeycardSignMessage,
"keycard-sign-pinless": s.commandKeycardSignPinless,
"keycard-sign-message-pinless": s.commandKeycardSignMessagePinless,
"keycard-set-pinless-path": s.commandKeycardSetPinlessPath,
"keycard-load-seed": s.commandKeycardLoadSeed,
"keycard-generate-mnemonic": s.commandKeycardGenerateMnemonic,
"keycard-identify": s.commandKeycardIdentify,
"cash-select": s.commandCashSelect,
"cash-sign": s.commandCashSign,
}
return s
}
func (s *Shell) write(str string) {
s.out.WriteString(str)
}
func (s *Shell) flushOut() {
io.Copy(os.Stdout, s.out)
}
func (s *Shell) Run() error {
reader := bufio.NewReader(os.Stdin)
defer s.flushOut()
for {
line, err := reader.ReadString('\n')
if err != nil && err != io.EOF {
break
}
err = s.evalLine(line)
if err != nil {
return err
}
}
return nil
}
func (s *Shell) commandEcho(args ...string) error {
fmt.Printf("> %s\n", strings.Join(args, " "))
return nil
}
func (s *Shell) commandGPSendAPDU(args ...string) error {
if err := s.requireArgs(args, 1); err != nil {
return err
}
rawCmd, err := hex.DecodeString(args[0])
if err != nil {
return err
}
cmd, err := apdu.ParseCommand(rawCmd)
if err != nil {
logger.Error("error parsing command", "error", err)
return err
}
var channel types.Channel
if sc := s.gpCmdSet.SecureChannel(); sc != nil {
channel = sc
} else {
channel = s.gpCmdSet.Channel()
}
logger.Info(fmt.Sprintf("send apdu %x", rawCmd))
resp, err := channel.Send(cmd)
if err != nil {
logger.Error("send apdu failed", "error", err)
return err
}
if resp.Sw != apdu.SwOK {
logger.Error("unexpected response", "sw", fmt.Sprintf("%x", resp.Sw))
return apdu.NewErrBadResponse(resp.Sw, "unexpected response")
}
return nil
}
func (s *Shell) commandGPSelect(args ...string) error {
if err := s.requireArgs(args, 0, 1); err != nil {
return err
}
if len(args) == 0 {
logger.Info("select ISD")
return s.gpCmdSet.Select()
}
aid, err := hex.DecodeString(args[0])
if err != nil {
return err
}
logger.Info(fmt.Sprintf("select AID %x", aid))
return s.gpCmdSet.SelectAID(aid)
}
func (s *Shell) commandGPOpenSecureChannel(args ...string) error {
if err := s.requireArgs(args, 0); err != nil {
return err
}
logger.Info("open secure channel")
return s.gpCmdSet.OpenSecureChannel()
}
func (s *Shell) commandGPDelete(args ...string) error {
if err := s.requireArgs(args, 1); err != nil {
return err
}
aid, err := hex.DecodeString(args[0])
if err != nil {
return err
}
logger.Info(fmt.Sprintf("delete %x", aid))
return s.gpCmdSet.DeleteObject(aid)
}
func (s *Shell) commandGPLoad(args ...string) error {
if err := s.requireArgs(args, 2); err != nil {
return err
}
f, err := os.Open(args[0])
if err != nil {
return err
}
defer f.Close()
pkgAID, err := hex.DecodeString(args[1])
if err != nil {
return err
}
logger.Info("load package")
callback := func(index, total int) {
logger.Debug(fmt.Sprintf("loading %d/%d", index+1, total))
}
if err = s.gpCmdSet.LoadPackage(f, pkgAID, callback); err != nil {
logger.Error("load failed", "error", err)
return err
}
return nil
}
func (s *Shell) commandGPInstallForInstall(args ...string) error {
if err := s.requireArgs(args, 3, 4); err != nil {
return err
}
pkgAID, err := hex.DecodeString(args[0])
if err != nil {
return err
}
appletAID, err := hex.DecodeString(args[1])
if err != nil {
return err
}
instanceAID, err := hex.DecodeString(args[2])
if err != nil {
return err
}
var params []byte
if len(args) == 4 {
params, err = hex.DecodeString(args[3])
if err != nil {
return err
}
}
logger.Info("install for install", "pkg", fmt.Sprintf("%x", pkgAID), "applet", fmt.Sprintf("%x", appletAID), "instance", fmt.Sprintf("%x", instanceAID), "params", fmt.Sprintf("%x", params))
return s.gpCmdSet.InstallForInstall(pkgAID, appletAID, instanceAID, params)
}
func (s *Shell) commandGPGetStatus(args ...string) error {
if err := s.requireArgs(args, 0); err != nil {
return err
}
logger.Info("get status")
cardStatus, err := s.gpCmdSet.GetStatus()
if err != nil {
logger.Error("get status failed", "error", err)
return err
}
s.write(fmt.Sprintf("CARD STATUS: %s\n\n", cardStatus.LifeCycle()))
return nil
}
func (s *Shell) commandKeycardInit(args ...string) error {
if err := s.requireArgs(args, 0); err != nil {
return err
}
if s.kCmdSet.ApplicationInfo == nil {
return errors.New("keycard applet not selected")
}
if !s.kCmdSet.ApplicationInfo.Installed {
return errAppletNotInstalled
}
if s.kCmdSet.ApplicationInfo.Initialized {
return errCardAlreadyInitialized
}
if s.Secrets == nil {
secrets, err := keycard.GenerateSecrets()
if err != nil {
logger.Error("secrets generation failed", "error", err)
return err
}
s.Secrets = secrets
}
logger.Info("initializing")
err := s.kCmdSet.Init(s.Secrets)
if err != nil {
logger.Error("initialization failed", "error", err)
return err
}
s.write(fmt.Sprintf("PIN: %s\n", s.Secrets.Pin()))
s.write(fmt.Sprintf("PUK: %s\n", s.Secrets.Puk()))
s.write(fmt.Sprintf("PAIRING PASSWORD: %s\n\n", s.Secrets.PairingPass()))
return nil
}
func (s *Shell) commandKeycardSetSecrets(args ...string) error {
if err := s.requireArgs(args, 3); err != nil {
return err
}
s.Secrets = keycard.NewSecrets(args[0], args[1], args[2])
return nil
}
func (s *Shell) commandKeycardSelect(args ...string) error {
if err := s.requireArgs(args, 0); err != nil {
return err
}
logger.Info("select keycard")
err := s.kCmdSet.Select()
info := s.kCmdSet.ApplicationInfo
var keyInitialized bool
if len(info.KeyUID) > 0 {
keyInitialized = true
}
s.write(fmt.Sprintf("Installed: %+v\n", info.Installed))
s.write(fmt.Sprintf("Initialized: %+v\n", info.Initialized))
s.write(fmt.Sprintf("Key Initialized: %+v\n", keyInitialized))
s.write(fmt.Sprintf("InstanceUID: %x\n", info.InstanceUID))
s.write(fmt.Sprintf("SecureChannelPublicKey: %x\n", info.SecureChannelPublicKey))
s.write(fmt.Sprintf("Version: %x\n", info.Version))
s.write(fmt.Sprintf("AvailableSlots: %x\n", info.AvailableSlots))
s.write(fmt.Sprintf("KeyUID: %x\n", info.KeyUID))
s.write(fmt.Sprintf("Capabilities:\n"))
s.write(fmt.Sprintf(" Secure channel:%v\n", info.HasSecureChannelCapability()))
s.write(fmt.Sprintf(" Key management:%v\n", info.HasKeyManagementCapability()))
s.write(fmt.Sprintf(" Credentials Management:%v\n", info.HasCredentialsManagementCapability()))
s.write(fmt.Sprintf(" NDEF:%v\n\n", info.HasNDEFCapability()))
if e, ok := err.(*apdu.ErrBadResponse); ok && e.Sw == globalplatform.SwFileNotFound {
logger.Error("select keycard failed", "error", err)
return ErrNotInstalled
}
return err
}
func (s *Shell) commandKeycardPair(args ...string) error {
if err := s.requireArgs(args, 0); err != nil {
return err
}
if s.Secrets == nil {
return errors.New("cannot pair without setting secrets")
}
logger.Info("pair")
err := s.kCmdSet.Pair(s.Secrets.PairingPass())
if err != nil {
logger.Error("pair failed", "error", err)
return err
}
s.write(fmt.Sprintf("PAIRING KEY: %x\n", s.kCmdSet.PairingInfo.Key))
s.write(fmt.Sprintf("PAIRING INDEX: %v\n\n", s.kCmdSet.PairingInfo.Index))
return nil
}
func (s *Shell) commandKeycardUnpair(args ...string) error {
if err := s.requireArgs(args, 1); err != nil {
return err
}
indexInt, err := strconv.ParseInt(args[0], 10, 8)
if err != nil {
return err
}
index := uint8(indexInt)
if s.Secrets == nil {
return errors.New("cannot unpair without setting secrets")
}
logger.Info(fmt.Sprintf("unpair index %d", index))
err = s.kCmdSet.Unpair(index)
if err != nil {
logger.Error("unpair failed", "error", err)
return err
}
s.write("UNPAIRED\n\n")
return nil
}
func (s *Shell) commandKeycardSetPairing(args ...string) error {
if err := s.requireArgs(args, 2); err != nil {
return err
}
key, err := s.parseHex(args[0])
if err != nil {
return err
}
index, err := strconv.ParseInt(args[1], 10, 8)
if err != nil {
return err
}
s.kCmdSet.SetPairingInfo(key, int(index))
return nil
}
func (s *Shell) commandKeycardOpenSecureChannel(args ...string) error {
if err := s.requireArgs(args, 0); err != nil {
return err
}
if s.kCmdSet.PairingInfo == nil {
return errors.New("cannot open secure channel without setting pairing info")
}
logger.Info("open keycard secure channel")
if err := s.kCmdSet.OpenSecureChannel(); err != nil {
logger.Error("open keycard secure channel failed", "error", err)
return err
}
return nil
}
func (s *Shell) commandKeycardGetStatus(args ...string) error {
if err := s.requireArgs(args, 0); err != nil {
return err
}
logger.Info("get status application")
appStatus, err := s.kCmdSet.GetStatusApplication()
if err != nil {
logger.Error("get status application failed", "error", err)
return err
}
logger.Info("get status key path")
keyStatus, err := s.kCmdSet.GetStatusKeyPath()
if err != nil {
logger.Error("get status key path failed", "error", err)
return err
}
s.write(fmt.Sprintf("STATUS - PIN RETRY COUNT: %d\n", appStatus.PinRetryCount))
s.write(fmt.Sprintf("STATUS - PUK RETRY COUNT: %d\n", appStatus.PUKRetryCount))
s.write(fmt.Sprintf("STATUS - KEY INITIALIZED: %v\n", appStatus.KeyInitialized))
s.write(fmt.Sprintf("STATUS - KEY PATH: %v\n\n", keyStatus.Path))
return nil
}
func (s *Shell) commandKeycardVerifyPIN(args ...string) error {
if err := s.requireArgs(args, 1); err != nil {
return err
}
logger.Info("verify PIN")
if err := s.kCmdSet.VerifyPIN(args[0]); err != nil {
logger.Error("verify PIN failed", "error", err)
return err
}
return nil
}
func (s *Shell) commandKeycardChangePIN(args ...string) error {
if err := s.requireArgs(args, 1); err != nil {
return err
}
logger.Info("change PIN")
if err := s.kCmdSet.ChangePIN(args[0]); err != nil {
logger.Error("change PIN failed", "error", err)
return err
}
return nil
}
func (s *Shell) commandKeycardChangePUK(args ...string) error {
if err := s.requireArgs(args, 1); err != nil {
return err
}
logger.Info("change PUK")
if err := s.kCmdSet.ChangePUK(args[0]); err != nil {
logger.Error("change PUK failed", "error", err)
return err
}
return nil
}
func (s *Shell) commandKeycardUnblockPin(args ...string) error {
if err := s.requireArgs(args, 2); err != nil {
return err
}
logger.Info("unblock PIN")
if err := s.kCmdSet.UnblockPIN(args[0], args[1]); err != nil {
logger.Error("unblock PIN failed", "error", err)
return err
}
return nil
}
func (s *Shell) commandKeycardChangePairingSecret(args ...string) error {
if err := s.requireArgs(args, 1); err != nil {
return err
}
logger.Info("change pairing secret")
if err := s.kCmdSet.ChangePairingSecret(args[0]); err != nil {
logger.Error("change pairing secret failed", "error", err)
return err
}
return nil
}
func (s *Shell) commandKeycardGenerateKey(args ...string) error {
if err := s.requireArgs(args, 0); err != nil {
return err
}
logger.Info("get status before generating key")
appStatus, err := s.kCmdSet.GetStatusApplication()
if err != nil {
logger.Error("get status failed", "error", err)
return err
}
if appStatus.KeyInitialized {
err = errors.New("key already generated. you must delete it before creating a new one")
logger.Error("generate key failed", "error", err)
return err
}
logger.Info("generate key")
keyUID, err := s.kCmdSet.GenerateKey()
if err != nil {
return err
}
s.write(fmt.Sprintf("KEY UID %x\n\n", keyUID))
return nil
}
func (s *Shell) commandKeycardRemoveKey(args ...string) error {
if err := s.requireArgs(args, 0); err != nil {
return err
}
logger.Info("remove key")
err := s.kCmdSet.RemoveKey()
if err != nil {
return err
}
s.write(fmt.Sprintf("KEY REMOVED \n\n"))
return nil
}
func (s *Shell) commandKeycardDeriveKey(args ...string) error {
if err := s.requireArgs(args, 1); err != nil {
return err
}
logger.Info(fmt.Sprintf("derive key %s", args[0]))
if err := s.kCmdSet.DeriveKey(args[0]); err != nil {
logger.Error("derive key failed", "error", err)
return err
}
return nil
}
func (s *Shell) commandKeycardExportKeyPrivate(args ...string) error {
if err := s.requireArgs(args, 1); err != nil {
return err
}
logger.Info(fmt.Sprintf("export key %s", args[0]))
privKey, pubKey, err := s.kCmdSet.ExportKey(true, false, false, args[0])
if err != nil {
logger.Error("export key failed", "error", err)
return err
}
s.write(fmt.Sprintf("EXPORTED PRIVATE KEY\n%x\n", privKey))
s.write(fmt.Sprintf("EXPORTED PUBLIC KEY\n%x\n\n", pubKey))
return nil
}
func (s *Shell) commandKeycardExportKeyPublic(args ...string) error {
if err := s.requireArgs(args, 1); err != nil {
return err
}
logger.Info(fmt.Sprintf("export key %s", args[0]))
privKey, pubKey, err := s.kCmdSet.ExportKey(true, false, true, args[0])
if err != nil {
logger.Error("export key failed", "error", err)
return err
}
s.write(fmt.Sprintf("EXPORTED PRIVATE KEY\n%x\n", privKey))
s.write(fmt.Sprintf("EXPORTED PUBLIC KEY\n%x\n\n", pubKey))
return nil
}
func (s *Shell) commandKeycardSign(args ...string) error {
if err := s.requireArgs(args, 1); err != nil {
return err
}
data, err := s.parseHex(args[0])
if err != nil {
logger.Error("failed parsing hex data", "error", err)
return err
}
logger.Info("sign")
sig, err := s.kCmdSet.Sign(data)
if err != nil {
logger.Error("sign failed", "error", err)
return err
}
s.writeSignatureInfo(sig)
return nil
}
func (s *Shell) commandKeycardSignWithPath(args ...string) error {
if err := s.requireArgs(args, 2); err != nil {
return err
}
data, err := s.parseHex(args[0])
if err != nil {
logger.Error("failed parsing hex data", "error", err)
return err
}
logger.Info("sign with path")
sig, err := s.kCmdSet.SignWithPath(data, args[1])
if err != nil {
logger.Error("sign with path failed", "error", err)
return err
}
s.writeSignatureInfo(sig)
return nil
}
func (s *Shell) commandKeycardSignMessage(args ...string) error {
if len(args) < 1 {
return errors.New("keycard-sign-message require at least 1 parameter")
}
originalMessage := strings.Join(args, " ")
hash := hashEthereumMessage(originalMessage)
logger.Info("sign message")
sig, err := s.kCmdSet.Sign(hash)
if err != nil {
logger.Error("sign message failed", "error", err)
return err
}
s.writeSignatureInfo(sig)
return nil
}
func (s *Shell) commandKeycardSignPinless(args ...string) error {
if err := s.requireArgs(args, 1); err != nil {
return err
}
data, err := s.parseHex(args[0])
if err != nil {
logger.Error("failed parsing hex data", "error", err)
return err
}
logger.Info("sign pinless")
sig, err := s.kCmdSet.SignPinless(data)
if err != nil {
logger.Error("sign pinless failed", "error", err)
return err
}
s.writeSignatureInfo(sig)
return nil
}
func (s *Shell) commandKeycardSignMessagePinless(args ...string) error {
if len(args) < 1 {
return errors.New("keycard-sign-message-pinless require at least 1 parameter")
}
originalMessage := strings.Join(args, " ")
hash := hashEthereumMessage(originalMessage)
logger.Info("sign message pinless")
sig, err := s.kCmdSet.SignPinless(hash)
if err != nil {
logger.Error("sign message pinless failed", "error", err)
return err
}
s.writeSignatureInfo(sig)
return nil
}
func (s *Shell) commandKeycardSetPinlessPath(args ...string) error {
if err := s.requireArgs(args, 1); err != nil {
return err
}
logger.Info(fmt.Sprintf("set pinless path %s", args[0]))
if err := s.kCmdSet.SetPinlessPath(args[0]); err != nil {
logger.Error("set pinless path failed", "error", err)
return err
}
return nil
}
func (s *Shell) commandKeycardGenerateMnemonic(args ...string) error {
if err := s.requireArgs(args, 1); err != nil {
return err
}
checksumSize, err := strconv.ParseInt(args[0], 10, 8)
if err != nil {
logger.Error("failed parsing checksum size", "error", err)
return err
}
logger.Info("generate mnemonic", "checksumSize", checksumSize)
indexes, err := s.kCmdSet.GenerateMnemonic(int(checksumSize))
if err != nil {
logger.Error("generate mnemonic failed", "error", err)
return err
}
s.write(fmt.Sprintf("MNEMONIC INDEXES %v\n\n", indexes))
return nil
}
func (s *Shell) commandKeycardLoadSeed(args ...string) error {
if err := s.requireArgs(args, 1); err != nil {
return err
}
seed, err := s.parseHex(args[0])
if err != nil {
logger.Error("failed parsing seed data", "error", err)
return err
}
logger.Info("loading seed", "seed", fmt.Sprintf("%x", seed))
keyID, err := s.kCmdSet.LoadSeed(seed)
if err != nil {
logger.Error("load seed failed", "error", err)
return err
}
logger.Info(fmt.Sprintf("key ID %x", keyID))
return nil
}
func (s *Shell) commandKeycardIdentify(args ...string) error {
pubkey, err := s.kCmdSet.Identify()
if err != nil {
logger.Error("failed card identification", "error", err)
return err
}
logger.Info(fmt.Sprintf("identification public key: %x", pubkey))
var compareKey []byte
if len(args) == 1 {
compareKey, err = s.parseHex(args[0])
if err != nil {
logger.Error("failed parsing public key", "error", err)
return err
}
} else {
compareKey = pubkey
}
if !bytes.Equal(compareKey, pubkey) {
logger.Error("the recovered key does not match the expected value", "error", err)
return errors.New("genuinity check failed")
}
return nil
}
func (s *Shell) commandCashSelect(args ...string) error {
if err := s.requireArgs(args, 0); err != nil {
return err
}
logger.Info("select cash")
err := s.cashCmdSet.Select()
info := s.cashCmdSet.CashApplicationInfo
s.write(fmt.Sprintf("Installed: %v\n", info.Installed))
s.write(fmt.Sprintf("PublicKey: %x\n", info.PublicKey))
s.write(fmt.Sprintf("PublicData: %x\n", info.PublicData))
s.write(fmt.Sprintf("Version: %x\n\n", info.Version))
if e, ok := err.(*apdu.ErrBadResponse); ok && e.Sw == globalplatform.SwFileNotFound {
logger.Error("select cash failed", "error", err)
return ErrCashNotInstalled
}
return err
}
func (s *Shell) commandCashSign(args ...string) error {
if err := s.requireArgs(args, 1); err != nil {
return err
}
data, err := s.parseHex(args[0])
if err != nil {
logger.Error("failed parsing hex data", "error", err)
return err
}
logger.Info("sign")
sig, err := s.cashCmdSet.Sign(data)
if err != nil {
logger.Error("sign failed", "error", err)
return err
}
s.writeSignatureInfo(sig)
return nil
}
func (s *Shell) requireArgs(args []string, possibleArgsN ...int) error {
for _, n := range possibleArgsN {
if len(args) == n {
return nil
}
}
ns := make([]string, len(possibleArgsN))
for i, n := range possibleArgsN {
ns[i] = fmt.Sprintf("%d", n)
}
return fmt.Errorf("wrong number of argument. got: %d, expected: %v", len(args), strings.Join(ns, " | "))
}
func (s *Shell) evalLine(rawLine string) error {
line := strings.TrimSpace(rawLine)
if len(line) == 0 || strings.HasPrefix(line, "#") {
return nil
}
line, err := s.evalTemplate(line)
if err != nil {
return err
}
reg := regexp.MustCompile("\\s+")
parts := reg.Split(line, -1)
if cmd, ok := s.commands[parts[0]]; ok {
return cmd(parts[1:]...)
}
return fmt.Errorf("command not found: %s", parts[0])
}