-
Notifications
You must be signed in to change notification settings - Fork 11
/
socsec.py
executable file
·1701 lines (1460 loc) · 65.8 KB
/
socsec.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
#!/usr/bin/env python3
# Copyright (c) 2020 ASPEED Technology Inc.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import argparse
import sys
import re
import os
import struct
import subprocess
import tempfile
import hexdump
from Crypto.Hash import SHA
from Crypto.Hash import SHA224
from Crypto.Hash import SHA256
from Crypto.Hash import SHA384
from Crypto.Hash import SHA512
from Crypto.Util import Counter
from Crypto.Cipher import AES
from Crypto.PublicKey import RSA
from bitarray import bitarray
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
RSA_SHA = 1 # mode 2
AES_RSA_SHA = 2 # mode 2 with aes encryption
AES_GCM = 3 # mode gcm
HASH_BINDING = 4
RSA_OEM = 0x8
RSA_SOC_PUB = 0xa
RSA_SOC_PRI = 0xe
AES_OEM = 0x2
AES_VAULT = 0x1
class SecError(Exception):
"""Application-specific errors.
These errors represent issues for which a stack-trace should not be
presented.
Attributes:
message: Error message.
"""
def __init__(self, message):
Exception.__init__(self, message)
class Algorithm(object):
"""Contains details about an algorithm.
See the avb_vbmeta_image.h file for more details about algorithms.
Attributes:
algorithm_type: Integer code corresponding to |AvbAlgorithmType|.
hash_name: Empty or a name from |hashlib.algorithms|.
hash_num_bytes: Number of bytes used to store the hash.
signature_num_bytes: Number of bytes used to store the signature.
public_key_num_bytes: Number of bytes used to store the public key.
padding: Padding used for signature, if any.
"""
def __init__(self, algorithm_type, hash_alg, hash_num_bytes,
signature_num_bytes, public_key_num_bytes):
self.algorithm_type = algorithm_type
self.hash_alg = hash_alg
self.hash_num_bytes = hash_num_bytes
self.signature_num_bytes = signature_num_bytes
self.public_key_num_bytes = public_key_num_bytes
class ChainPartitionDescriptor(object):
def __init__(self, image_path, out_path, sign_key_path, verify_key_path,
next_verify_key_path):
self.image_path = image_path
self.out_path = out_path
self.sign_key_path = sign_key_path
self.verify_key_path = verify_key_path
self.next_verify_key_path = next_verify_key_path
def parse_path(path):
if path is None or path == '':
return os.path.dirname(os.path.abspath(__file__))+'/'
if path[-1] != '/':
path += '/'
return path
def parse_number(string):
"""Parse a string as a number.
This is just a short-hand for int(string, 0) suitable for use in the
|type| parameter of |ArgumentParser|'s add_argument() function. An
improvement to just using type=int is that this function supports
numbers in other bases, e.g. "0x1234".
Arguments:
string: The string to parse.
Returns:
The parsed integer.
Raises:
ValueError: If the number could not be parsed.
"""
return int(string, 0)
def rsa_bit_length(rsa_key_file: str, var: str) -> int:
with open(rsa_key_file, 'rb') as f:
key_file_bin = f.read()
f.close()
rsa_key = RSA.importKey(key_file_bin)
return _rsa_bit_length(rsa_key, var)
def _rsa_bit_length(rsa_key, var):
if var == 'n':
key_bit_length = bitarray(bin(rsa_key.n)[2:]).length()
elif var == 'e':
key_bit_length = bitarray(bin(rsa_key.e)[2:]).length()
elif var == 'd':
key_bit_length = bitarray(bin(rsa_key.d)[2:]).length()
return key_bit_length
def rsa_key_to_bin(rsa_key_file, types, order='little'):
if order not in ['little', 'big']:
raise ValueError("order error")
with open(rsa_key_file, 'rb') as f:
key_file_bin = f.read()
f.close()
rsa_key = RSA.importKey(key_file_bin)
rsa_len = _rsa_bit_length(rsa_key, 'n')
n = bitarray(bin(rsa_key.n)[2:])
e = bitarray(bin(rsa_key.e)[2:])
n_remain = (8-(n.length() % 8)) % 8
e_remain = (8-(e.length() % 8)) % 8
for _ in range(0, n_remain):
n.insert(0, 0)
for _ in range(0, e_remain):
e.insert(0, 0)
n = n.tobytes()
e = e.tobytes()
n_b = bytearray(n)
e_b = bytearray(e)
if order == 'little':
n_b.reverse()
e_b.reverse()
if types == 'public':
exp = e_b
elif types == 'private':
d = bitarray(bin(rsa_key.d)[2:])
d_remain = (8-(d.length() % 8)) % 8
for _ in range(0, d_remain):
d.insert(0, 0)
d = d.tobytes()
d_b = bytearray(d)
if order == 'little':
d_b.reverse()
exp = d_b
else:
raise ValueError("types error")
if rsa_len == 1024:
m_len = 128
elif rsa_len == 2048:
m_len = 256
elif rsa_len == 3072:
m_len = 384
else:
m_len = 512
key_bin = bytearray(m_len * 2)
insert_bytearray(n_b, key_bin, 0)
insert_bytearray(exp, key_bin, m_len)
return key_bin
def rsa_signature(alg_data, rsa_key_file, src_bin,
signing_helper, signing_helper_with_files, order='little'):
src_bin = bytearray(src_bin)
if order == 'little':
src_bin.reverse()
if signing_helper_with_files is not None:
signing_file = tempfile.NamedTemporaryFile()
signing_file.write(src_bin)
signing_file.flush()
p = subprocess.Popen([
signing_helper_with_files, rsa_key_file, signing_file.name])
retcode = p.wait()
if retcode != 0:
raise ValueError('Error signing')
signing_file.seek(0)
read_f = signing_file.read()
signature = bytearray(read_f)
if order == 'little':
signature.reverse()
else:
if signing_helper is not None:
p = subprocess.Popen(
[signing_helper, rsa_key_file],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
else:
p = subprocess.Popen(
['openssl', 'rsautl', '-sign', '-inkey', rsa_key_file],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
(pout, perr) = p.communicate(input=src_bin)
retcode = p.wait()
if retcode != 0:
raise ValueError('Error signing: {}'.format(perr))
signature = bytearray(pout)
if order == 'little':
signature.reverse()
if signature.__len__() < 512:
signature = signature + bytearray(512 - signature.__len__())
return signature
def rsa_verify(alg_data, rsa_key_file, signature, digest, order='little'):
rev_signature = bytearray(signature)
if order == 'little':
rev_signature.reverse()
if rev_signature.__len__() < alg_data.signature_num_bytes:
rev_signature = rev_signature + \
bytearray(alg_data.signature_num_bytes - rev_signature.__len__())
with open(rsa_key_file, 'rb') as f:
key_file_bin = f.read()
f.close()
rsakey = RSA.importKey(key_file_bin)
try:
if rsakey.d:
cmd = "openssl rsautl -verify -raw -inkey " + rsa_key_file
except (AttributeError):
cmd = "openssl rsautl -verify -raw --pubin -inkey " + rsa_key_file
p = subprocess.Popen(
cmd,
shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
sign_dec, stderr = p.communicate(input=rev_signature)
if stderr or p.returncode != 0:
print(stderr)
sign_dec = bytearray(sign_dec)
if order == 'little':
sign_dec.reverse()
sign_dec = sign_dec[:digest.__len__()]
else:
sign_dec = sign_dec[sign_dec.__len__() - digest.__len__():]
if sign_dec == digest:
return True
else:
return False
def rsa_encrypt(rsa_key_file, src_bin, order='little'):
with open(rsa_key_file, 'rb') as f:
key_bin = f.read()
f.close()
rsa_key = RSA.importKey(key_bin)
src_bin = bytearray(src_bin)
if order == 'little':
src_bin.reverse()
if rsa_key.has_private():
t = RSA.construct((rsa_key.n, rsa_key.d, rsa_key.e))
cipher = Cipher_pkcs1_v1_5.new(t)
src_enc = cipher.encrypt(src_bin)
else:
cipher = Cipher_pkcs1_v1_5.new(rsa_key)
src_enc = cipher.encrypt(src_bin)
src_enc = bytearray(src_enc)
if order == 'little':
src_enc.reverse()
key_bit_length = bitarray(bin(rsa_key.n)[2:]).length()
key_byte_length = int((key_bit_length + 7) / 8)
if src_enc.__len__() < key_byte_length:
src_enc = src_enc + bytearray(key_byte_length - src_enc.__len__())
return src_enc
def rsa_decrypt(key_type, rsa_key_file, src_bin, order='little'):
with open(rsa_key_file, 'rb') as f:
key_bin = f.read()
f.close()
rsa_key = RSA.importKey(key_bin)
src_bin = bytearray(src_bin)
if order == 'little':
src_bin.reverse()
if key_type == 'public':
cipher = Cipher_pkcs1_v1_5.new(rsa_key)
src_enc = cipher.decrypt(src_bin, "")
elif key_type == 'private':
t = RSA.construct((rsa_key.n, rsa_key.d, rsa_key.e))
cipher = Cipher_pkcs1_v1_5.new(t)
src_enc = cipher.decrypt(src_bin, "")
src_enc = bytearray(src_enc)
if order == 'little':
src_enc.reverse()
key_bit_length = bitarray(bin(rsa_key.n)[2:]).length()
key_byte_length = int((key_bit_length + 7) / 8)
if src_enc.__len__() < key_byte_length:
src_enc = src_enc + bytearray(key_byte_length - src_enc.__len__())
return src_enc
def insert_bytearray(src, dst, offset):
if offset+src.__len__() > dst.__len__():
dst.extend(bytearray(offset-dst.__len__()+src.__len__()))
dst[offset:offset+src.__len__()] = src
class OTP_info(object):
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))+'/'
MAGIC_WORD_OTP = 'SOCOTP'
HEADER_FORMAT = '<8s8s5I'
HEADER_SIZE = struct.calcsize(HEADER_FORMAT)
CHECKSUM_LEN = 32
INC_DATA = 1 << 31
INC_CONF = 1 << 30
INC_STRAP = 1 << 29
INC_ECC = 1 << 28
INC_DUMP = 1 << 27
INC_ORDER = 1 << 26
OTP_INFO = {
'A0': {
'config': ROOT_DIR+'otp_info/a0_config.json',
'strap': ROOT_DIR+'otp_info/a0_strap.json',
'data_region_size': 8192,
'ecc_region_offset': 7168,
'config_region_size': 64,
'otp_strap_bit_size': 64,
},
'A1': {
'config': ROOT_DIR+'otp_info/a1_config.json',
'strap': ROOT_DIR+'otp_info/a1_strap.json',
'data_region_size': 8192,
'ecc_region_offset': 7168,
'config_region_size': 64,
'otp_strap_bit_size': 64,
},
'A2': {
'config': ROOT_DIR+'otp_info/a2_config.json',
'strap': ROOT_DIR+'otp_info/a2_strap.json',
'data_region_size': 8192,
'ecc_region_offset': 7168,
'config_region_size': 64,
'otp_strap_bit_size': 64,
},
'A3': {
'config': ROOT_DIR+'otp_info/a2_config.json',
'strap': ROOT_DIR+'otp_info/a2_strap.json',
'data_region_size': 8192,
'ecc_region_offset': 7168,
'config_region_size': 64,
'otp_strap_bit_size': 64,
},
'1030A0': {
'config': ROOT_DIR+'otp_info/1030a0_config.json',
'strap': ROOT_DIR+'otp_info/1030a0_strap.json',
'data_region_size': 8192,
'ecc_region_offset': 7168,
'config_region_size': 64,
'otp_strap_bit_size': 64,
}
}
class Sec(object):
"""Business logic for socsec command-line tool."""
MAGIC_WORD_VB = 'SOCSEC'
ROT_HEADER_FORMAT = '<8I'
ROT_HEADER_SIZE = struct.calcsize(ROT_HEADER_FORMAT)
COT_INFO_FORMAT = '<2I'
COT_INFO_SIZE = struct.calcsize(COT_INFO_FORMAT)
COT_HEADER_FORMAT = '<16s6I472s'
COT_HEADER_SIZE = struct.calcsize(COT_HEADER_FORMAT)
def parse_algorithm(self, algorithm_name):
algorithm_type = -1
rsa_len = 0
sha_len = 0
match_alg = re.match(
r'AES_RSA(1024|2048|3072|4096)_SHA(224|256|384|512)',
algorithm_name, re.M)
if match_alg:
algorithm_type = AES_RSA_SHA
rsa_len = match_alg.group(1)
sha_len = match_alg.group(2)
match_alg = re.match(
r'RSA(1024|2048|3072|4096)_SHA(224|256|384|512)',
algorithm_name, re.M)
if match_alg:
algorithm_type = RSA_SHA
rsa_len = match_alg.group(1)
sha_len = match_alg.group(2)
if algorithm_name == 'AES_GCM':
algorithm_type = AES_GCM
match_alg = re.match(
r'SHA(224|256|384|512)',
algorithm_name, re.M)
if match_alg:
algorithm_type = HASH_BINDING
sha_len = match_alg.group(1)
if algorithm_type == -1:
raise SecError('Algorithm is invalid')
if rsa_len == '1024':
signature_num_bytes = 128
public_key_num_bytes = 2*1024//8
elif rsa_len == '2048':
signature_num_bytes = 256
public_key_num_bytes = 2*2048//8
elif rsa_len == '3072':
signature_num_bytes = 384
public_key_num_bytes = 2*3072//8
elif rsa_len == '4096':
signature_num_bytes = 512
public_key_num_bytes = 2*4096//8
else:
signature_num_bytes = 0
public_key_num_bytes = 0
if sha_len == '224':
hash_alg = SHA224
hash_num_bytes = 28
elif sha_len == '256':
hash_alg = SHA256
hash_num_bytes = 32
elif sha_len == '384':
hash_alg = SHA384
hash_num_bytes = 48
elif sha_len == '512':
hash_alg = SHA512
hash_num_bytes = 64
else:
hash_alg = None
hash_num_bytes = 0
return Algorithm(algorithm_type, hash_alg, hash_num_bytes,
signature_num_bytes, public_key_num_bytes)
def verify_bl1_mode_2_image(self, sec_image, verify_key_path, alg_data,
sign_image_size, signature_offset, rsa_key_order):
sha = alg_data.hash_alg.new(sec_image[0:sign_image_size])
digest = sha.digest()
image_signature = sec_image[signature_offset:
(signature_offset+alg_data.signature_num_bytes)]
if not rsa_verify(alg_data, verify_key_path,
image_signature, digest, order=rsa_key_order):
raise SecError("signature verify failed")
def decode_bl1_mode_2_enc_image(self, image, sec_image, header_offset,
enc_offset, aes_data_offset, aes_key,
rsa_aes_key_path, alg_data,
sign_image_size, key_in_otp):
# if not key_in_otp:
# rsa_key_length = alg_data.signature_num_bytes
# key_obj = sec_image[aes_data_offset:aes_data_offset + rsa_key_length]
# aes_object = rsa_decrypt(
# 'public', rsa_aes_key_path, bytes(key_obj))
# aes_key = bytes(aes_object[0:0x20])
# aes_iv = bytes(aes_object[0x20:0x30])
# else:
aes_iv = sec_image[aes_data_offset:aes_data_offset+16]
ctr = Counter.new(128, initial_value=int.from_bytes(
aes_iv, byteorder='big'))
aes = AES.new(aes_key, AES.MODE_CTR, counter=ctr)
dec_image = bytearray(aes.decrypt(
bytes(sec_image[enc_offset:sign_image_size])))
if image[enc_offset:] != dec_image:
raise SecError("image decrypt failed")
def verify_bl1_mode_gcm_image(self, image, sec_image, signature_offset,
sign_image_size,
enc_offset, aes_data_offset, aes_key):
image_signature = sec_image[signature_offset:signature_offset+16]
rev_signature = bytearray(16)
for i in range(0, 15, 4):
rev_signature[i] = image_signature[12-i]
rev_signature[i+1] = image_signature[13-i]
rev_signature[i+2] = image_signature[14-i]
rev_signature[i+3] = image_signature[15-i]
aes_iv = sec_image[aes_data_offset:aes_data_offset+12]
try:
aes = AES.new(aes_key, AES.MODE_GCM, nonce=aes_iv[0:12])
aes.update(sec_image[:enc_offset])
plaintext = aes.decrypt_and_verify(
sec_image[enc_offset:sign_image_size], rev_signature)
except (ValueError, KeyError):
raise SecError("gcm verify failed")
# if image[enc_offset:] != plaintext[:image.__len__()-enc_offset]:
if image[enc_offset:] != plaintext:
raise SecError("image decrypt failed")
def verify_bl1_image(self, image, sec_image, header_offset, verify_key_path,
gcm_aes_key, aes_key, rsa_aes_key_path, alg_data,
key_in_otp, rsa_key_order):
header = sec_image[header_offset:header_offset+self.ROT_HEADER_SIZE]
(aes_data_offset, enc_offset, sign_image_size,
signature_offset, revision_low, revision_high,
reserved, bl1_header_checksum) = struct.unpack(self.ROT_HEADER_FORMAT, header)
if((aes_data_offset + enc_offset + sign_image_size +
signature_offset + revision_low + revision_high +
reserved + bl1_header_checksum) & 0xffffffff) != 0:
raise SecError("header checksum verify failed")
if sign_image_size % 512:
raise SecError("The sign_image_size should be 512 bytes aligned")
print("check header PASS")
if alg_data.algorithm_type in [RSA_SHA, AES_RSA_SHA]:
self.verify_bl1_mode_2_image(sec_image, verify_key_path, alg_data,
sign_image_size, signature_offset, rsa_key_order)
print("check integrity PASS")
if alg_data.algorithm_type == AES_RSA_SHA and key_in_otp:
self.decode_bl1_mode_2_enc_image(image, sec_image, header_offset,
enc_offset, aes_data_offset, aes_key,
rsa_aes_key_path, alg_data,
sign_image_size, key_in_otp)
print("check aes decode PASS")
if alg_data.algorithm_type == AES_GCM:
self.verify_bl1_mode_gcm_image(image, sec_image, signature_offset,
sign_image_size, enc_offset,
aes_data_offset, gcm_aes_key)
print("check gcm integrity and decode PASS")
def verify_sv_chain_image(self, image_list, first_layer_vk_path,
alg_data, rsa_key_order):
for i in range(0, len(image_list)):
print('BL{:d} verifying'.format(i + 2))
part_image = image_list[i]
header = part_image[:self.COT_HEADER_SIZE]
(magic_word, info, sign_image_size, signature_offset,
npkey_offset, revision_low, revision_high, reserved) = struct.unpack(self.COT_HEADER_FORMAT, header)
mw = self.MAGIC_WORD_VB.encode()
if magic_word[0:len(mw)] == mw:
print("check header magic word PASS")
else:
raise SecError("header magic word verify failed")
if i == 0:
va = alg_data
vk = first_layer_vk_path
else:
va = next_alg_data
vk = next_vk
if i != len(image_list) - 1:
next_alg_data = self.parse_cot_info(info)
next_vk_n = part_image[npkey_offset:npkey_offset +
int(next_alg_data.public_key_num_bytes / 2)]
next_vk_e = part_image[int(npkey_offset + next_alg_data.public_key_num_bytes / 2):
npkey_offset + next_alg_data.public_key_num_bytes]
next_vk_n = int.from_bytes(
next_vk_n, byteorder=rsa_key_order, signed=False)
next_vk_e = int.from_bytes(
next_vk_e, byteorder=rsa_key_order, signed=False)
next_vk_obj = RSA.construct((next_vk_n, next_vk_e))
signing_file = tempfile.NamedTemporaryFile()
next_vk_obj.exportKey
signing_file.write(next_vk_obj.publickey().exportKey('PEM'))
signing_file.flush()
next_vk = signing_file.name
self.verify_bl1_mode_2_image(part_image, vk, va, sign_image_size,
signature_offset, rsa_key_order)
print("check integrity PASS")
def make_bl1_mode_2_image(self, image, alg_data, sign_key_path,
header_offset,
sign_image_size, signature_offset,
rsa_key_order,
signing_helper, signing_helper_with_files):
# sign the image
sha = alg_data.hash_alg.new(image[0:sign_image_size])
digest = sha.digest()
signature = rsa_signature(
alg_data, sign_key_path, digest,
signing_helper, signing_helper_with_files, order=rsa_key_order)
insert_bytearray(signature, image, signature_offset)
def make_bl1_mode_2_enc_image(self, image, alg_data, sign_key_path,
header_offset,
sign_image_size, signature_offset,
enc_offset, aes_key, aes_iv, aes_data_offset,
key_in_otp, rsa_aes_key_path, rsa_key_order,
signing_helper, signing_helper_with_files):
# encrypt image
ctr = Counter.new(128, initial_value=int.from_bytes(
aes_iv, byteorder='big'))
aes = AES.new(aes_key, AES.MODE_CTR, counter=ctr)
enc_image = bytearray(aes.encrypt(
bytes(image[enc_offset:sign_image_size])))
insert_bytearray(enc_image, image, enc_offset)
# insert aes object
if key_in_otp:
insert_bytearray(aes_iv, image, aes_data_offset)
else:
aes_object = bytearray(48)
insert_bytearray(aes_key, aes_object, 0)
insert_bytearray(aes_iv, aes_object, 0x20)
enc_aes_object = rsa_encrypt(
rsa_aes_key_path, bytes(aes_object), order=rsa_key_order)
insert_bytearray(enc_aes_object, image, aes_data_offset)
# sign the image
sha = alg_data.hash_alg.new(image[0:sign_image_size])
digest = sha.digest()
signature = rsa_signature(
alg_data, sign_key_path, digest,
signing_helper, signing_helper_with_files, order=rsa_key_order)
insert_bytearray(signature, image, signature_offset)
def make_bl1_mode_gcm_image(self, image, alg_data, gcm_aes_key, gcm_aes_iv,
header_offset, enc_offset,
sign_image_size, signature_offset,
aes_data_offset,
signing_helper, signing_helper_with_files):
aes = AES.new(gcm_aes_key, AES.MODE_GCM, nonce=gcm_aes_iv[0:12])
aes.update(image[:enc_offset])
ciphertext, signature = aes.encrypt_and_digest(
image[enc_offset:sign_image_size])
# reverse signature for secure boot rom code
rev_signature = bytearray(16)
for i in range(0, 15, 4):
rev_signature[i] = signature[12-i]
rev_signature[i+1] = signature[13-i]
rev_signature[i+2] = signature[14-i]
rev_signature[i+3] = signature[15-i]
insert_bytearray(ciphertext, image, enc_offset)
insert_bytearray(gcm_aes_iv, image, aes_data_offset)
insert_bytearray(rev_signature, image, signature_offset)
def _cot_info(self, cot_alg_data, rsa_e_bits_len):
info = 0
if cot_alg_data.algorithm_type == RSA_SHA:
info = 1
if cot_alg_data.signature_num_bytes == 128:
info |= 0
elif cot_alg_data.signature_num_bytes == 256:
info |= 1 << 3
elif cot_alg_data.signature_num_bytes == 384:
info |= 2 << 3
elif cot_alg_data.signature_num_bytes == 512:
info |= 3 << 3
info |= rsa_e_bits_len << 20
elif cot_alg_data.algorithm_type == HASH_BINDING:
info = 0
else:
raise SecError(
"COT only support RSA_SHA and HASH_BINDING algorithm")
if cot_alg_data.hash_num_bytes == 28:
info |= 0
elif cot_alg_data.hash_num_bytes == 32:
info |= 1 << 1
elif cot_alg_data.hash_num_bytes == 48:
info |= 2 << 1
elif cot_alg_data.hash_num_bytes == 64:
info |= 3 << 1
return info
def parse_cot_info(self, info):
if info & 1:
algorithm_type = RSA_SHA
else:
algorithm_type = HASH_BINDING
rsa_info = (info >> 3) & 3
if rsa_info == 0:
signature_num_bytes = 128
public_key_num_bytes = 2*1024//8
elif rsa_info == 1:
signature_num_bytes = 256
public_key_num_bytes = 2*2048//8
elif rsa_info == 2:
signature_num_bytes = 384
public_key_num_bytes = 2*3072//8
else:
signature_num_bytes = 512
public_key_num_bytes = 2*4096//8
hash_info = (info >> 1) & 3
if hash_info == 0:
hash_alg = SHA224
hash_num_bytes = 28
elif hash_info == 1:
hash_alg = SHA256
hash_num_bytes = 32
elif hash_info == 2:
hash_alg = SHA384
hash_num_bytes = 48
else:
hash_alg = SHA512
hash_num_bytes = 64
return Algorithm(algorithm_type, hash_alg, hash_num_bytes,
signature_num_bytes, public_key_num_bytes)
def insert_bl1_cot_info(self, image, cot_alg_data, cot_header_offset,
verify_key_path, cot_digest_fd, cot_data_offset):
if cot_alg_data.algorithm_type == RSA_SHA:
e_bits = rsa_bit_length(verify_key_path, 'e')
cot_data = bytearray(rsa_key_to_bin(verify_key_path, 'public'))
elif cot_alg_data.algorithm_type == HASH_BINDING:
cot_data = bytearray(cot_digest_fd.read())
else:
raise SecError(
"COT only support RSA_SHA and HASH_BINDING algorithm")
info = self._cot_info(cot_alg_data, e_bits)
cot_header = struct.pack(
self.COT_INFO_FORMAT,
info,
cot_data_offset
)
insert_bytearray(cot_header, image, cot_header_offset)
insert_bytearray(cot_data, image, cot_data_offset)
def make_secure_bl1_image(self, soc_version, bl1_image_fd, sign_key_path, gcm_aes_key_fd, output_fd,
algorithm_name, header_offset, rollback_index,
enc_offset, aes_key_fd, rsa_aes_key_path,
key_in_otp,
rsa_key_order,
cot_algorithm_name,
cot_verify_key_path,
cot_digest_fd,
signing_helper,
signing_helper_with_files):
"""Implements the 'make_vbmeta_image' command.
Arguments:
bl1_image: Bootloader 1 image.
sign_key_path: Path to rsa signing key to use or None.
output: File to write the image to.
algorithm_name: Name of algorithm to use.
rollback_index: The rollback index to use.
enc_offset:
aes_key_fd;
rsa_aes_key_path;
key_in_otp:
cot_algorithm_name:
cot_verify_key_path:
cot_digest_fd:
signing_helper: Program which signs a hash and return signature.
signing_helper_with_files: Same as signing_helper but uses files instead.
Raises:
SecError: If a chained partition is malformed.
"""
aes_key = None
gcm_aes_key = None
bl1_image = bytearray(bl1_image_fd.read())
bl1_image_len = len(bl1_image)
if soc_version == '2600':
if header_offset == None:
header_offset = 0x20
if enc_offset == None:
enc_offset = 0x50
if bl1_image_len > (60 * 1024):
raise SecError("The maximum size of BL1 image is 60 KBytes.")
elif soc_version == '1030':
if header_offset == None:
header_offset = 0x400
if enc_offset == None:
enc_offset = 0x430
if bl1_image_len > (768 * 1024):
raise SecError("The maximum size of BL1 image is 768 KBytes.")
else:
raise SecError("SOC version is not avaliable")
if enc_offset % 16:
raise SecError("The enc_offset should be 16 bytes aligned")
if enc_offset < header_offset + 0x30:
raise SecError(
"The enc_offset should 0x30 more than header_offset")
if rsa_key_order not in ['big', 'little']:
raise SecError("RSA key order should be 'big' or 'little'")
alg_data = self.parse_algorithm(algorithm_name)
aes_data_offset = 0
sign_image_size = 0
signature_offset = 0
revision_low = 0
revision_high = 0
bl1_header_checksum = 0
if cot_algorithm_name:
cot_alg_data = self.parse_algorithm(cot_algorithm_name)
cot_header_offset = header_offset + self.ROT_HEADER_SIZE
cot_data_offset = max((bl1_image_len + 0xf) & (~0xf),
(cot_header_offset + self.COT_INFO_SIZE + 0xf) & (~0xf))
if cot_alg_data.algorithm_type == RSA_SHA:
sign_image_size = cot_data_offset + cot_alg_data.public_key_num_bytes
elif cot_alg_data.algorithm_type == HASH_BINDING:
sign_image_size = cot_data_offset + cot_alg_data.hash_num_bytes
else:
raise SecError(
"COT only support RSA_SHA and HASH_BINDING algorithm")
sign_image_size = (sign_image_size + 511) & (~511)
else:
sign_image_size = (bl1_image_len + 511) & (~511)
if alg_data.algorithm_type == AES_RSA_SHA:
aes_data_offset = sign_image_size
if key_in_otp:
signature_offset = sign_image_size + 16
else:
signature_offset = sign_image_size + alg_data.signature_num_bytes
elif alg_data.algorithm_type == AES_GCM:
aes_data_offset = sign_image_size
signature_offset = sign_image_size + 16
else:
enc_offset = 0
signature_offset = sign_image_size
bl1_header_checksum = -(aes_data_offset + enc_offset +
sign_image_size + signature_offset +
revision_low + revision_high) & 0xFFFFFFFF
bl1_header = struct.pack(
self.ROT_HEADER_FORMAT,
aes_data_offset,
enc_offset,
sign_image_size,
signature_offset,
revision_low,
revision_high,
0,
bl1_header_checksum
)
bl1_image.extend(bytearray(sign_image_size - bl1_image_len))
output_image = bytearray(sign_image_size)
insert_bytearray(bl1_image, output_image, 0)
# insert header
insert_bytearray(bl1_header, output_image, header_offset)
if cot_algorithm_name:
self.insert_bl1_cot_info(output_image, cot_alg_data,
cot_header_offset, cot_verify_key_path,
cot_digest_fd, cot_data_offset)
plain_image = output_image.copy()
else:
plain_image = bl1_image
if alg_data.algorithm_type == RSA_SHA:
if not sign_key_path:
raise SecError("Missing sign key")
self.make_bl1_mode_2_image(output_image, alg_data, sign_key_path,
header_offset,
sign_image_size, signature_offset,
rsa_key_order,
signing_helper, signing_helper_with_files)
elif alg_data.algorithm_type == AES_RSA_SHA:
aes_iv = open('/dev/urandom', 'rb').read(16)
if aes_key_fd:
aes_key = bytearray(aes_key_fd.read())
else:
raise SecError("Missing aes_key for AES_RSA_SHA")
if (not key_in_otp) & (not rsa_aes_key_path):
raise SecError(
"Missing --rsa_aes when key is not in otp")
self.make_bl1_mode_2_enc_image(output_image, alg_data, sign_key_path,
header_offset,
sign_image_size, signature_offset,
enc_offset, aes_key,
aes_iv, aes_data_offset,
key_in_otp, rsa_aes_key_path,
rsa_key_order,
signing_helper,
signing_helper_with_files)
elif alg_data.algorithm_type == AES_GCM:
gcm_aes_iv = open('/dev/urandom', 'rb').read(12)
gcm_aes_iv = gcm_aes_iv + b"\x00\x00\x00\x01"
if gcm_aes_key_fd:
gcm_aes_key = bytearray(gcm_aes_key_fd.read())
else:
raise SecError("Missing gcm_aes_key for AES_GCM")
self.make_bl1_mode_gcm_image(output_image, alg_data, gcm_aes_key, gcm_aes_iv,
header_offset, enc_offset,
sign_image_size, signature_offset,
aes_data_offset,
signing_helper, signing_helper_with_files)
else:
raise SecError("Algorithm not supported")
self.verify_bl1_image(plain_image, output_image, header_offset,
sign_key_path, gcm_aes_key,
aes_key, rsa_aes_key_path,
alg_data, key_in_otp, rsa_key_order)
output_fd.write(bytes(output_image))
output_fd.close()
def make_sv_partation_image(self, alg_data, descriptor, rsa_key_order,
signing_helper, signing_helper_with_files):
image = bytearray(open(descriptor.image_path, 'rb').read())
image[:0] = bytearray(self.COT_HEADER_SIZE)
image_len = len(image)
sign_image_size = 0
signature_offset = 0
npkey_offset = 0
revision_low = 0
revision_high = 0
if descriptor.next_verify_key_path:
npkey_bin = bytearray(rsa_key_to_bin(
descriptor.next_verify_key_path, 'public'))
npkey_offset = (image_len + 0xf) & (~0xf)
sign_image_size = npkey_offset + alg_data.public_key_num_bytes
insert_bytearray(npkey_bin, image, npkey_offset)
e_bits = rsa_bit_length(descriptor.next_verify_key_path, 'e')