-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathsatochip_cli.py
More file actions
3032 lines (2612 loc) · 128 KB
/
satochip_cli.py
File metadata and controls
3032 lines (2612 loc) · 128 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
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
#!/usr/bin/env python3
#
# Copyright (c) 2023 Stephen Rothery - https://github.com/3rdIteration
# Includes code from SeedKeeper, Electrum-Satochip by Toporin
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import traceback
from getpass import getpass
from hashlib import sha256
from os import urandom, environ
import base64
import cbor2 # for cashu
import binascii
import json
import logging
import sys
import time
from typing import Tuple, Dict, List, Any
import click
import websockets
import asyncio
import math
from ecdsa import SECP256k1, ECDH
from mnemonic import Mnemonic
from nostr.event import Event, EventKind
from smartcard.System import readers
from pysatochip.CardConnector import (CardConnector, IncorrectUnlockCodeError, IncorrectUnlockCounterError,
IdentityBlockedError, WrongPinError, CardObjectAlreadyPresentError)
from pysatochip.JCconstants import *
from pysatochip.Satochip2FA import Satochip2FA, SERVER_LIST
from pysatochip.SecretDecryption import Decrypt_Secret
from pysatochip.electrum_mnemonic import Mnemonic as electrum_mnemonic
from pysatochip.electrum_mnemonic import seed_type as electrum_seedtype
from pysatochip.util import list_hyphenated_values, dict_swap_keys_values
# CardConnector Object used by everything
global cc
logging.basicConfig(level=logging.WARNING, format='%(levelname)s [%(module)s] %(funcName)s | %(message)s')
logger = logging.getLogger(__name__)
logger.setLevel(logging.WARNING)
def mnemonic_to_masterseed(bip39_mnemonic, bip39_passphrase, mnemonic_type):
print(mnemonic_type)
mnemonic_masterseed = None
if "BIP39" in mnemonic_type:
mnemonic_obj = Mnemonic("english")
if mnemonic_obj.check(bip39_mnemonic):
mnemonic_masterseed = Mnemonic.to_seed(bip39_mnemonic, bip39_passphrase)
else:
raise Exception("Invalid Mnemonic Checksum (Perhaps an Electrum seed?)")
if "Electrum" in mnemonic_type:
if len(electrum_seedtype(bip39_mnemonic)) > 0:
mnemonic_masterseed = electrum_mnemonic.mnemonic_to_seed(bip39_mnemonic, bip39_passphrase)
else:
raise Exception("Invalid Mnemonic Checksum (Perhaps an BIP39 seed?)")
return mnemonic_masterseed
def mnemonic_to_entropy(bip39_mnemonic, wordlist):
print(f"Worldlist: {wordlist}")
mnemonic_obj = Mnemonic(wordlist)
entropy = mnemonic_obj.to_entropy(bip39_mnemonic)
return entropy # bytearray
def entropy_to_mnemonic(entropy_bytes, wordlist):
print(f"Worldlist: {wordlist}")
mnemonic_obj = Mnemonic(wordlist)
mnemonic = mnemonic_obj.to_mnemonic(entropy_bytes)
return mnemonic # str
def do_challenge_response(msg):
(id_2FA, msg_out) = cc.card_crypt_transaction_2FA(msg, True)
d = {}
d['msg_encrypt'] = msg_out
d['id_2FA'] = id_2FA
logger.info("id_2FA: " + id_2FA)
reply_encrypt = None
hmac = 20 * "00" # bytes.fromhex(20*"00") # default response (reject)
status_msg = ""
for server in SERVER_LIST:
print("Confirm Action on your 2fa device to proceed...")
try:
Satochip2FA.do_challenge_response(d, server_name=server)
# decrypt and parse reply to extract challenge response
reply_encrypt = d['reply_encrypt']
break
except Exception as e:
status_msg += f"\nFailed to contact cosigner! \n=>trying another server\n\n"
print(status_msg)
# self.handler.show_error(f"No response received from '{server}', trying another server")
if reply_encrypt is not None:
reply_decrypt = cc.card_crypt_transaction_2FA(reply_encrypt, False)
logger.info("challenge:response= " + reply_decrypt)
reply_decrypt = reply_decrypt.split(":")
hmac = reply_decrypt[1]
return hmac # return a hexstring
async def broadcast_event_async(event, relay_url):
"""Broadcasts a Nostr event to a relay via websocket"""
logger.debug(f"Event string to publish: {event}")
try:
async with websockets.connect(relay_url) as websocket:
logger.debug(f"Connected to {relay_url}")
await websocket.send(event)
print("Event sent, awaiting response...")
response = await websocket.recv()
print(f"Received response: {response}")
except Exception as e:
logger.warning(f"Error broadcasting event: {e}")
def broadcast_event(event, relay):
"""Synchronous wrapper for broadcast_event_async"""
#loop = asyncio.get_event_loop()./
loop = asyncio.new_event_loop()
loop.run_until_complete(broadcast_event_async(event, relay))
# Accept any prefix of a command name.
#
# from <https://click.palletsprojects.com/en/8.0.x/advanced/?#command-aliases>
class AliasedGroup(click.Group):
def get_command(self, ctx, cmd_name):
rv = click.Group.get_command(self, ctx, cmd_name)
if rv is not None:
return rv
matches = [x for x in self.list_commands(ctx)
if x.startswith(cmd_name)]
if not matches:
return None
elif len(matches) == 1:
return click.Group.get_command(self, ctx, matches[0])
ctx.fail(f"Too many matches: {', '.join(sorted(matches))}")
def resolve_command(self, ctx, args):
# always return the full command name
_, cmd, args = super().resolve_command(ctx, args)
return cmd.name, cmd, args
@click.command(cls=AliasedGroup)
@click.option("--verbose", is_flag=True, help="Provide detailed logs")
@click.option("--devicefilter", default=None, help="Filter only certain devices [satochip, seedkeeper, satodime]")
def main(verbose, devicefilter):
loglevel = logging.WARNING
if verbose:
loglevel = logging.DEBUG
logger.setLevel(loglevel)
logger.debug("In main()")
# Unless devicefilter has been specified, infer it based off the command (if possible)
if not devicefilter:
command_type = sys.argv[1].split("-")[0]
if command_type in ["satochip", "seedkeeper", "satodime", "satocash"]:
devicefilter = command_type
if "util-" not in sys.argv[1][:5]:
global cc
# Connect to the card and get ready for a command
cc = CardConnector(None, loglevel, devicefilter)
time.sleep(1) # give some time to initialize reader...
try:
status = cc.card_get_status()
except Exception as ex:
logger.critical("Card Connect Failed")
exit(ex)
if (cc.needs_secure_channel):
cc.card_initiate_secure_channel()
if status[3]['setup_done'] == False and cc.card_type != "Satodime":
print()
print("WARNING: Card Setup Not Complete, operating with default PIN")
print(" (This state is only useful for Personalisation of PKI)")
print("CARD NOT SAFE TO USE UNTIL SETUP COMPLETE")
print("RUN CARD SETUP UNLESS YOU KNOW EXACTLY WHAT YOU ARE DOING!!!")
print()
cc.set_pin(0, [0x4D, 0x75, 0x73, 0x63, 0x6C, 0x65, 0x30, 0x30]) #Default card PIN
else:
pass
logger.debug("In main() end")
"""##############################
# COMMON FUNCTIONS #
##############################"""
@main.command()
def common_get_card_type():
"""Return detected card type"""
print(cc.card_type)
@main.command()
@click.option("--plain-apdu", default=None, help="APDU to Transmit (List of Bytes)")
def common_transmit(plain_apdu):
"""Transmits a plain APDU"""
print(cc.card_transmit(plain_apdu))
@main.command()
def common_get_card_ATR():
"""Get ATR for Card"""
print(cc.card_get_ATR())
@main.command()
def common_get_card_CPLC():
"""Get CPLC Data for Card"""
print(cc.card_get_CPLC())
@main.command()
def common_get_card_IIN():
"""Get IIN for Card"""
print(cc.card_get_IIN())
@main.command()
def common_get_card_CIN():
"""Get CIN for Card"""
print(cc.card_get_CIN())
@main.command()
def common_get_card_uid_sha1():
"""Get the Serial Number for the Device (Used this as the Subject CN for a personalisation certificate)"""
print(cc.UID_SHA1.lower())
@main.command()
def common_get_card_status():
"""Get a summary of the device status"""
response, sw1, sw2, status_dic = cc.card_get_status()
print(status_dic)
@main.command()
def common_get_card_label():
"""Retrieves the plain text label for the card"""
try:
if cc.card_type != "Satodime":
# get PIN from environment variable or interactively
if 'PYSATOCHIP_PIN' in environ:
pin= environ.get('PYSATOCHIP_PIN')
print("INFO: PIN value recovered from environment variable 'PYSATOCHIP_PIN'")
else:
pin = getpass("Enter your PIN:")
cc.card_verify_PIN(pin)
(response, sw1, sw2, label) = cc.card_get_label()
print("Device Label:", label)
except Exception as e:
print(e)
@main.command()
@click.option("--label", default="", help="Device Label.")
def common_set_card_label(label):
"""Sets a plain text label for the card (Optional)"""
try:
if cc.card_type != "Satodime":
# TODO: for satodime, may fail if performed via NFC (needs ownership)
# get PIN from environment variable or interactively
if 'PYSATOCHIP_PIN' in environ:
pin= environ.get('PYSATOCHIP_PIN')
print("INFO: PIN value recovered from environment variable 'PYSATOCHIP_PIN'")
else:
pin = getpass("Enter your PIN:")
cc.card_verify_PIN(pin)
(response, sw1, sw2) = cc.card_set_label(label)
if sw1 != 0x90 or sw2 != 0x00:
print("ERROR: Set Label Failed")
else:
print("Device Label Updated")
except Exception as e:
print(e)
@main.command()
def common_get_card_ndef():
"""Retrieves the ndef tag for the card"""
try:
if cc.card_type != "Satodime":
# get PIN from environment variable or interactively
if 'PYSATOCHIP_PIN' in environ:
pin= environ.get('PYSATOCHIP_PIN')
print("INFO: PIN value recovered from environment variable 'PYSATOCHIP_PIN'")
else:
pin = getpass("Enter your PIN:")
cc.card_verify_PIN(pin)
(response, sw1, sw2, ndef_bytes) = cc.card_get_ndef()
print("Device ndef:", ndef_bytes.hex())
except Exception as e:
print(e)
@main.command()
@click.option("--ndef", default="", help="Device NDEF in hexadecimal.")
def common_set_card_ndef(ndef):
"""Sets a ndef value for the card (Optional)
For example:
- google.com is 000fD1010B5502676F6F676C652E636F6D
- Android app org.satochip.satodimeapp is 002Ad40f18616e64726f69642e636f6d3a706b676f72672e7361746f636869702e7361746f64696d65617070
"""
try:
if cc.card_type != "Satodime":
# TODO: for satodime, may fail if performed via NFC (needs ownership)
# get PIN from environment variable or interactively
if 'PYSATOCHIP_PIN' in environ:
pin= environ.get('PYSATOCHIP_PIN')
print("INFO: PIN value recovered from environment variable 'PYSATOCHIP_PIN'")
else:
pin = getpass("Enter your PIN:")
cc.card_verify_PIN(pin)
ndef_bytes = bytes.fromhex(ndef)
(response, sw1, sw2) = cc.card_set_ndef(ndef_bytes)
if sw1 != 0x90 or sw2 != 0x00:
print("ERROR: Set ndef Failed with error code: {hex(256*sw1+sw2)}")
else:
print("Device ndef Updated")
except Exception as e:
print(e)
@main.command()
@click.option("--nfc-policy", default=0, help="NFC Policy: 0 = NFC_ENABLED, 1 = NFC_DISABLED, 2 = NFC_BLOCKED")
def common_set_nfc_policy(nfc_policy):
"""Sets the NFC interface policy: enable/disable/block card communication through NFC.
The default policy is 'NFC_ENABLED'. The NFC policy can only be set via the contact (USB) interface.
WARNING: if the policy is set to 2 (NFC_BLOCKED), it can only be reenabled through a factory reset!"""
try:
if (nfc_policy == 2):
if click.confirm("Are you sure that you want to block NFC interface? NFC can only be reenabled with factory reset!", default=False):
# we don't try to recover PIN from environment variables for destructive operations
pin = getpass("Enter your PIN:")
else:
print("Blocking NFC interface cancelled!")
exit()
else:
# get PIN from environment variable or interactively
if 'PYSATOCHIP_PIN' in environ:
pin= environ.get('PYSATOCHIP_PIN')
print("INFO: PIN value recovered from environment variable 'PYSATOCHIP_PIN'")
else:
pin = getpass("Enter your PIN:")
cc.card_verify_PIN(pin)
(response, sw1, sw2) = cc.card_set_nfc_policy(nfc_policy)
if (sw1 == 0x90 and sw2 == 0x00):
print("NFC policy applied successfully!")
elif (sw1 == 0x9C and sw2 == 0x48):
print("Cannot set the NFC policy through the NFC interface, use contact interface instead")
elif (sw1 == 0x9C and sw2 == 0x49):
print("Cannot set the NFC policy: NFC interface is BLOCKED, a factory reset is required to reenable NFC!")
else:
print(f"Failed to set NFC policy with error code: {hex(256*sw1+sw2)}")
except Exception as e:
print(e)
@main.command()
@click.option("--feature-id", default=0, help="Feature ID: 0 = FEATURE_ID_SCHNORR, 1 = FEATURE_ID_NOSTR, 2 = FEATURE_ID_LIQUID")
@click.option("--feature-policy", default=0, help="Feature Policy: 0 = FEATURE_ENABLED, 1 = FEATURE_DISABLED, 2 = FEATURE_BLOCKED")
def common_set_feature_policy(feature_id, feature_policy):
"""Sets the feature usage policy: enable/disable/block the feature with given ID.
WARNING: if the policy is set to 2 (FEATURE_BLOCKED), it can only be reenabled through a factory reset!"""
try:
if (feature_policy == 2):
if click.confirm("Are you sure that you want to block feature? Feature can only be reenabled with factory reset!", default=False):
# we don't try to recover PIN from environment variables for destructive operations
pin = getpass("Enter your PIN:")
else:
print("Blocking feature cancelled!")
exit()
else:
# get PIN from environment variable or interactively
if 'PYSATOCHIP_PIN' in environ:
pin= environ.get('PYSATOCHIP_PIN')
print("INFO: PIN value recovered from environment variable 'PYSATOCHIP_PIN'")
else:
pin = getpass("Enter your PIN:")
cc.card_verify_PIN(pin)
(response, sw1, sw2) = cc.card_set_feature_policy(feature_id, feature_policy)
if (sw1 == 0x90 and sw2 == 0x00):
print("New feature policy applied successfully!")
elif (sw1 == 0x9C and sw2 == 0x4B):
print("Cannot set the feature policy: feature is BLOCKED, a factory reset is required to reenable it!")
else:
print(f"Failed to set feature policy with error code: {hex(256*sw1+sw2)}")
except Exception as e:
print(e)
@main.command()
@click.option("--label", default="", help="Card Label")
def common_initial_setup(label):
"""Run the initial card setup process"""
if cc.card_type == "Satodime":
pin_0 = list("1234".encode('utf8')) # This isn't actually used in Satodime, so can be anything
else:
pin = getpass("Enter your PIN:")
pin2 = getpass("Enter your PIN again to confirm:")
if pin != pin2:
print("ERROR! The two PINs provided do not match! ")
exit()
pin_0 = list(pin.encode('utf8'))
# Just stick with the defaults from SeedKeeper tool
pin_tries_0 = 0x05
ublk_tries_0 = 0x01
# PUK code can be used when PIN is unknown and the card is locked
# We use a random value as the PUK is not used currently and is not user friendly
ublk_0 = list(urandom(16))
pin_tries_1 = 0x01
ublk_tries_1 = 0x01
pin_1 = list(urandom(16)) # the second pin is not used currently
ublk_1 = list(urandom(16))
secmemsize = 32 # 0x0000 # => for satochip - TODO: hardcode value?
memsize = 0x0000 # RFU
create_object_ACL = 0x01 # RFU
create_key_ACL = 0x01 # RFU
create_pin_ACL = 0x01 # RFU
(response, sw1, sw2) = cc.card_setup(pin_tries_0, ublk_tries_0, pin_0, ublk_0, pin_tries_1, ublk_tries_1, pin_1, ublk_1, secmemsize, memsize, create_object_ACL, create_key_ACL, create_pin_ACL, option_flags=0, hmacsha160_key=None, amount_limit=0)
if sw1 != 0x90 or sw2 != 0x00:
if cc.card_type == "Satodime":
print("Error: Claim Satodime Ownership Failed")
else:
print("ERROR: Setup Failed")
exit()
else:
if cc.card_type == "Satodime":
print("Success: Satodime Ownership Claimed")
else:
print("Setup Succeeded")
if cc.card_type == "Satodime":
unlock_counter = response[0:SIZE_UNLOCK_COUNTER]
unlock_secret = response[SIZE_UNLOCK_COUNTER:(SIZE_UNLOCK_COUNTER + SIZE_UNLOCK_SECRET)]
print()
print("Satodime Secrets (Needed to operate via NFC)")
print("Unlock Secret:", bytes(unlock_secret).hex())
print("Unlock Counter:", bytes(unlock_counter).hex())
print()
if len(label) > 0:
common_set_card_label(["--label", label])
"""##############################
# COMMON PIN MGMT #
##############################"""
@main.command()
def common_verify_PIN():
"""Verify that the pin supplied by --pin matches the current device pin"""
try:
pin = getpass("Enter your PIN:")
(response, sw1, sw2) = cc.card_verify_PIN(pin)
if sw1 != 0x90 or sw2 != 0x00:
print("ERROR: Incorrect Pin Supplied")
else:
print("Correct Pin Verified")
except Exception as e:
print(e)
@main.command()
def common_change_PIN():
"""Change the card PIN"""
pin = getpass("Enter your current PIN:")
new_pin = getpass("Enter your new PIN:")
new_pin2 = getpass("Confirm your new PIN:")
if new_pin != new_pin2:
print("ERROR! The two new PINs provided do not match!")
exit()
pin = list(pin.encode('utf8'))
new_pin = list(new_pin.encode('utf8'))
response, sw1, sw2 = cc.card_change_PIN(0, pin, new_pin)
if sw1 == 0x90 and sw2 == 0x00:
print("Success: Pin Changed")
if sw1 == 0x63:
print("Failed: Incorrect PIN")
"""##############################
# COMMON PKI #
##############################"""
@main.command()
def common_export_perso_pubkey():
"""Export the personalisation pubkey from the device"""
try:
# PIN required except for satodime
if cc.card_type != "Satodime":
# get PIN from environment variable or interactively
if 'PYSATOCHIP_PIN' in environ:
pin= environ.get('PYSATOCHIP_PIN')
print("INFO: PIN value recovered from environment variable 'PYSATOCHIP_PIN'")
else:
pin = getpass("Enter your PIN:")
cc.card_verify_PIN(pin)
print(binascii.hexlify(bytearray(cc.card_export_perso_pubkey())).decode())
except Exception as e:
print(e)
@main.command()
@click.option("--cert", default=None, help="The device certificate (base64 encoded)")
@click.option("--cert-file", default=None, help="The device certificate file (base64 encoded)")
def common_import_perso_certificate(cert, cert_file):
"""Import a personalisation certificate into the device"""
if cert_file:
with open(cert_file, 'r', encoding='utf-8') as f:
cert = f.read()
cert = cert.replace("-----BEGIN CERTIFICATE-----", "").replace("-----END CERTIFICATE-----", "")
# TODO: can only import certificate before setup is done
# no user pin required
cc.card_import_perso_certificate(cert)
@main.command()
def common_export_perso_certificate():
"""Export the personalisation certificate that is on the device"""
if cc.card_get_status()[3]['setup_done'] == False:
print("Unable to perform this function until setup is complete")
return
try:
# PIN required except for satodime
if cc.card_type != "Satodime":
# get PIN from environment variable or interactively
if 'PYSATOCHIP_PIN' in environ:
pin= environ.get('PYSATOCHIP_PIN')
print("INFO: PIN value recovered from environment variable 'PYSATOCHIP_PIN'")
else:
pin = getpass("Enter your PIN:")
cc.card_verify_PIN(pin)
print(cc.card_export_perso_certificate())
except Exception as e:
print(e)
@main.command()
@click.option("--privkey", default=None, help="The device NDEF authentikey to import (hex encoded)")
def common_import_ndef_authentikey(privkey):
"""Import the NDEF authentikey privkey on the card."""
try:
print(f"cardtype: {cc.card_type}")
# PIN required except for satodime
if cc.card_type != "Satodime":
# get PIN from environment variable or interactively
if 'PYSATOCHIP_PIN' in environ:
pin= environ.get('PYSATOCHIP_PIN')
print("INFO: PIN value recovered from environment variable 'PYSATOCHIP_PIN'")
else:
pin = getpass("Enter your PIN:")
cc.card_verify_PIN(pin)
privkey_bytes = bytes.fromhex(privkey)
response, sw1, sw2 = cc.card_import_ndef_authentikey(privkey_bytes)
print(f"response: {hex(sw1*256+sw2)}")
except Exception as e:
print(e)
@main.command()
def common_verify_authenticity():
if cc.card_get_status()[3]['setup_done'] == False:
print("Unable to perform this function until setup is complete")
return
"""Verify the authenticy of the currently connected card"""
try:
# PIN required except for satodime
if cc.card_type != "Satodime":
# get PIN from environment variable or interactively
if 'PYSATOCHIP_PIN' in environ:
pin= environ.get('PYSATOCHIP_PIN')
print("INFO: PIN value recovered from environment variable 'PYSATOCHIP_PIN'")
else:
pin = getpass("Enter your PIN:")
cc.card_verify_PIN(pin)
is_authentic, txt_ca, txt_subca, txt_device, txt_error = cc.card_verify_authenticity()
print("Card is authentic:", is_authentic)
print("CA Cert:", txt_ca)
print("SubCA Cert:", txt_subca)
print("Device Cert:", txt_device)
print("Error:", txt_error)
except Exception as e:
print(e)
"""##############################
# SATOCHIP IMPORTS #
##############################"""
@main.command()
@click.option("--use-passphrase", is_flag=True, help="Use a BIP39 Passphrase")
def satochip_import_new_mnemonic(use_passphrase):
"""Generates and imports a new BIP39 mnemonic to the SatoChip Device"""
if click.confirm("WARNING: This tool should only be used to generate a new seed if run in a secure, offline environment. (Like TAILS Linux) \nAre you sure that you want to do this?", default=False):
passphrase = ""
if use_passphrase:
passphrase = input("Enter your passphrase:")
mnemo = Mnemonic("english")
words = mnemo.generate(strength=256)
seed = mnemo.to_seed(words, passphrase=passphrase)
print("Mnemonic Words:", words)
print("BIP39 Passphrase you entered:", passphrase)
print("Be sure to note these words down...")
if click.confirm(
"WARNING: These seed words are your wallet, back them up in a secure, offline place and don't share them with anyone. \nConfirm when you have written them down",
default=False):
try:
# get PIN from environment variable or interactively
if 'PYSATOCHIP_PIN' in environ:
pin= environ.get('PYSATOCHIP_PIN')
print("INFO: PIN value recovered from environment variable 'PYSATOCHIP_PIN'")
else:
pin = getpass("Enter your PIN:")
cc.card_verify_PIN(pin)
cc.card_bip32_import_seed(seed)
print("Seed Successfully Imported")
except Exception as e:
print(e)
@main.command()
def satochip_import_unencrypted_masterseed():
"""Imports a BIP39 Seed (In Hexidecimal Format) to the SatoChip Device"""
try:
# get PIN from environment variable or interactively
if 'PYSATOCHIP_PIN' in environ:
pin= environ.get('PYSATOCHIP_PIN')
print("INFO: PIN value recovered from environment variable 'PYSATOCHIP_PIN'")
else:
pin = getpass("Enter your PIN:")
cc.card_verify_PIN(pin)
seed = input("Enter your BIP39 Seed hex (Masterseed):")
cc.card_bip32_import_seed(seed)
print("Seed Successfully Imported")
except Exception as e:
print(e)
@main.command()
@click.option("--use-passphrase", is_flag=True, help="Use a BIP39 Passphrase")
@click.option("--electrum", is_flag=True, help="Treat the seed as an Electrum Type seed (As opposed to BIP39)")
def satochip_import_unencrypted_mnemonic(use_passphrase, electrum):
"""Imports a mnemonic Seed (In Electrum or BIP39 Format) to the SatoChip Device"""
try:
# get PIN from environment variable or interactively
if 'PYSATOCHIP_PIN' in environ:
pin= environ.get('PYSATOCHIP_PIN')
print("INFO: PIN value recovered from environment variable 'PYSATOCHIP_PIN'")
else:
pin = getpass("Enter your PIN:")
cc.card_verify_PIN(pin)
mnemonic_type = "BIP39"
if electrum:
mnemonic_type = "Electrum"
mnemonic = input("Enter your mnemonic seed:")
passphrase = ""
if use_passphrase:
passphrase = input("Enter your passphrase:")
seed = mnemonic_to_masterseed(mnemonic, passphrase, mnemonic_type)
cc.card_bip32_import_seed(seed)
print("Seed Successfully Imported")
except Exception as e:
print(e)
@main.command()
@click.option("--json-file", required=True, help="A file containing the encrypted JSON Masterseed (Returned by seedkeeper_export_secret())")
def satochip_import_encrypted_masterseed(json_file):
"""Imports an encrypted seed backup. (The type typically exported from a SeedKeeper device)"""
try:
f = open(json_file)
secret_json = json.load(f)
# get PIN from environment variable or interactively
if 'PYSATOCHIP_PIN' in environ:
pin= environ.get('PYSATOCHIP_PIN')
print("INFO: PIN value recovered from environment variable 'PYSATOCHIP_PIN'")
else:
pin = getpass("Enter your PIN:")
cc.card_verify_PIN(pin)
cc.card_import_encrypted_secret(secret_json['secrets'][0])
print("Success: Masterseed Imported")
except Exception as e:
print(e)
@main.command()
@click.option("--json-file", required=True, help="A file containing the encrypted JSON 2FA key (Returned by seedkeeper_export_secret())")
def satochip_import_encrypted_2fa_key(json_file):
"""Imports an encrypted seed backup. (The type typically exported from a SeedKeeper device)"""
if click.confirm("WARNING: This will import AND enable 2FA on your Satochip device using the key provided. \nAre you sure that you want to do this?", default=False):
try:
f = open(json_file)
secret_json = json.load(f)
# get PIN from environment variable or interactively
if 'PYSATOCHIP_PIN' in environ:
pin= environ.get('PYSATOCHIP_PIN')
print("INFO: PIN value recovered from environment variable 'PYSATOCHIP_PIN'")
else:
pin = getpass("Enter your PIN:")
cc.card_verify_PIN(pin)
cc.card_import_encrypted_secret(secret_json['secrets'][0])
print("Success: 2FA Key Imported and Enabled")
except Exception as e:
print(e)
@main.command()
@click.option("--pubkey", required=True, help="the pubkey in uncompressed form (65 bytes) as a hex_string or bytes or list of int")
def satochip_import_trusted_pubkey(pubkey):
"""Imports a trusted pubkey"""
try:
# get PIN from environment variable or interactively
if 'PYSATOCHIP_PIN' in environ:
pin= environ.get('PYSATOCHIP_PIN')
print("INFO: PIN value recovered from environment variable 'PYSATOCHIP_PIN'")
else:
pin = getpass("Enter your PIN:")
cc.card_verify_PIN(pin)
pubkey_hex = cc.card_import_trusted_pubkey(pubkey)
print(f"Successfully imported trusted_pubkey: {pubkey_hex}")
except Exception as e:
print(e)
@main.command()
def satochip_export_trusted_pubkey():
"""Exports the current trusted pubkey"""
try:
# get PIN from environment variable or interactively
if 'PYSATOCHIP_PIN' in environ:
pin= environ.get('PYSATOCHIP_PIN')
print("INFO: PIN value recovered from environment variable 'PYSATOCHIP_PIN'")
else:
pin = getpass("Enter your PIN:")
cc.card_verify_PIN(pin)
print(cc.card_export_trusted_pubkey())
except Exception as e:
print(e)
@main.command()
def common_export_authentikey():
"""Exports the device Authentikey"""
try:
# get PIN from environment variable or interactively
if 'PYSATOCHIP_PIN' in environ:
pin= environ.get('PYSATOCHIP_PIN')
print("INFO: PIN value recovered from environment variable 'PYSATOCHIP_PIN'")
else:
pin = getpass("Enter your PIN:")
cc.card_verify_PIN(pin)
print(cc.card_export_authentikey().get_public_key_hex(False))
except Exception as e:
print(e)
@main.command()
def satochip_reset_seed():
"""Wipes the seed that is currently on the device."""
if click.confirm("Are you sure that you want to wipe the device seed? (This will cause an UNRECOVERABLE LOSS OF FUNDS if you don't have a working backup", default=False):
try:
# we don't try to recover PIN from environment variables for destructive operations
pin = getpass("Enter your PIN:")
cc.card_verify_PIN(pin)
if cc.needs_2FA:
cc.card_bip32_get_authentikey()
authentikeyx = bytearray(cc.parser.authentikey_coordx).hex()
msg = {'action': "reset_seed", 'authentikeyx': authentikeyx}
msg = json.dumps(msg)
hmac = do_challenge_response(msg)
# send request
(response, sw1, sw2) = cc.card_reset_seed(cc.pin, hmac)
else:
(response, sw1, sw2) = cc.card_reset_seed(cc.pin)
if (sw1 == 0x90 and sw2 == 0x00):
print("Seed reset successfully!\nYou can now load a new seed")
else:
print(f"Failed to reset seed with error code: {hex(256*sw1+sw2)}")
except Exception as e:
print(e)
@main.command()
def satochip_bip32_get_authentikey():
"""Export the BIP32 Authentikey"""
try:
# get PIN from environment variable or interactively
if 'PYSATOCHIP_PIN' in environ:
pin= environ.get('PYSATOCHIP_PIN')
print("INFO: PIN value recovered from environment variable 'PYSATOCHIP_PIN'")
else:
pin = getpass("Enter your PIN:")
cc.card_verify_PIN(pin)
print(cc.card_bip32_get_authentikey().get_public_key_hex(False))
except Exception as e:
print(e)
@main.command()
@click.option("--path", default="m/44'/0'/0'/0", help="path (str | bytes): the BIP32 path; if given as a string, it will be converted to bytes (4 bytes for each path index)")
def satochip_bip32_get_extendedkey(path):
"""Get extended pubkey and chaincode for a given derivation path (m/44'/0'/0'/0 by default)"""
try:
# get PIN from environment variable or interactively
if 'PYSATOCHIP_PIN' in environ:
pin= environ.get('PYSATOCHIP_PIN')
print("INFO: PIN value recovered from environment variable 'PYSATOCHIP_PIN'")
else:
pin = getpass("Enter your PIN:")
cc.card_verify_PIN(pin)
(key, chaincode) = cc.card_bip32_get_extendedkey(path)
print("Key: ", key.get_public_key_hex(True))
print("Chaincode: ", chaincode.hex())
except Exception as e:
print(e)
@main.command()
@click.option("--path", default="m/44'/0'/0'/0", help="The BIP32 path to retrieve the xpub for")
@click.option("--xtype", default="standard", help="xtype (str): the type of transaction such as 'standard', 'p2wpkh-p2sh', 'p2wpkh', 'p2wsh-p2sh', 'p2wsh'")
@click.option("--is-mainnet", default=True, help="is_mainnet (bool): is mainnet or testnet")
def satochip_bip32_get_xpub(path, xtype, is_mainnet):
"""Get extended public key (xpub) for a given derivation path (m/44'/0'/0'/0 by default) and script type (p2pkh by default)"""
try:
# get PIN from environment variable or interactively
if 'PYSATOCHIP_PIN' in environ:
pin= environ.get('PYSATOCHIP_PIN')
print("INFO: PIN value recovered from environment variable 'PYSATOCHIP_PIN'")
else:
pin = getpass("Enter your PIN:")
cc.card_verify_PIN(pin)
print(cc.card_bip32_get_xpub(path, xtype, is_mainnet))
except Exception as e:
print(e)
@main.command()
def satochip_bip32_get_liquid_master_blinding_key():
"""Get the Liquid-Bitcoin Master Blinding Key. This is required on the host side to unblind output amounts in Liquid-Bitcoin confidential transactions"""
try:
# get PIN from environment variable or interactively
if 'PYSATOCHIP_PIN' in environ:
pin= environ.get('PYSATOCHIP_PIN')
print("INFO: PIN value recovered from environment variable 'PYSATOCHIP_PIN'")
else:
pin = getpass("Enter your PIN:")
cc.card_verify_PIN(pin)
master_blinding_key = bytes(cc.card_bip32_get_liquid_master_blinding_key())
print(f"Liquid-Bitcoin Master Blinding Key: {master_blinding_key.hex()}")
except Exception as e:
print(e)
"""##############################
# SATOCHIP PRIVKEY #
##############################"""
@main.command()
@click.option("--keyslot", required=True, help="the keyslot where the key should be imported (0-16)")
@click.option("--privkey", required=True, help="the 32byte private key in hex format")
def satochip_import_privkey(keyslot, privkey):
"""Imports a given private ECkey into the card at given keyslot
The keyslot provided should be available.
The private key should be in hex format (exactly 64 hex chars)
"""
try:
keyslot = int(keyslot)
# convert privkey hex to bytes
privkey_bytes = bytes.fromhex(privkey)
# get PIN from environment variable or interactively
if 'PYSATOCHIP_PIN' in environ:
pin= environ.get('PYSATOCHIP_PIN')
print("INFO: PIN value recovered from environment variable 'PYSATOCHIP_PIN'")
else:
pin = getpass("Enter your PIN:")
cc.card_verify_PIN(pin)
# check if 2FA is required
if (cc.needs_2FA==None):
(response, sw1, sw2, d) = cc.card_get_status()
if cc.needs_2FA:
raise ValueError("Required 2FA not supported currently!")
# import private key
cc.satochip_import_privkey(keyslot, privkey_bytes)
print(f"Private key imported successfully!")
except Exception as ex:
print(f"Exception during private key import: {ex}")
@main.command()
@click.option("--keyslot", required=True, help="the keyslot where the key should be imported (0-16)")
def satochip_reset_privkey(keyslot):
"""Reset the private ECkey at given keyslot"""
try:
keyslot = int(keyslot)
# get PIN from environment variable or interactively
if 'PYSATOCHIP_PIN' in environ:
pin= environ.get('PYSATOCHIP_PIN')
print("INFO: PIN value recovered from environment variable 'PYSATOCHIP_PIN'")
else:
pin = getpass("Enter your PIN:")
cc.card_verify_PIN(pin)
# check if 2FA is required
hmac=b''
if (cc.needs_2FA==None):
(response, sw1, sw2, d) = cc.card_get_status()
if cc.needs_2FA:
raise ValueError("Required 2FA not supported currently!")
# reset private key
cc.satochip_reset_privkey(keyslot)
print(f"Private key reset successfully!")
except Exception as ex:
print(f"Exception during private key import: {ex}")
@main.command()
@click.option("--keyslot", required=True, help="the keyslot where the key should be imported (0-16)")
def satochip_get_pubkey_from_keyslot(keyslot):
"""return the public key associated with a particular private key stored
at a given keyslot.
"""
try:
keyslot = int(keyslot)
# get PIN from environment variable or interactively
if 'PYSATOCHIP_PIN' in environ:
pin= environ.get('PYSATOCHIP_PIN')
print("INFO: PIN value recovered from environment variable 'PYSATOCHIP_PIN'")
else:
pin = getpass("Enter your PIN:")
cc.card_verify_PIN(pin)
# check if 2FA is required
hmac=b''
if (cc.needs_2FA==None):
(response, sw1, sw2, d) = cc.card_get_status()
if cc.needs_2FA:
raise ValueError("Required 2FA not supported currently!")
# export pubkey
pubkey = cc.satochip_get_pubkey_from_keyslot(keyslot)
print(f"pubkey for slot {keyslot}: {pubkey.get_public_key_bytes(compressed=False).hex()}")
print(f"pubkey for slot {keyslot}: {pubkey.get_public_key_bytes(compressed=True).hex()}")
except Exception as ex:
print(f"Exception during private key import: {ex}")
"""##############################
# SATOCHIP SIGNATURE #
##############################"""
@main.command()
@click.option("--keyslot", default="255", help="keyslot of the private key (for single-key wallet")
@click.option("--path", default="m/44'/0'/0'/0/0", help="path: the full BIP32 path of the address")
@click.option("--hash", required=True, help="The hash to sign as hex string")
def satochip_sign_hash(hash: str, keyslot, path):
"""Sign a hash with the Satochip"""
hash_bytes = bytes.fromhex(hash)
hash_list = list(hash_bytes)
try:
# get PIN from environment variable or interactively
if 'PYSATOCHIP_PIN' in environ:
pin= environ.get('PYSATOCHIP_PIN')
print("INFO: PIN value recovered from environment variable 'PYSATOCHIP_PIN'")
else:
pin = getpass("Enter your PIN:")