-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathaftltool.py
More file actions
executable file
·1892 lines (1615 loc) · 70.8 KB
/
aftltool.py
File metadata and controls
executable file
·1892 lines (1615 loc) · 70.8 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 2020, The Android Open Source Project
#
# 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.
#
"""Command-line tool for AFTL support for Android Verified Boot images."""
import argparse
import base64
import hashlib
import json
import multiprocessing
import os
import queue
import struct
import subprocess
import sys
import tempfile
import time
# This is to work around temporarily with the issue that python3 does not permit
# relative imports anymore going forward. This adds the proto directory relative
# to the location of aftltool to the sys.path.
# TODO(b/154068467): Implement proper importing of generated *_pb2 modules.
EXEC_PATH = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(EXEC_PATH, 'proto'))
# pylint: disable=wrong-import-position,import-error
import avbtool
import aftl_pb2
import api_pb2
from crypto.sigpb import sigpb_pb2
# pylint: enable=wrong-import-position,import-error
class AftlError(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)
def rsa_key_read_pem_bytes(key_path):
"""Reads the bytes out of the passed in PEM file.
Arguments:
key_path: A string containing the path to the PEM file.
Returns:
A bytearray containing the DER encoded bytes in the PEM file.
Raises:
AftlError: If openssl cannot decode the PEM file.
"""
# Use openssl to decode the PEM file.
args = ['openssl', 'rsa', '-in', key_path, '-pubout', '-outform', 'DER']
p = subprocess.Popen(args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
(pout, perr) = p.communicate()
retcode = p.wait()
if retcode != 0:
raise AftlError('Error decoding: {}'.format(perr))
return pout
def check_signature(log_root, log_root_sig,
transparency_log_pub_key):
"""Validates the signature provided by the transparency log.
Arguments:
log_root: The transparency log_root data structure.
log_root_sig: The signature of the transparency log_root data structure.
transparency_log_pub_key: The file path to the transparency log public key.
Returns:
True if the signature check passes, otherwise False.
"""
logsig_tmp = tempfile.NamedTemporaryFile()
logsig_tmp.write(log_root_sig)
logsig_tmp.flush()
logroot_tmp = tempfile.NamedTemporaryFile()
logroot_tmp.write(log_root)
logroot_tmp.flush()
p = subprocess.Popen(['openssl', 'dgst', '-sha256', '-verify',
transparency_log_pub_key,
'-signature', logsig_tmp.name, logroot_tmp.name],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
p.communicate()
retcode = p.wait()
if not retcode:
return True
return False
# AFTL Merkle Tree Functionality
def rfc6962_hash_leaf(leaf):
"""RFC6962 hashing function for hashing leaves of a Merkle tree.
Arguments:
leaf: A bytearray containing the Merkle tree leaf to be hashed.
Returns:
A bytearray containing the RFC6962 SHA256 hash of the leaf.
"""
hasher = hashlib.sha256()
# RFC6962 states a '0' byte should be prepended to the data.
# This is done in conjunction with the '1' byte for non-leaf
# nodes for 2nd preimage attack resistance.
hasher.update(b'\x00')
hasher.update(leaf)
return hasher.digest()
def rfc6962_hash_children(l, r):
"""Calculates the inner Merkle tree node hash of child nodes l and r.
Arguments:
l: A bytearray containing the left child node to be hashed.
r: A bytearray containing the right child node to be hashed.
Returns:
A bytearray containing the RFC6962 SHA256 hash of 1|l|r.
"""
hasher = hashlib.sha256()
# RFC6962 states a '1' byte should be prepended to the concatenated data.
# This is done in conjunction with the '0' byte for leaf
# nodes for 2nd preimage attack resistance.
hasher.update(b'\x01')
hasher.update(l)
hasher.update(r)
return hasher.digest()
def chain_border_right(seed, proof):
"""Computes a subtree hash along the left-side tree border.
Arguments:
seed: A bytearray containing the starting hash.
proof: A list of bytearrays representing the hashes in the inclusion proof.
Returns:
A bytearray containing the left-side subtree hash.
"""
for h in proof:
seed = rfc6962_hash_children(h, seed)
return seed
def chain_inner(seed, proof, leaf_index):
"""Computes a subtree hash on or below the tree's right border.
Arguments:
seed: A bytearray containing the starting hash.
proof: A list of bytearrays representing the hashes in the inclusion proof.
leaf_index: The current leaf index.
Returns:
A bytearray containing the subtree hash.
"""
for i, h in enumerate(proof):
if leaf_index >> i & 1 == 0:
seed = rfc6962_hash_children(seed, h)
else:
seed = rfc6962_hash_children(h, seed)
return seed
def root_from_icp(leaf_index, tree_size, proof, leaf_hash):
"""Calculates the expected Merkle tree root hash.
Arguments:
leaf_index: The current leaf index.
tree_size: The number of nodes in the Merkle tree.
proof: A list of bytearrays containing the inclusion proof.
leaf_hash: A bytearray containing the initial leaf hash.
Returns:
A bytearray containing the calculated Merkle tree root hash.
Raises:
AftlError: If invalid parameters are passed in.
"""
if leaf_index < 0:
raise AftlError('Invalid leaf_index value: {}'.format(leaf_index))
if tree_size < 0:
raise AftlError('Invalid tree_size value: {}'.format(tree_size))
if leaf_index >= tree_size:
err_str = 'leaf_index cannot be equal or larger than tree_size: {}, {}'
raise AftlError(err_str.format(leaf_index, tree_size))
if proof is None:
raise AftlError('Inclusion proof not provided.')
if leaf_hash is None:
raise AftlError('No leaf hash provided.')
# Calculate the point to split the proof into two parts.
# The split is where the paths to leaves diverge.
inner = (leaf_index ^ (tree_size - 1)).bit_length()
result = chain_inner(leaf_hash, proof[:inner], leaf_index)
result = chain_border_right(result, proof[inner:])
return result
class AftlImageHeader(object):
"""A class for representing the AFTL image header.
Attributes:
magic: Magic for identifying the AftlImage.
required_icp_version_major: The major version of AVB that wrote the entry.
required_icp_version_minor: The minor version of AVB that wrote the entry.
aftl_image_size: Total size of the AftlImage.
icp_count: Number of inclusion proofs represented in this structure.
"""
SIZE = 18 # The size of the structure, in bytes
MAGIC = b'AFTL'
FORMAT_STRING = ('!4s2L' # magic, major & minor version.
'L' # AFTL image size.
'H') # number of inclusion proof entries.
def __init__(self, data=None):
"""Initializes a new AftlImageHeader object.
Arguments:
data: If not None, must be a bytearray of size |SIZE|.
Raises:
AftlError: If invalid structure for AftlImageHeader.
"""
assert struct.calcsize(self.FORMAT_STRING) == self.SIZE
if data:
(self.magic, self.required_icp_version_major,
self.required_icp_version_minor, self.aftl_image_size,
self.icp_count) = struct.unpack(self.FORMAT_STRING, data)
else:
self.magic = self.MAGIC
self.required_icp_version_major = avbtool.AVB_VERSION_MAJOR
self.required_icp_version_minor = avbtool.AVB_VERSION_MINOR
self.aftl_image_size = self.SIZE
self.icp_count = 0
if not self.is_valid():
raise AftlError('Invalid structure for AftlImageHeader.')
def encode(self):
"""Serializes the AftlImageHeader |SIZE| to bytes.
Returns:
The encoded AftlImageHeader as bytes.
Raises:
AftlError: If invalid structure for AftlImageHeader.
"""
if not self.is_valid():
raise AftlError('Invalid structure for AftlImageHeader')
return struct.pack(self.FORMAT_STRING, self.magic,
self.required_icp_version_major,
self.required_icp_version_minor,
self.aftl_image_size,
self.icp_count)
def is_valid(self):
"""Ensures that values in the AftlImageHeader are sane.
Returns:
True if the values in the AftlImageHeader are sane, False otherwise.
"""
if self.magic != AftlImageHeader.MAGIC:
sys.stderr.write(
'AftlImageHeader: magic value mismatch: {}\n'
.format(repr(self.magic)))
return False
if self.required_icp_version_major > avbtool.AVB_VERSION_MAJOR:
sys.stderr.write('AftlImageHeader: major version mismatch: {}\n'.format(
self.required_icp_version_major))
return False
if self.required_icp_version_minor > avbtool.AVB_VERSION_MINOR:
sys.stderr.write('AftlImageHeader: minor version mismatch: {}\n'.format(
self.required_icp_version_minor))
return False
if self.aftl_image_size < self.SIZE:
sys.stderr.write('AftlImageHeader: Invalid AFTL image size: {}\n'.format(
self.aftl_image_size))
return False
if self.icp_count < 0 or self.icp_count > 65535:
sys.stderr.write(
'AftlImageHeader: ICP entry count out of range: {}\n'.format(
self.icp_count))
return False
return True
def print_desc(self, o):
"""Print the AftlImageHeader.
Arguments:
o: The object to write the output to.
"""
o.write(' AFTL image header:\n')
i = ' ' * 4
fmt = '{}{:25}{}\n'
o.write(fmt.format(i, 'Major version:', self.required_icp_version_major))
o.write(fmt.format(i, 'Minor version:', self.required_icp_version_minor))
o.write(fmt.format(i, 'Image size:', self.aftl_image_size))
o.write(fmt.format(i, 'ICP entries count:', self.icp_count))
class AftlIcpEntry(object):
"""A class for the transparency log inclusion proof entries.
The data that represents each of the components of the ICP entry are stored
immediately following the ICP entry header. The format is log_url,
SignedLogRoot, and inclusion proof hashes.
Attributes:
log_url_size: Length of the string representing the transparency log URL.
leaf_index: Leaf index in the transparency log representing this entry.
log_root_descriptor_size: Size of the transparency log's SignedLogRoot.
fw_info_leaf_size: Size of the FirmwareInfo leaf passed to the log.
log_root_sig_size: Size in bytes of the log_root_signature
proof_hash_count: Number of hashes comprising the inclusion proof.
inc_proof_size: The total size of the inclusion proof, in bytes.
log_url: The URL for the transparency log that generated this inclusion
proof.
log_root_descriptor: The data comprising the signed tree head structure.
fw_info_leaf: The data comprising the FirmwareInfo leaf.
log_root_signature: The data comprising the log root signature.
proofs: The hashes comprising the inclusion proof.
"""
SIZE = 27 # The size of the structure, in bytes
FORMAT_STRING = ('!L' # transparency log server url size
'Q' # leaf index
'L' # log root descriptor size
'L' # firmware info leaf size
'H' # log root signature size
'B' # number of hashes in the inclusion proof
'L') # size of the inclusion proof in bytes
# These are used to capture the log_url, log_root_descriptor,
# fw_info leaf, log root signature, and the proofs elements for the
# encode function.
def __init__(self, data=None):
"""Initializes a new ICP entry object.
Arguments:
data: If not None, must be a bytearray of size >= |SIZE|.
Raises:
AftlError: If data does not represent a well-formed AftlIcpEntry.
"""
# Assert the header structure is of a sane size.
assert struct.calcsize(self.FORMAT_STRING) == self.SIZE
if data:
# Deserialize the header from the data.
(self._log_url_size_expected,
self.leaf_index,
self._log_root_descriptor_size_expected,
self._fw_info_leaf_size_expected,
self._log_root_sig_size_expected,
self._proof_hash_count_expected,
self._inc_proof_size_expected) = struct.unpack(self.FORMAT_STRING,
data[0:self.SIZE])
# Deserialize ICP entry components from the data.
expected_format_string = '{}s{}s{}s{}s{}s'.format(
self._log_url_size_expected,
self._log_root_descriptor_size_expected,
self._fw_info_leaf_size_expected,
self._log_root_sig_size_expected,
self._inc_proof_size_expected)
(log_url, log_root_descriptor_bytes, fw_info_leaf_bytes,
self.log_root_signature, proof_bytes) = struct.unpack(
expected_format_string, data[self.SIZE:self.get_expected_size()])
self.log_url = log_url.decode('ascii')
self.log_root_descriptor = TrillianLogRootDescriptor(
log_root_descriptor_bytes)
self.fw_info_leaf = FirmwareInfoLeaf(fw_info_leaf_bytes)
self.proofs = []
if self._proof_hash_count_expected > 0:
proof_idx = 0
hash_size = (self._inc_proof_size_expected
// self._proof_hash_count_expected)
for _ in range(self._proof_hash_count_expected):
proof = proof_bytes[proof_idx:(proof_idx+hash_size)]
self.proofs.append(proof)
proof_idx += hash_size
else:
self.leaf_index = 0
self.log_url = ''
self.log_root_descriptor = TrillianLogRootDescriptor()
self.fw_info_leaf = FirmwareInfoLeaf()
self.log_root_signature = b''
self.proofs = []
if not self.is_valid():
raise AftlError('Invalid structure for AftlIcpEntry')
@property
def log_url_size(self):
"""Gets the size of the log_url attribute."""
if hasattr(self, 'log_url'):
return len(self.log_url)
return self._log_url_size_expected
@property
def log_root_descriptor_size(self):
"""Gets the size of the log_root_descriptor attribute."""
if hasattr(self, 'log_root_descriptor'):
return self.log_root_descriptor.get_expected_size()
return self._log_root_descriptor_size_expected
@property
def fw_info_leaf_size(self):
"""Gets the size of the fw_info_leaf attribute."""
if hasattr(self, 'fw_info_leaf'):
return self.fw_info_leaf.get_expected_size()
return self._fw_info_leaf_size_expected
@property
def log_root_sig_size(self):
"""Gets the size of the log_root signature."""
if hasattr(self, 'log_root_signature'):
return len(self.log_root_signature)
return self._log_root_sig_size_expected
@property
def proof_hash_count(self):
"""Gets the number of proof hashes."""
if hasattr(self, 'proofs'):
return len(self.proofs)
return self._proof_hash_count_expected
@property
def inc_proof_size(self):
"""Gets the total size of the proof hashes in bytes."""
if hasattr(self, 'proofs'):
result = 0
for proof in self.proofs:
result += len(proof)
return result
return self._inc_proof_size_expected
def verify_icp(self, transparency_log_pub_key):
"""Verifies the contained inclusion proof given the public log key.
Arguments:
transparency_log_pub_key: The path to the trusted public key for the log.
Returns:
True if the calculated signature matches AftlIcpEntry's. False otherwise.
"""
if not transparency_log_pub_key:
return False
leaf_hash = rfc6962_hash_leaf(self.fw_info_leaf.encode())
calc_root = root_from_icp(self.leaf_index,
self.log_root_descriptor.tree_size,
self.proofs,
leaf_hash)
if ((calc_root == self.log_root_descriptor.root_hash) and
check_signature(
self.log_root_descriptor.encode(),
self.log_root_signature,
transparency_log_pub_key)):
return True
return False
def verify_vbmeta_image(self, vbmeta_image, transparency_log_pub_key):
"""Verify the inclusion proof for the given VBMeta image.
Arguments:
vbmeta_image: A bytearray with the VBMeta image.
transparency_log_pub_key: File path to the PEM file containing the trusted
transparency log public key.
Returns:
True if the inclusion proof validates and the vbmeta hash of the given
VBMeta image matches the one in the fw_info_leaf; otherwise False.
"""
if not vbmeta_image:
return False
# Calculate the hash of the vbmeta image.
vbmeta_hash = hashlib.sha256(vbmeta_image).digest()
# Validates the inclusion proof and then compare the calculated vbmeta_hash
# against the one in the inclusion proof.
return (self.verify_icp(transparency_log_pub_key)
and self.fw_info_leaf.vbmeta_hash == vbmeta_hash)
def encode(self):
"""Serializes the header |SIZE| and data to a bytearray().
Returns:
A bytearray() with the encoded header.
Raises:
AftlError: If invalid entry structure.
"""
proof_bytes = bytearray()
if not self.is_valid():
raise AftlError('Invalid AftlIcpEntry structure')
expected_format_string = '{}{}s{}s{}s{}s{}s'.format(
self.FORMAT_STRING,
self.log_url_size,
self.log_root_descriptor_size,
self.fw_info_leaf_size,
self.log_root_sig_size,
self.inc_proof_size)
for proof in self.proofs:
proof_bytes.extend(proof)
return struct.pack(expected_format_string,
self.log_url_size, self.leaf_index,
self.log_root_descriptor_size, self.fw_info_leaf_size,
self.log_root_sig_size, self.proof_hash_count,
self.inc_proof_size, self.log_url.encode('ascii'),
self.log_root_descriptor.encode(),
self.fw_info_leaf.encode(),
self.log_root_signature,
proof_bytes)
def translate_response(self, log_url, afi_response):
"""Translates an AddFirmwareInfoResponse object to an AftlIcpEntry.
Arguments:
log_url: String representing the transparency log URL.
afi_response: The AddFirmwareResponse object to translate.
"""
self.log_url = log_url
# Deserializes from AddFirmwareInfoResponse.
self.leaf_index = afi_response.fw_info_proof.proof.leaf_index
self.log_root_descriptor = TrillianLogRootDescriptor(
afi_response.fw_info_proof.sth.log_root)
self.fw_info_leaf = FirmwareInfoLeaf(afi_response.fw_info_leaf)
self.log_root_signature = afi_response.fw_info_proof.sth.log_root_signature
self.proofs = afi_response.fw_info_proof.proof.hashes
def get_expected_size(self):
"""Gets the expected size of the full entry out of the header.
Returns:
The expected size of the AftlIcpEntry from the header.
"""
return (self.SIZE + self.log_url_size + self.log_root_descriptor_size +
self.fw_info_leaf_size + self.log_root_sig_size +
self.inc_proof_size)
def is_valid(self):
"""Ensures that values in an AftlIcpEntry structure are sane.
Returns:
True if the values in the AftlIcpEntry are sane, False otherwise.
"""
if self.leaf_index < 0:
sys.stderr.write('ICP entry: leaf index out of range: '
'{}.\n'.format(self.leaf_index))
return False
if (not self.log_root_descriptor or
not isinstance(self.log_root_descriptor, TrillianLogRootDescriptor) or
not self.log_root_descriptor.is_valid()):
sys.stderr.write('ICP entry: invalid TrillianLogRootDescriptor.\n')
return False
if (not self.fw_info_leaf or
not isinstance(self.fw_info_leaf, FirmwareInfoLeaf)):
sys.stderr.write('ICP entry: invalid FirmwareInfo.\n')
return False
return True
def print_desc(self, o):
"""Print the ICP entry.
Arguments:
o: The object to write the output to.
"""
i = ' ' * 4
fmt = '{}{:25}{}\n'
o.write(fmt.format(i, 'Transparency Log:', self.log_url))
o.write(fmt.format(i, 'Leaf index:', self.leaf_index))
o.write(' ICP hashes: ')
for i, proof_hash in enumerate(self.proofs):
if i != 0:
o.write(' ' * 29)
o.write('{}\n'.format(proof_hash.hex()))
self.log_root_descriptor.print_desc(o)
self.fw_info_leaf.print_desc(o)
class TrillianLogRootDescriptor(object):
"""A class representing the Trillian log_root descriptor.
Taken from Trillian definitions:
https://github.com/google/trillian/blob/master/trillian.proto#L255
Attributes:
version: The version number of the descriptor. Currently only version=1 is
supported.
tree_size: The size of the tree.
root_hash_size: The size of the root hash in bytes. Valid values are between
0 and 128.
root_hash: The root hash as bytearray().
timestamp: The timestamp in nanoseconds.
revision: The revision number as long.
metadata_size: The size of the metadata in bytes. Valid values are between
0 and 65535.
metadata: The metadata as bytearray().
"""
FORMAT_STRING_PART_1 = ('!H' # version
'Q' # tree_size
'B' # root_hash_size
)
FORMAT_STRING_PART_2 = ('!Q' # timestamp
'Q' # revision
'H' # metadata_size
)
def __init__(self, data=None):
"""Initializes a new TrillianLogRoot descriptor."""
if data:
# Parses first part of the log_root descriptor.
data_length = struct.calcsize(self.FORMAT_STRING_PART_1)
(self.version, self.tree_size, self.root_hash_size) = struct.unpack(
self.FORMAT_STRING_PART_1, data[0:data_length])
data = data[data_length:]
# Parses the root_hash bytes if the size indicates existance.
if self.root_hash_size > 0:
self.root_hash = data[0:self.root_hash_size]
data = data[self.root_hash_size:]
else:
self.root_hash = b''
# Parses second part of the log_root descriptor.
data_length = struct.calcsize(self.FORMAT_STRING_PART_2)
(self.timestamp, self.revision, self.metadata_size) = struct.unpack(
self.FORMAT_STRING_PART_2, data[0:data_length])
data = data[data_length:]
# Parses the metadata if the size indicates existance.
if self.metadata_size > 0:
self.metadata = data[0:self.metadata_size]
else:
self.metadata = b''
else:
self.version = 1
self.tree_size = 0
self.root_hash_size = 0
self.root_hash = b''
self.timestamp = 0
self.revision = 0
self.metadata_size = 0
self.metadata = b''
if not self.is_valid():
raise AftlError('Invalid structure for TrillianLogRootDescriptor.')
def get_expected_size(self):
"""Calculates the expected size of the TrillianLogRootDescriptor.
Returns:
The expected size of the TrillianLogRootDescriptor.
"""
return (struct.calcsize(self.FORMAT_STRING_PART_1) + self.root_hash_size +
struct.calcsize(self.FORMAT_STRING_PART_2) + self.metadata_size)
def encode(self):
"""Serializes the TrillianLogDescriptor to a bytearray().
Returns:
A bytearray() with the encoded header.
Raises:
AftlError: If invalid entry structure.
"""
if not self.is_valid():
raise AftlError('Invalid structure for TrillianLogRootDescriptor.')
expected_format_string = '{}{}s{}{}s'.format(
self.FORMAT_STRING_PART_1,
self.root_hash_size,
self.FORMAT_STRING_PART_2[1:],
self.metadata_size)
return struct.pack(expected_format_string,
self.version, self.tree_size, self.root_hash_size,
self.root_hash, self.timestamp, self.revision,
self.metadata_size, self.metadata)
def is_valid(self):
"""Ensures that values in the descritor are sane.
Returns:
True if the values are sane; otherwise False.
"""
cls = self.__class__.__name__
if self.version != 1:
sys.stderr.write('{}: Bad version value {}.\n'.format(cls, self.version))
return False
if self.tree_size < 0:
sys.stderr.write('{}: Bad tree_size value {}.\n'.format(cls,
self.tree_size))
return False
if self.root_hash_size < 0 or self.root_hash_size > 128:
sys.stderr.write('{}: Bad root_hash_size value {}.\n'.format(
cls, self.root_hash_size))
return False
if len(self.root_hash) != self.root_hash_size:
sys.stderr.write('{}: root_hash_size {} does not match with length of '
'root_hash {}.\n'.format(cls, self.root_hash_size,
len(self.root_hash)))
return False
if self.timestamp < 0:
sys.stderr.write('{}: Bad timestamp value {}.\n'.format(cls,
self.timestamp))
return False
if self.revision < 0:
sys.stderr.write('{}: Bad revision value {}.\n'.format(cls,
self.revision))
return False
if self.metadata_size < 0 or self.metadata_size > 65535:
sys.stderr.write('{}: Bad metadatasize value {}.\n'.format(
cls, self.metadata_size))
return False
if len(self.metadata) != self.metadata_size:
sys.stderr.write('{}: metadata_size {} does not match with length of'
'metadata {}.\n'.format(cls, self.metadata_size,
len(self.metadata)))
return False
return True
def print_desc(self, o):
"""Print the TrillianLogRootDescriptor.
Arguments:
o: The object to write the output to.
"""
o.write(' Log Root Descriptor:\n')
i = ' ' * 6
fmt = '{}{:23}{}\n'
o.write(fmt.format(i, 'Version:', self.version))
o.write(fmt.format(i, 'Tree size:', self.tree_size))
o.write(fmt.format(i, 'Root hash size:', self.root_hash_size))
if self.root_hash_size > 0:
o.write(fmt.format(i, 'Root hash:', self.root_hash.hex()))
o.write(fmt.format(i, 'Timestamp (ns):', self.timestamp))
o.write(fmt.format(i, 'Revision:', self.revision))
o.write(fmt.format(i, 'Metadata size:', self.metadata_size))
if self.metadata_size > 0:
o.write(fmt.format(i, 'Metadata:', self.metadata.hex()))
class FirmwareInfoLeaf(object):
"""A class representing the FirmwareInfo leaf.
AFTL returns the fw_info_leaf as a JSON blob and this class is able to
parse the blog and provide necessary attributes needed for validation.
Attributes:
vbmeta_hash: This is the SHA256 hash of vbmeta.
version_incremental: Subcomponent of the build fingerprint as defined at
https://source.android.com/compatibility/android-cdd#3_2_2_build_parameters.
For example, a Pixel device with the following build fingerprint
google/crosshatch/crosshatch:9/PQ3A.190605.003/5524043:user/release-keys,
would have 5524043 for the version incremental.
platform_key: Public key of the platform. This is the same key used to sign
the vbmeta.
manufacturer_key_hash: SHA256 of the manufacturer public key (DER-encoded,
x509 subjectPublicKeyInfo format). The public key MUST already be in the
list of root keys known and trusted by the AFTL.
description: Free form description field. It can be used to annotate this
message with further context on the build (e.g., carrier specific build).
"""
def __init__(self, data=None):
"""Initializes a new FirmwareInfoLeaf descriptor."""
if data:
# We have to preserve the original fw_info_leaf bytes in order to preserve
# hash equivalence with what is stored in the Trillian log and matches up
# with the proofs.
self._fw_info_leaf_bytes = data
# Deserialize the JSON blob and keep only the FirmwareInfo parts.
try:
fw_info_leaf = json.loads(self._fw_info_leaf_bytes)
self._fw_info_leaf_dict = (
fw_info_leaf['Value']['FwInfo']['info']['info'])
except (ValueError, KeyError) as e:
raise AftlError('Invalid structure for FirmwareInfoLeaf: {}'.format(e))
else:
self._fw_info_leaf_bytes = b''
self._fw_info_leaf_dict = dict()
if not self.is_valid():
raise AftlError('Invalid structure for FirmwareInfoLeaf.')
@property
def vbmeta_hash(self):
"""Gets the vbmeta_hash attribute."""
return self._lookup_base64_attribute('vbmeta_hash')
@property
def version_incremental(self):
"""Gets the version_incremental attribute."""
return self._fw_info_leaf_dict.get('version_incremental')
@property
def platform_key(self):
"""Gets the platform key attribute."""
return self._lookup_base64_attribute('platform_key')
@property
def manufacturer_key_hash(self):
"""Gets the manufacturer_key_hash attribute."""
return self._lookup_base64_attribute('manufacturer_key_hash')
@property
def description(self):
"""Gets the description attribute."""
return self._fw_info_leaf_dict.get('description')
def _lookup_base64_attribute(self, key):
"""Looks up an attribute that is Base64 encoded and decodes it.
Arguments:
key: The name of the attribute to look up.
Returns:
The attribute value or None if not defined.
"""
result = self._fw_info_leaf_dict.get(key)
if result:
result = base64.b64decode(result)
return result
def get_expected_size(self):
"""Gets the expected size of the JSON-serialized FirmwareInfoLeaf.
Returns:
The expected size of the FirmwareInfo leaf in byte or 0 if not initalized.
"""
if not self._fw_info_leaf_bytes:
return 0
return len(self._fw_info_leaf_bytes)
def encode(self):
"""Serializes the FirmwareInfoLeaf.
Returns:
A bytearray() with the JSON-serialized FirmwareInfoLeaf.
"""
return self._fw_info_leaf_bytes
def is_valid(self):
"""Ensures that values in the descritor are sane.
Returns:
True if the values are sane; otherwise False.
"""
# Checks that the decode fw_info_leaf at max contains values defined in the
# FirmwareInfo proto buf.
expected_fields = set(aftl_pb2.FirmwareInfo()
.DESCRIPTOR.fields_by_name.keys())
actual_fields = set(self._fw_info_leaf_dict.keys())
if actual_fields.issubset(expected_fields):
return True
return False
def print_desc(self, o):
"""Print the FirmwareInfoLeaf.
Arguments:
o: The object to write the output to.
"""
o.write(' Firmware Info Leaf:\n')
# The order of the fields is based on the definition in
# proto.aftl_pb2.FirmwareInfo.
i = ' ' * 6
fmt = '{}{:23}{}\n'
if self.vbmeta_hash:
o.write(fmt.format(i, 'VBMeta hash:', self.vbmeta_hash.hex()))
if self.version_incremental:
o.write(fmt.format(i, 'Version incremental:', self.version_incremental))
if self.platform_key:
o.write(fmt.format(i, 'Platform key:', self.platform_key))
if self.manufacturer_key_hash:
o.write(fmt.format(i, 'Manufacturer key hash:',
self.manufacturer_key_hash.hex()))
if self.description:
o.write(fmt.format(i, 'Description:', self.description))
class AftlImage(object):
"""A class for the AFTL image, which contains the transparency log ICPs.
This encapsulates an AFTL ICP section with all information required to
validate an inclusion proof.
Attributes:
image_header: A header for the section.
icp_entries: A list of AftlIcpEntry objects representing the inclusion
proofs.
"""
def __init__(self, data=None):
"""Initializes a new AftlImage section.
Arguments:
data: If not None, must be a bytearray representing an AftlImage.
Raises:
AftlError: If the data does not represent a well-formed AftlImage.
"""
if data:
image_header_bytes = data[0:AftlImageHeader.SIZE]
self.image_header = AftlImageHeader(image_header_bytes)
if not self.image_header.is_valid():
raise AftlError('Invalid AftlImageHeader.')
icp_count = self.image_header.icp_count
# Jump past the header for entry deserialization.
icp_index = AftlImageHeader.SIZE
# Validate each entry.
self.icp_entries = []
# add_icp_entry() updates entries and header, so set header count to
# compensate.
self.image_header.icp_count = 0
for i in range(icp_count):
# Get the entry header from the AftlImage.
cur_icp_entry = AftlIcpEntry(data[icp_index:])
cur_icp_entry_size = cur_icp_entry.get_expected_size()
# Now validate the entry structure.
if not cur_icp_entry.is_valid():
raise AftlError('Validation of ICP entry {} failed.'.format(i))
self.add_icp_entry(cur_icp_entry)
icp_index += cur_icp_entry_size
else:
self.image_header = AftlImageHeader()
self.icp_entries = []
if not self.is_valid():
raise AftlError('Invalid AftlImage.')
def add_icp_entry(self, icp_entry):
"""Adds a new AftlIcpEntry to the AftlImage, updating fields as needed.
Arguments:
icp_entry: An AftlIcpEntry structure.
"""
self.icp_entries.append(icp_entry)
self.image_header.icp_count += 1
self.image_header.aftl_image_size += icp_entry.get_expected_size()
def verify_vbmeta_image(self, vbmeta_image, transparency_log_pub_keys):
"""Verifies the contained inclusion proof given the public log key.
Arguments:
vbmeta_image: The vbmeta_image that should be verified against the