-
Notifications
You must be signed in to change notification settings - Fork 10
/
keygen.py
1690 lines (1529 loc) · 62 KB
/
keygen.py
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
from upydevice import Device
import sys
from upydev.fileio import BleFileIO, SerialFileIO, WebSocketFileIO
from upydevice import check_device_type
from upydev.devicemanagement import check_zt_group
import getpass
import os
import json
import upydev
from binascii import hexlify
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa, padding, ec # next: ed25519
from cryptography.hazmat.primitives import serialization
from cryptography import x509
from cryptography.x509.oid import NameOID
from cryptography.hazmat.primitives import hashes
from cryptography.exceptions import InvalidSignature
import string
import secrets
import hashlib
import netifaces
import socket
import locale
from datetime import datetime, timedelta
import ipaddress
import argparse
import shlex
import tempfile
rawfmt = argparse.RawTextHelpFormatter
CHECK = "[\033[92m\u2714\x1b[0m]"
XF = "[\u001b[31;1m\u2718\u001b[0m]"
dict_arg_options = {
"kg": [
"t",
"zt",
"p",
"wss",
"f",
"rkey",
"tfkey",
"key_size",
"show_key",
"g",
"to",
"fre",
"a",
],
"rsa": ["t", "zt", "p", "wss", "fre", "f"],
}
KG = dict(
help="to generate a key pair (RSA) or key & certificate (ECDSA) for ssl",
desc="generate key pair and exchange with device, or refresh WebREPL " "password",
mode=dict(
help="indicate a key {rsa, ssl, wr}",
metavar="mode",
choices=["rsa", "ssl", "wr"],
nargs="?",
),
subcmd=dict(
help="- gen: generate a ECDSA key/cert (default)"
"\n- rotate: To rotate CA key/cert pair old->new or"
" new->old"
"\n- add: add a device cert to upydev path verify location."
"\n- export: export CA or device cert to cwd."
"\n- status: check datetime certificate validity.",
metavar="subcmd",
choices=["gen", "add", "export", "rotate", "status"],
default="gen",
nargs="?",
),
dst=dict(
help="indicate a subject: {dev, host, CA}, default: dev",
metavar="dest",
choices=["dev", "host", "CA"],
default="dev",
nargs="?",
),
options={
"-t": dict(help="device target address", required=True),
"-p": dict(help="device password or baudrate", required=True),
"-wss": dict(
help="use WebSocket Secure",
required=False,
default=False,
action="store_true",
),
"-zt": dict(
help="internal flag for zerotierone device",
required=False,
default=False,
action="store_true",
),
"-rst": dict(
help="internal flag for reset",
required=False,
default=False,
action="store_true",
),
"-key_size": dict(
help="RSA key size, default:2048", default=2048, required=False, type=int
),
"-show_key": dict(
help="show generated RSA key",
required=False,
default=False,
action="store_true",
),
"-tfkey": dict(
help="transfer keys to device",
required=False,
default=False,
action="store_true",
),
"-rkey": dict(
help="option to remove private device key from host",
required=False,
default=False,
action="store_true",
),
"-g": dict(
help="option to store new WebREPL password globally",
required=False,
default=False,
action="store_true",
),
"-to": dict(help="serial device name to upload to", required=False),
"-f": dict(
help="cert name to add to verify locations", required=False, nargs="*"
),
"-a": dict(
help="show all devs ssl cert status",
required=False,
default=False,
action="store_true",
),
},
)
RSA = dict(
help="to perform operations with RSA key pair as sign, verify or " "authenticate",
desc="sign files, verify signatures or authenticate devices with "
"RSA challenge\nusing device keys or host keys",
mode=dict(
help="indicate an action {sign, verify, auth}",
metavar="mode",
choices=["sign", "verify", "auth"],
),
subcmd=dict(
help="indicate a file to sign/verify", metavar="file/signature", nargs="?"
),
options={
"-t": dict(help="device target address", required=True),
"-p": dict(help="device password or baudrate", required=True),
"-wss": dict(
help="use WebSocket Secure",
required=False,
default=False,
action="store_true",
),
"-host": dict(
help="to use host keys", required=False, default=False, action="store_true"
),
"-rst": dict(
help="internal flag for reset",
required=False,
default=False,
action="store_true",
),
},
)
KG_CMD_DICT_PARSER = {"kg": KG, "rsa": RSA}
usag = """%(prog)s command [options]\n
"""
_help_subcmds = "%(prog)s [command] -h to see further help of any command"
parser = argparse.ArgumentParser(
prog="upydev",
description=("keygen/cryptography tools" + "\n\n" + _help_subcmds),
formatter_class=rawfmt,
usage=usag,
prefix_chars="-",
)
subparser_cmd = parser.add_subparsers(
title="commands",
prog="",
dest="m",
)
for command, subcmd in KG_CMD_DICT_PARSER.items():
if "desc" in subcmd.keys():
_desc = f"{subcmd['help']}\n\n{subcmd['desc']}"
else:
_desc = subcmd["help"]
_subparser = subparser_cmd.add_parser(
command, help=subcmd["help"], description=_desc, formatter_class=rawfmt
)
for pos_arg in subcmd.keys():
if pos_arg not in ["subcmd", "help", "desc", "options", "alt_ops"]:
_subparser.add_argument(pos_arg, **subcmd[pos_arg])
if subcmd["subcmd"]:
_subparser.add_argument("subcmd", **subcmd["subcmd"])
for option, op_kargs in subcmd["options"].items():
_subparser.add_argument(option, f"-{option}", **op_kargs)
def parseap(command_args):
try:
return parser.parse_known_args(command_args)
except SystemExit: # argparse throws these because it assumes you only want
# to do the command line
return None # should be a default one
def sh_cmd(cmd_inp):
# parse args
command_line = shlex.split(cmd_inp)
all_args = parseap(command_line)
if not all_args:
return
else:
args, unknown_args = all_args
return args, unknown_args
def filter_bool_opt(k, v):
if v and isinstance(v, bool):
return f"{k}"
else:
return ""
def expand_margs(v):
if isinstance(v, list):
return " ".join([str(val) for val in v])
else:
return v
UPYDEV_PATH = upydev.__path__[0]
CHECK = "[\033[92m\u2714\x1b[0m]"
XF = "[\u001b[31;1m\u2718\u001b[0m]"
OK = "\033[92mOK\x1b[0m"
FAIL = "\u001b[31;1mF\u001b[0m"
KEYGEN_HELP = """
> KEYGEN: Usage '$ upydev ACTION [opts]'
ACTIONS:
- gen_rsakey: To generate RSA-2048 bit key pair that will be shared with the device
(it is unique for each device) use -tfkey to send this key to the
device (use only if connected directly to the AP of the device or a
"secure" wifi e.g. local/home). If not connected to a "secure" wifi
upload the key (it is stored in upydev.__path__) by USB/Serial connection.
*Use -rkey option to remove private key from host (only store public key).
To generate a host key pair use 'kg rsa host'. Then the public key will be sent
to the device so it can verify or authenticate the host signature.
- rsa_sign: To sign a file with device RSA key, (rsa lib required), use -f to indicate
the file to sign or use alias form: $ upydev rsa sign [FILE]
* To sign a file with host RSA key: $ upydev rsa sign host [FILE]
- rsa_verify: To verify a signature of a file made with device RSA key, use -f to indicate
the signature file to verify or use alias form: $ upydev rsa verify [FILE]
* To verify in device a signature made with host RSA key: $ upydev rsa verify host [FILE]
- rsa_auth: To authenticate a device with RSA encrypted challenge (Public Keys exchange must be done first)
- rf_wrkey: To "refresh" the WebREPL password with a new random password derivated from
the RSA key previously generated. A token then is sent to the device to generate
the same password from the RSA key previously uploaded. This won't leave
any clues in the TCP Websocekts packages of the current WebREPL password.
(Only the token will be visible; check this using wireshark)
(This needs upysecrets.py)
- sslgen_key: To generate ECDSA key and a self-signed certificate to enable SSL sockets
This needs a passphrase, that will be required every time the key is loaded.
Use -tfkey to upload this key to the device
(use only if connected directly to the AP of the device or a
"secure" wifi e.g. local/home). If not connected to a "secure" wifi
upload the key (it is stored in upydev.__path__) by USB/Serial connection.
Use -to [serial devname] flag with -tfkey to transfer keys by USB/Serial
"""
# CRYPTO
def rsa_keygen(args, dir="", store=True, show_key=False, id="00", host=False):
private_key = rsa.generate_private_key(
public_exponent=65537, key_size=args.key_size, backend=default_backend()
)
# my_p = getpass.getpass(prompt='Password: ', stream=None)
# pem = private_key.private_bytes(encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8,
# encryption_algorithm=serialization.BestAvailableEncryption(bytes(my_p, 'utf-8')))
key_ser = serialization.NoEncryption()
if host:
my_p = getpass.getpass(prompt="Password: ", stream=None)
# print(my_p)
key_ser = serialization.BestAvailableEncryption(bytes(my_p, "utf-8"))
pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=key_ser,
)
public_key = private_key.public_key()
pub_pem = public_key.public_bytes(
encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.PKCS1
)
if show_key:
print(pem)
if store:
pv_key = f"upy_pv_rsa{id}.key"
pb_key = f"upy_pub_rsa{id}.key"
if host:
pv_key = f"upy_host_pv_rsa{id}.key"
pb_key = f"upy_host_pub_rsa{id}.key"
# private key
keypv_path_file = os.path.join(dir, pv_key)
with open(keypv_path_file, "wb") as keyfile:
keyfile.write(pem)
# public key
keypb_path_file = os.path.join(dir, pb_key)
with open(keypb_path_file, "wb") as keyfile:
keyfile.write(pub_pem)
return pem # , my_p
def load_rsa_key(dir="", show_key=False, id="00"):
buff_key = b""
rsa_key_abs = os.path.join(dir, "upy_pub_rsa{}.key".format(id))
try:
with open(rsa_key_abs, "rb") as keyfile:
while True:
try:
buff = keyfile.read(2000)
if buff != b"":
buff_key += buff
else:
break
except Exception as e:
print(e)
if show_key:
print(buff_key)
return buff_key
except Exception as e:
print(
"No RSA key found for this device, generate one first with '$ upydev gen_rsakey -tfkey' "
)
def load_rsa_pvkey(dir="", show_key=False, id="00"):
buff_key = b""
rsa_key_abs = os.path.join(dir, "upy_pv_rsa{}.key".format(id))
try:
with open(rsa_key_abs, "rb") as keyfile:
while True:
try:
buff = keyfile.read(2000)
if buff != b"":
buff_key += buff
else:
break
except Exception as e:
print(e)
if show_key:
print(buff_key)
return buff_key
except Exception as e:
print(
"No RSA key found for this device, generate one first with '$ upydev gen_rsakey -tfkey' "
)
def upy_keygen(rsa_key):
aZ09 = bytes(string.ascii_letters + string.digits, "ascii")
raw_key_list = [line for line in rsa_key.splitlines()[1:-1]]
raw_key = b""
for line in raw_key_list:
raw_key += line
random_token = secrets.token_bytes(32) # send this
for b in random_token:
raw_key += bytes(chr(raw_key[b]), "utf-8")
key_hash = hashlib.sha256()
key_hash.update(raw_key)
hashed_key = key_hash.digest()
index_key = [secrets.randbelow(len(hashed_key)) for i in range(8)] # send this
password_long = bytes([hashed_key[val] for val in index_key])
password_short = bytes([aZ09[val % len(aZ09)] for val in password_long]).decode()
return (password_short, random_token + bytes(index_key))
def get_cert_data():
# MAC ADDRESS IF
try:
try:
ip_soc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ip_soc.connect(("8.8.8.8", 1))
local_ip = ip_soc.getsockname()[0]
ip_soc.close()
addrs = local_ip
except Exception as e:
addrs = [
netifaces.ifaddresses(iface)[netifaces.AF_INET][0]["addr"]
for iface in netifaces.interfaces()
if netifaces.AF_INET in netifaces.ifaddresses(iface)
][-1]
USER = os.environ["USER"]
HOST_NAME = socket.gethostname()
COUNTRY_CODE = locale.getlocale()[0].split("_")[1]
return {
"addrs": addrs,
"USER": USER,
"HOST_NAME": HOST_NAME,
"COUNTRY_CODE": COUNTRY_CODE,
}
except Exception as e:
default_temp = {
"addrs": "xxxx",
"USER": "xxxx",
"HOST_NAME": "xxxx",
"COUNTRY_CODE": "XX",
}
return default_temp
def ssl_ECDSA_key_certgen(args, dir="", store=True, dev_name=None):
print("Getting unique id...")
dev = Device(
args.t, args.p, init=True, ssl=args.wss, auth=args.wss, autodetect=True
)
id_bytes = dev.cmd(
"from machine import unique_id; unique_id()", silent=True, rtn_resp=True
)
unique_id = hexlify(id_bytes).decode()
print("ID: {}".format(unique_id))
dev_platform = dev.dev_platform
dev.disconnect()
key = ec.generate_private_key(ec.SECP256R1(), backend=default_backend())
# key = ed25519.Ed25519PrivateKey.generate()
# my_p = getpass.getpass(prompt="Passphrase: ", stream=None)
pem = key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption(),
)
der = key.private_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption(),
)
if store:
new_key_pem = f"SSL_key{unique_id}.pem"
new_key_der = f"SSL_key{unique_id}.der"
# if new_key_pem in os.listdir(dir):
# new_key_pem = f'~{new_key_pem}'
# new_key_der = f'~{new_key_der}'
key_path_file_pem = os.path.join(dir, new_key_pem)
with open(key_path_file_pem, "wb") as keyfile:
keyfile.write(pem)
key_path_file_der = os.path.join(dir, new_key_der)
with open(key_path_file_der, "wb") as keyfile:
keyfile.write(der)
cert_data = get_cert_data()
if dev_name:
cert_data["USER"] = dev_name
cert_data["HOST_NAME"] = args.t
subject = issuer = x509.Name(
[
x509.NameAttribute(NameOID.USER_ID, f"{dev_platform}@{unique_id}"),
x509.NameAttribute(NameOID.SURNAME, cert_data["HOST_NAME"]),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, "MicroPython"),
x509.NameAttribute(NameOID.COMMON_NAME, cert_data["USER"]),
]
)
# host_ip = ipaddress.IPv4Address(cert_data["addrs"])
# if '.local' in args.t:
# args.t = socket.gethostbyname(args.t)
ca_key = key
# host_id = hexlify(os.environ['USER'].encode()).decode()[:10]
key_path_file_pem = os.path.join(UPYDEV_PATH, "ROOT_CA_key.pem")
key_path_rot_file_pem = os.path.join(UPYDEV_PATH, "~ROOT_CA_key.pem")
cert_ca_path_file_pem = os.path.join(UPYDEV_PATH, "ROOT_CA_cert.pem")
with open(cert_ca_path_file_pem, "rb") as rootCA:
root_data = rootCA.read()
ROOT_CA_cert = x509.load_pem_x509_certificate(root_data)
# Use always newest ROOT_CA to sign dev certificates SR
if os.path.exists(key_path_rot_file_pem):
cert_ca_rot_pem = os.path.join(UPYDEV_PATH, "~ROOT_CA_cert.pem")
with open(cert_ca_rot_pem, "rb") as rootCA_rot:
root_data = rootCA_rot.read()
ROOT_CA_cert_rot = x509.load_pem_x509_certificate(root_data)
if ROOT_CA_cert_rot.not_valid_before > ROOT_CA_cert.not_valid_before:
key_path_file_pem = key_path_rot_file_pem
ROOT_CA_cert = ROOT_CA_cert_rot
if os.path.exists(key_path_file_pem):
with open(key_path_file_pem, "rb") as key_file:
while True:
try:
my_p = getpass.getpass(
prompt="Enter passphrase for ROOT CA key :", stream=None
)
# print(my_p)
ca_key = serialization.load_pem_private_key(
key_file.read(), my_p.encode()
)
break
except ValueError:
# print(e)
key_file.seek(0)
print("Passphrase incorrect, try again...")
issuer = ROOT_CA_cert.issuer
if not args.zt:
csr = (
x509.CertificateSigningRequestBuilder()
.subject_name(subject)
.add_extension(
x509.SubjectAlternativeName(
[
x509.DNSName("wss://{}:8833".format(args.t)),
x509.DNSName("wss://192.168.4.1:8833"),
]
),
critical=False,
)
.sign(key, hashes.SHA256(), default_backend())
)
else:
dev_ip = args.zt["dev"]
if ":" in args.t:
args.t, port = args.t.split(":")
else:
port = "8833"
csr = (
x509.CertificateSigningRequestBuilder()
.subject_name(subject)
.add_extension(
x509.SubjectAlternativeName(
[
x509.DNSName(f"wss://{args.t}:{port}"),
x509.DNSName("wss://192.168.4.1:8833"),
x509.DNSName(f"wss://{dev_ip}:8833"),
]
),
critical=False,
)
.sign(key, hashes.SHA256(), default_backend())
)
# SIGN
if not args.zt:
cert = (
x509.CertificateBuilder()
.subject_name(csr.subject)
.issuer_name(issuer)
.public_key(csr.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(datetime.utcnow())
.not_valid_after(datetime.utcnow() + timedelta(days=365))
.add_extension(
x509.SubjectAlternativeName(
[
x509.DNSName(f"wss://{args.t}:8833"),
x509.DNSName("wss://192.168.4.1:8833"),
]
),
critical=False,
)
.sign(ca_key, hashes.SHA256(), default_backend())
)
else:
cert = (
x509.CertificateBuilder()
.subject_name(csr.subject)
.issuer_name(issuer)
.public_key(csr.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(datetime.utcnow())
.not_valid_after(datetime.utcnow() + timedelta(days=365))
.add_extension(
x509.SubjectAlternativeName(
[
x509.DNSName(f"wss://{args.t}:{port}"),
x509.DNSName("wss://192.168.4.1:8833"),
x509.DNSName(f"wss://{dev_ip}:8833"),
]
),
critical=False,
)
.sign(ca_key, hashes.SHA256(), default_backend())
)
# SIGN
if store:
cert_path_file_pem = os.path.join(dir, f"SSL_certificate{unique_id}.pem")
with open(cert_path_file_pem, "wb") as certfile:
certfile.write(cert.public_bytes(serialization.Encoding.PEM))
cert_path_file_der = os.path.join(dir, f"SSL_certificate{unique_id}.der")
with open(cert_path_file_der, "wb") as certfile:
certfile.write(cert.public_bytes(serialization.Encoding.DER))
print(f"Device {unique_id} ECDSA key & certificate generated.")
if args.tfkey:
print("Transfering ECDSA key and certificate to the device...")
ssl_k = key_path_file_der
ssl_c = cert_path_file_der
return {"ACTION": "put", "mode": "SSL", "Files": [ssl_k, ssl_c]}
def ssl_ECDSA_key_certgen_host(args, dir="", store=True):
print("Getting unique id...")
unique_id = hexlify(os.environ["USER"].encode()).decode()[:10]
print("ID HOST: {}".format(unique_id))
dev_platform = sys.platform
key = ec.generate_private_key(ec.SECP256R1(), backend=default_backend())
# key = ed25519.Ed25519PrivateKey.generate()
my_p = getpass.getpass(prompt="Passphrase: ", stream=None)
pem = key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.BestAvailableEncryption(
bytes(my_p, "utf-8")
),
)
# der = key.private_bytes(encoding=serialization.Encoding.DER,
# format=serialization.PrivateFormat.TraditionalOpenSSL,
# encryption_algorithm=serialization.NoEncryption())
if store:
key_path_file_pem = os.path.join(dir, f"HOST_key@{unique_id}.pem")
with open(key_path_file_pem, "wb") as keyfile:
keyfile.write(pem)
# key_path_file_der = os.path.join(dir, f'SSL_key{unique_id}.der')
# with open(key_path_file_der, 'wb') as keyfile:
# keyfile.write(der)
cert_data = get_cert_data()
subject = x509.Name(
[
x509.NameAttribute(NameOID.USER_ID, f"{dev_platform}@{unique_id}"),
x509.NameAttribute(NameOID.SURNAME, "{}".format(cert_data["HOST_NAME"])),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, "MicroPython"),
x509.NameAttribute(NameOID.COMMON_NAME, cert_data["USER"]),
]
)
host_ip = ipaddress.IPv4Address(cert_data["addrs"])
# if '.local' in args.t:
# args.t = socket.gethostbyname(args.t)
key_path_file_pem = os.path.join(UPYDEV_PATH, "ROOT_CA_key.pem")
if os.path.exists(key_path_file_pem):
pass
with open(key_path_file_pem, "rb") as key_file:
while True:
try:
my_p = getpass.getpass(
prompt="Enter passphrase for ROOT CA key :", stream=None
)
# print(my_p)
ca_key = serialization.load_pem_private_key(
key_file.read(), my_p.encode()
)
break
except ValueError:
# print(e)
key_file.seek(0)
print("Passphrase incorrect, try again...")
cert_ca_path_file_pem = os.path.join(UPYDEV_PATH, "ROOT_CA_cert.pem")
with open(cert_ca_path_file_pem, "rb") as rootCA:
root_data = rootCA.read()
ROOT_CA_cert = x509.load_pem_x509_certificate(root_data)
issuer = ROOT_CA_cert.issuer
subject = issuer # allocate less RAM in device?
if not args.zt:
csr = (
x509.CertificateSigningRequestBuilder()
.subject_name(subject)
.add_extension(
x509.SubjectAlternativeName(
[
x509.DNSName("localhost"),
x509.IPAddress(host_ip),
]
),
critical=False,
)
.sign(key, hashes.SHA256(), default_backend())
)
else:
if ":" in args.t:
args.t, port = args.t.split(":")
csr = (
x509.CertificateSigningRequestBuilder()
.subject_name(subject)
.add_extension(
x509.SubjectAlternativeName(
[
x509.DNSName("localhost"),
x509.IPAddress(host_ip),
x509.DNSName(f"{args.t}"),
]
),
critical=False,
)
.sign(key, hashes.SHA256(), default_backend())
)
if not args.zt:
cert = (
x509.CertificateBuilder()
.subject_name(csr.subject)
.issuer_name(issuer)
.public_key(csr.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(datetime.utcnow())
.not_valid_after(datetime.utcnow() + timedelta(days=365))
.add_extension(
x509.SubjectAlternativeName(
[
x509.DNSName("localhost"),
x509.IPAddress(host_ip),
]
),
critical=False,
)
.sign(ca_key, hashes.SHA256(), default_backend())
)
else:
cert = (
x509.CertificateBuilder()
.subject_name(csr.subject)
.issuer_name(issuer)
.public_key(csr.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(datetime.utcnow())
.not_valid_after(datetime.utcnow() + timedelta(days=365))
.add_extension(
x509.SubjectAlternativeName(
[
x509.DNSName("localhost"),
x509.IPAddress(host_ip),
x509.DNSName(f"{args.t}"),
]
),
critical=False,
)
.sign(ca_key, hashes.SHA256(), default_backend())
)
if store:
cert_path_file_pem = os.path.join(dir, f"HOST_cert@{unique_id}.pem")
with open(cert_path_file_pem, "wb") as certfile:
certfile.write(cert.public_bytes(serialization.Encoding.PEM))
print(f"Host {unique_id} ECDSA key & certificate generated.")
def ssl_ECDSA_key_certgen_CA(args, dir="", store=True):
print("Generating ROOT CA key/cert chain...")
unique_id = hexlify(os.environ["USER"].encode()).decode()[:10]
print("ID HOST: {}".format(unique_id))
dev_platform = sys.platform
key = ec.generate_private_key(ec.SECP256R1(), backend=default_backend())
# key = ed25519.Ed25519PrivateKey.generate()
my_p = getpass.getpass(prompt="Passphrase: ", stream=None)
pem = key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.BestAvailableEncryption(
bytes(my_p, "utf-8")
),
)
if store:
key_path_file_pem = os.path.join(dir, "ROOT_CA_key.pem")
with open(key_path_file_pem, "wb") as keyfile:
keyfile.write(pem)
cert_data = get_cert_data()
subject = issuer = x509.Name(
[
x509.NameAttribute(NameOID.USER_ID, f"{dev_platform}@{unique_id}"),
x509.NameAttribute(NameOID.SURNAME, "{}".format(cert_data["HOST_NAME"])),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, "MicroPython"),
x509.NameAttribute(NameOID.COMMON_NAME, cert_data["USER"]),
]
)
cert = (
x509.CertificateBuilder()
.subject_name(subject)
.issuer_name(issuer)
.public_key(key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(datetime.utcnow())
.not_valid_after(datetime.utcnow() + timedelta(days=1825))
.add_extension(
x509.BasicConstraints(ca=True, path_length=None),
critical=True,
)
.sign(key, hashes.SHA256(), default_backend())
)
if store:
cert_path_file_pem = os.path.join(dir, "ROOT_CA_cert.pem")
with open(cert_path_file_pem, "wb") as certfile:
certfile.write(cert.public_bytes(serialization.Encoding.PEM))
print("ROOT CA ECDSA key & certificate generated.")
if args.tfkey:
print("Transfering ECDSA ROOT certificate to the device...")
ssl_k = key_path_file_pem
ssl_c = cert_path_file_pem
return {"ACTION": "put", "mode": "SSL_HOST", "Files": [ssl_k, ssl_c]}
# CRYPTO
def get_rsa_key(args):
# print('Generating RSA key...')
print("Getting unique id...")
dev = Device(args.t, args.p, init=True, ssl=args.wss, auth=args.wss)
id_bytes = dev.cmd(
"from machine import unique_id; unique_id()", silent=True, rtn_resp=True
)
dev.disconnect()
unique_id = hexlify(id_bytes).decode()
print("ID: {}".format(unique_id))
pkey = rsa_keygen(args, dir=UPYDEV_PATH, show_key=args.show_key, id=unique_id)
print("Done!")
if args.tfkey: # move out for now
print("Loading RSA key...")
key_abs = os.path.join(UPYDEV_PATH, "upy_pv_rsa{}.key".format(unique_id))
key_abs_pub = os.path.join(UPYDEV_PATH, "upy_pub_rsa{}.key".format(unique_id))
print("Transfering RSA key to the device...")
return {"ACTION": "put", "mode": "RSA", "Files": [key_abs, key_abs_pub]}
def get_rsa_key_host(args):
# print('Generating RSA key...')
# print('Getting Host unique id...')
# bb = 6
# while True:
# try:
# unique_id = hexlify(uuid.getnode().to_bytes(bb, 'big')).decode()
# break
# except OverflowError:
# bb += 1
unique_id = hexlify(os.environ["USER"].encode()).decode()[:12]
# print('Host ID: {}'.format(unique_id))
pkey = rsa_keygen(
args, dir=UPYDEV_PATH, show_key=args.show_key, id=unique_id, host=True
)
print("Done!")
if args.tfkey: # move out for now
print("Loading Host Public RSA key...")
key_abs_pub = os.path.join(UPYDEV_PATH, f"upy_host_pub_rsa{unique_id}.key")
print("Transfering Host Public RSA key to the device...")
return {"ACTION": "put", "mode": "RSA", "Files": [key_abs_pub]}
def refresh_wrkey(args, device):
print("Generating new random WebREPL password for {}...".format(device))
print("Getting unique id...")
dev = Device(args.t, args.p, init=True, ssl=args.wss, auth=args.wss)
id_bytes = dev.cmd(
"from machine import unique_id; unique_id()", silent=True, rtn_resp=True
)
unique_id = hexlify(id_bytes).decode()
print("ID: {}".format(unique_id))
pvkey = load_rsa_key(dir=UPYDEV_PATH, show_key=args.show_key, id=unique_id)
print("Generating random password from RSA key...")
new_p, new_token = upy_keygen(pvkey)
# Encrypt password and decrypt on device
is_rsa = dev.cmd(
"import os; 'rsa' in os.listdir('/lib')", silent=True, rtn_resp=True
)
if is_rsa:
dev_pubkey = serialization.load_pem_public_key(pvkey)
dev_pvkey = f"upy_pv_rsa{unique_id}.key"
dev.cmd(
f"from rsa.rsautil import RSAPrivateKey; pv = RSAPrivateKey('{dev_pvkey}')"
)
enc_new_p = dev_pubkey.encrypt(new_p.encode(), padding.PKCS1v15())
dev.cmd("new_pass = b''")
# Send password
for i in range(0, len(enc_new_p), 32):
dev.cmd(f"new_pass += {enc_new_p[i:i+32]}")
# Save password
dev.cmd("pv._decrypt_passwd(new_pass)")
else:
dev.cmd("from upysecrets import load_key, upy_keygen")
dev.cmd("rk = load_key()")
dev.cmd("newp = upy_keygen(rk, {})".format(new_token))
print("New random password generated!")
dev.reset(reconnect=False)
upydev_ip = args.t
upydev_pass = new_p
upy_conf = {"addr": upydev_ip, "passwd": upydev_pass, "name": device}
file_conf = "upydev_.config"
if args.g:
file_conf = os.path.join(UPYDEV_PATH, "upydev_.config")
with open(file_conf, "w") as config_file:
config_file.write(json.dumps(upy_conf))
if args.g:
print("{} settings saved globally!".format(device))
else:
print("{} settings saved in working directory!".format(device))
# check if device is in global group
dt = check_device_type(args.t)
upydev_name = device
group_file = "UPY_G.config"
group_file_path = os.path.join(UPYDEV_PATH, group_file)
if group_file in os.listdir(UPYDEV_PATH):
with open(group_file_path, "r", encoding="utf-8") as group:
devices = json.loads(group.read())
if upydev_name in devices:
devices.update({upydev_name: [upydev_ip, upydev_pass]})
with open(group_file_path, "w", encoding="utf-8") as group:
group.write(json.dumps(devices))
print("{} {} settings saved in global group!".format(dt, upydev_name))
def get_ssl_keycert(args, host=False, CA=False, dev_name=None):
# DEVICE (key,cert pair) --> .DER (key,cert) to device
if not host and not CA:
if args.tfkey:
ssl_dict = ssl_ECDSA_key_certgen(
args, dir=tempfile.gettempdir(), dev_name=dev_name
)
else:
ssl_dict = ssl_ECDSA_key_certgen(args, dir=UPYDEV_PATH, dev_name=dev_name)
# HOST (key, cert pair) --> .PEM (cert) to device (CADATA)
elif host:
# if args.tfkey:
# ssl_dict = ssl_ECDSA_key_certgen_host(args, dir=tempfile.gettempdir())
# else:
ssl_dict = ssl_ECDSA_key_certgen_host(args, dir=UPYDEV_PATH)
elif CA:
if args.tfkey:
ssl_dict = ssl_ECDSA_key_certgen_CA(args, dir=tempfile.gettempdir())
else:
ssl_dict = ssl_ECDSA_key_certgen_CA(args, dir=UPYDEV_PATH)
if ssl_dict:
return ssl_dict
# def add_ssl_cert(cert):
# # device cert
# # detect if cert is present; ask for rotation
# pass
#
#
# def export_ssl_cert(cert):
# # device cert
# # detect if cert is present; ask for new cert if present
# pass
def get_ssl_cert_status(cert):
with open(cert, "rb") as cert_data: