-
Notifications
You must be signed in to change notification settings - Fork 3
/
primitives.py
1754 lines (1446 loc) · 70.8 KB
/
primitives.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
import hashlib
import hmac
import os
from Crypto.Cipher import AES
from Crypto.Hash import keccak
from Crypto.PublicKey import RSA
from boofuzz.blocks import Request
from boofuzz.fuzzable import Fuzzable
from boofuzz.fuzzable_block import FuzzableBlock
from boofuzz.primitives import Static
from .constants import CONSTANTS
from .helpers import swap_endianness_and_bits
from .models import AESKey, FuzzPosition, Series7KeyFile, UltraScaleKeyFile
class SyncWord(Static):
"""Primitive for a sync word.
https://docs.xilinx.com/r/en-US/ug470_7Series_Config
Table 5-3, page 75
"""
_id = 0
def __init__(self, *args, **kwargs):
# Append id to name because boofuzz needs all primitives to have an individual name.
SyncWord._id += 1
super(SyncWord, self).__init__(
name=f"SyncWord{SyncWord._id}",
default_value=b"\xAA\x99\x55\x66",
*args,
**kwargs,
)
class NOP(Static):
"""Primitive for a NOP command.
https://docs.xilinx.com/r/en-US/ug470_7Series_Config
Table 5-21, page 100
"""
_id = 0
def __init__(self, nop_count: int = 1, *args, **kwargs):
# Append id to name because boofuzz needs all primitives to have an individual name.
NOP._id += 1
super(NOP, self).__init__(
name=f"NOP{NOP._id}",
default_value=b"\x20\x00\x00\x00" * nop_count,
*args,
**kwargs,
)
class Type1Packet(Static):
"""Primitive for a Type 1 Packet.
https://docs.xilinx.com/r/en-US/ug470_7Series_Config
Table 5-20, page 100
"""
def __init__(
self,
name: str,
opcode: str,
register_address: int,
word_count: int,
*args,
**kwargs,
):
if opcode != "read" and opcode != "write":
raise ValueError('opcode has to be "read" or "write"')
if register_address < 0 or register_address > 31:
raise ValueError("register_address has to be >= 0 and <= 31")
# 2**11 = 2048
if word_count < 0 or word_count > 2047:
raise ValueError("word_count has to be >= 0 and <= 2047")
# Header Type
value = 0b001
# Opcode
value <<= 2
if opcode == "read":
value |= 0b01
else:
value |= 0b10
# Register Address
value <<= 14
value |= register_address
# Reserved
value <<= 2
# Word Count
value <<= 11
value |= word_count
super(Type1Packet, self).__init__(
name=name, default_value=value.to_bytes(4, "big"), *args, **kwargs
)
class Type1ReadPacket(Type1Packet):
"""Primitive for a Type 1 Packet with the "Read" (01) opcode."""
def __init__(
self, name: str, register_address: int, word_count: int = 1, *args, **kwargs
):
super(Type1ReadPacket, self).__init__(
name=name,
opcode="read",
register_address=register_address,
word_count=word_count,
*args,
**kwargs,
)
class Type1WritePacket(Type1Packet):
"""Primitive for a Type 1 Packet with the "Write" (10) opcode."""
def __init__(
self, name: str, register_address: int, word_count: int = 1, *args, **kwargs
):
super(Type1WritePacket, self).__init__(
name=name,
opcode="write",
register_address=register_address,
word_count=word_count,
*args,
**kwargs,
)
class Type2Packet(Static):
"""Primitive for a Type 2 Packet.
https://docs.xilinx.com/r/en-US/ug470_7Series_Config
Table 5-22, page 101
"""
def __init__(self, name: str, opcode: str, word_count: int, *args, **kwargs):
if opcode != "read" and opcode != "write":
raise ValueError('opcode has to be "read" or "write"')
# 2**27 = 134217728
if word_count < 0 or word_count > 134217727:
raise ValueError("word_count has to be >= 0 and <= 134217727")
# Header Type
value = 0b010
# Opcode
value <<= 2
if opcode == "read":
value |= 0b01
else:
value |= 0b10
# Word Count
value <<= 27
value |= word_count
super(Type2Packet, self).__init__(
name=name, default_value=value.to_bytes(4, "big"), *args, **kwargs
)
class Type2ReadPacket(Type2Packet):
"""Primitive for a Type 2 Packet with the "Read" (01) opcode."""
def __init__(self, name: str, word_count: int, *args, **kwargs):
super(Type2ReadPacket, self).__init__(
name=name, opcode="read", word_count=word_count, *args, **kwargs
)
class Type2WritePacket(Type2Packet):
"""Primitive for a Type 2 Packet with the "Write" (10) opcode."""
def __init__(self, name: str, word_count: int, *args, **kwargs):
super(Type2WritePacket, self).__init__(
name=name, opcode="write", word_count=word_count, *args, **kwargs
)
class BitstreamWord(Fuzzable):
"""Custom Fuzzable which represents a single 32 bit long bitstream word.
https://boofuzz.readthedocs.io/en/stable/user/protocol-definition.html#making-your-own-block-primitive
Static_bits is the base value in which fuzzed bits have to be 0.
All set bits in fuzzing_mask are fuzzed by generating all possible submasks.
If fuzzing_mask is a list of masks all possible submasks for every mask are generated.
If the fuzzing_mask is set to zero only the static bits are returned.
Example:
static_bits = 0x28 00 e0 01 = 0b00101000 00000000 11100000 00000001
fuzzing_mask = 0x00 00 00 0e = 0b00000000 00000000 00000000 00001110
=>
mutation 1 = 0x28 00 e0 0f = 0b00101000 00000000 11100000 00001111
mutation 2 = 0x28 00 e0 0d = 0b00101000 00000000 11100000 00001101
mutation 3 = 0x28 00 e0 0b = 0b00101000 00000000 11100000 00001011
mutation 4 = 0x28 00 e0 09 = 0b00101000 00000000 11100000 00001001
mutation 5 = 0x28 00 e0 07 = 0b00101000 00000000 11100000 00000111
mutation 6 = 0x28 00 e0 05 = 0b00101000 00000000 11100000 00000101
mutation 7 = 0x28 00 e0 03 = 0b00101000 00000000 11100000 00000011
mutation 8 = 0x28 00 e0 01 = 0b00101000 00000000 11100000 00000001
"""
def __init__(
self,
name: str,
static_bits: int,
fuzzing_mask: int | list[int],
default_value: bytes = None,
fuzz_values: list[bytes] = None,
*args,
**kwargs,
):
if static_bits < 0 or static_bits >= 0x100000000:
raise ValueError("static_bits has to be >= 0 and < 0x100000000")
if not isinstance(fuzzing_mask, list):
fuzzing_mask_list = [fuzzing_mask]
else:
fuzzing_mask_list = fuzzing_mask
for fuzzing_mask in fuzzing_mask_list:
if fuzzing_mask < 0 or fuzzing_mask >= 0x100000000:
raise ValueError("fuzzing_mask has to be >= 0 and < 0x100000000")
if static_bits & fuzzing_mask != 0:
raise ValueError(
"static_bits and fuzzing_mask can not have set bits at the same positions"
)
self._static_bits = static_bits
self._fuzzing_mask_list = fuzzing_mask_list
super(BitstreamWord, self).__init__(
name=name,
default_value=default_value,
fuzzable=True,
fuzz_values=fuzz_values,
*args,
**kwargs,
)
def mutations(self, default_value):
# Generate all submasks for each fuzzing mask and
# yield the result of a bitwise OR of the current submask and the static bits.
# https://cp-algorithms.com/algebra/all-submasks.html
for fuzzing_mask in self._fuzzing_mask_list:
sub_mask = fuzzing_mask
while sub_mask > 0:
yield self._static_bits | sub_mask
sub_mask = (sub_mask - 1) & fuzzing_mask
# Yield the static bits as an extra mutation because
# the algorithm above does not consider the submask equal to zero.
yield self._static_bits
def encode(self, value, mutation_context):
if isinstance(value, int):
return value.to_bytes(4, "big")
elif isinstance(value, bytes):
return value
else:
return b""
def num_mutations(self, default_value):
return (
sum(
[
2 ** fuzzing_mask.bit_count()
for fuzzing_mask in self._fuzzing_mask_list
]
)
# Count the submask equal to zero only once.
- len(self._fuzzing_mask_list)
+ 1
)
class FuzzedBitstream(Fuzzable):
"""Custom Fuzzable which will apply the given fuzzing masks to the given positions of the given bitstream.
https://boofuzz.readthedocs.io/en/stable/user/protocol-definition.html#making-your-own-block-primitive
file_name is the name of the bitstream file that will be mutated. The bitstream has to be placed in BITSTREAMS_DIR.
All set bits in fuzzing_mask are fuzzed by generating all possible submasks.
If fuzzing_mask is a list of masks all possible submasks for every mask are generated.
With the fuzzing_position argument we can define to which positions of the bitstream the fuzzing masks will be applied.
It is possible to only give a starting position (first position is zero) and the generated submasks will be applied to
the 32-bit word starting at this address and all following words.
Otherwise we can pass a single FuzzPosition object or a list of FuzzPosition objects as fuzzing_position.
The index_start parameter of the FuzzPosition specifies the first byte of the first 32-bit word that will be fuzzed.
The word_count parameter defines how many 32-bit words will be fuzzed.
If we pass an empty list as fuzzing_position only the original bitstream will be returned.
Examples:
bitstream = 00000000 00000000 FFFFFFFF
fuzzing_mask = [0x00000001, 0x00000010]
Example 1:
fuzzing_position = 0
=>
position: 0 1 2 3 4 5 6 7 8 9 ...
mutation 1 = 00000001 00000000 FFFFFFFF (word at position 0, first mask)
mutation 2 = 00000010 00000000 FFFFFFFF (word at position 0, second mask)
mutation 3 = 00000000 00000001 FFFFFFFF (word at position 4, first mask)
mutation 4 = 00000000 00000010 FFFFFFFF (word at position 4, second mask)
mutation 5 = 00000000 00000000 FFFFFFFE (word at position 8, first mask)
mutation 6 = 00000000 00000000 FFFFFFEF (word at position 8, second mask)
mutation 7 = 00000000 00000000 FFFFFFFF (original bitstream)
Example 2:
fuzzing_position = 7
=>
position: 0 1 2 3 4 5 6 7 8 9 ...
mutation 1 = 00000000 00000000 FFFFFEFF (word at position 7, first mask)
mutation 2 = 00000000 00000000 FFFFEFFF (word at position 7, second mask)
mutation 3 = 00000000 00000000 FFFFFFFF (original bitstream)
Example 3:
fuzzing_position = FuzzPosition(3, 2)
=>
position: 0 1 2 3 4 5 6 7 8 9 ...
mutation 1 = 00000000 00000100 FFFFFFFF (word at position 3, first mask)
mutation 2 = 00000000 00001000 FFFFFFFF (word at position 3, second mask)
mutation 3 = 00000000 00000000 FFFFFEFF (word at position 7, first mask)
mutation 4 = 00000000 00000000 FFFFEFFF (word at position 7, second mask)
mutation 5 = 00000000 00000000 FFFFFFFF (original bitstream)
Example 4:
fuzzing_position = [FuzzPosition(0, 2), FuzzPosition(3, 1)]
=>
position: 0 1 2 3 4 5 6 7 8 9 ...
mutation 1 = 00000001 00000000 FFFFFFFF (word at position 0, first mask)
mutation 2 = 00000010 00000000 FFFFFFFF (word at position 0, second mask)
mutation 3 = 00000000 00000001 FFFFFFFF (word at position 4, first mask)
mutation 4 = 00000000 00000010 FFFFFFFF (word at position 4, second mask)
mutation 5 = 00000000 00000100 FFFFFFFF (word at position 3, first mask)
mutation 6 = 00000000 00001000 FFFFFFFF (word at position 3, second mask)
mutation 7 = 00000000 00000000 FFFFFFFF (original bitstream)
"""
def __init__(
self,
name: str,
file_name: str,
fuzzing_mask: int | list[int],
fuzzing_position: int | FuzzPosition | list[FuzzPosition],
*args,
**kwargs,
):
with open(os.path.join(CONSTANTS.BITSTREAMS_DIR, file_name), "rb") as f:
self._bitstream = bytearray(f.read())
# If the bitstream starts with 0x0009 this indicates that the bitstream contains a bitstream header.
# This is usually the case if the bitstream has been generated by Vivado or other official tools by Xilinx.
# We cut the header because everything before the sync word is ignored by the configuration engine anyways.
if self._bitstream.startswith(b"\x00\x09"):
self._bitstream = self._bitstream[
self._bitstream.index(SyncWord().render()) :
]
self._bitstream_length = len(self._bitstream)
if self._bitstream_length % 4 != 0:
raise ValueError(
f'the length of the bitstream "{file_name}" must be a multiple of 4'
)
if not isinstance(fuzzing_mask, list):
fuzzing_mask_list = [fuzzing_mask]
else:
fuzzing_mask_list = fuzzing_mask
for fuzzing_mask in fuzzing_mask_list:
if fuzzing_mask < 0 or fuzzing_mask >= 0x100000000:
raise ValueError("fuzzing_mask has to be >= 0 and < 0x100000000")
self._fuzzing_mask_list = fuzzing_mask_list
if isinstance(fuzzing_position, int):
# Start from given position and fuzz all follwing words.
# Ignore bytes at the end that do not form a whole word.
fuzzing_position_list = [
FuzzPosition(
fuzzing_position, (self._bitstream_length - fuzzing_position) // 4
)
]
elif not isinstance(fuzzing_position, list):
fuzzing_position_list = [fuzzing_position]
else:
fuzzing_position_list = fuzzing_position
for fuzzing_position in fuzzing_position_list:
if (
fuzzing_position.index_start + fuzzing_position.word_count * 4
> self._bitstream_length
):
raise ValueError("fuzzing_position will exceed bitstream length")
self._fuzzing_position_list = fuzzing_position_list
super(FuzzedBitstream, self).__init__(
name=name,
default_value=None,
fuzzable=True,
fuzz_values=None,
*args,
**kwargs,
)
def mutations(self, default_value):
# This function works similar to the mutations function of the BitstreamWord primitive above.
# The difference is that we will always yield a complete bitstream.
# For all specified positions in this bitstream we will apply all generated submasks.
# Apply means XORing the current submask to the current position of the original bitstream.
for fuzzing_position in self._fuzzing_position_list:
for word_index in range(fuzzing_position.word_count):
# word_position is the first byte of the word at the currently fuzzed position.
word_position = fuzzing_position.index_start + word_index * 4
# Store the unmodiefied word at the currently fuzzed position.
original_word = self._bitstream[word_position : word_position + 4]
# Copy the original bitstream so we can modify it without losing the original.
mutated_bitstream = self._bitstream.copy()
for fuzzing_mask in self._fuzzing_mask_list:
sub_mask = fuzzing_mask
while sub_mask > 0:
sub_mask_bytes = sub_mask.to_bytes(4, "big")
# Apply the current submask to the currently fuzzed position.
for mask_index in range(4):
mutated_bitstream[word_position + mask_index] = (
original_word[mask_index] ^ sub_mask_bytes[mask_index]
)
yield mutated_bitstream
sub_mask = (sub_mask - 1) & fuzzing_mask
# Yield the unchanged bitstream as an extra mutation because
# the algorithm above does not consider the submask equal to zero.
yield self._bitstream
def encode(self, value, mutation_context):
if isinstance(value, bytearray):
return bytes(value)
else:
return b""
def num_mutations(self, default_value):
total_word_count = sum(
fuzzing_position.word_count
for fuzzing_position in self._fuzzing_position_list
)
return (
sum(
[
2 ** fuzzing_mask.bit_count() * total_word_count
for fuzzing_mask in self._fuzzing_mask_list
]
)
# Count the submask equal to zero only once.
- len(self._fuzzing_mask_list) * total_word_count
+ 1
)
class AlternatingWord(Fuzzable):
"""Custom Fuzzable that alternates between two values.
For the first test case, this primitive is rendered to value_a.
This primitive is not mutated and is statically rendered to value_a or value_b.
To generate test cases, a mutated primitive must be part of the request
(e.g., the Simple primitive or the BitstreamWord primitive).
https://boofuzz.readthedocs.io/en/stable/user/protocol-definition.html#making-your-own-block-primitive
"""
def __init__(self, name: str, value_a: int, value_b: int, *args, **kwargs):
if value_a < 0 or value_a >= 0x100000000:
raise ValueError("value_a has to be >= 0 and < 0x100000000")
if value_b < 0 or value_b >= 0x100000000:
raise ValueError("value_b has to be >= 0 and < 0x100000000")
self._value_a = value_a.to_bytes(4, "big")
self._value_b = value_b.to_bytes(4, "big")
self._current_mutation = None
self._return_value_a = False
super(AlternatingWord, self).__init__(
name=name,
default_value=self._value_a,
fuzzable=False,
fuzz_values=None,
*args,
**kwargs,
)
def encode(self, value, mutation_context):
# If the mutation changed, we are in a new test case and switch the returned value.
if self._current_mutation != mutation_context.mutations:
self._current_mutation = mutation_context.mutations
self._return_value_a = not self._return_value_a
if self._return_value_a:
return self._value_a
else:
return self._value_b
class AlternatingBitstream(Fuzzable):
"""Custom Fuzzable that alternates between two bitstreams.
file_name_a and file_name_b define the bitstreams in the bitstreams directory of the used board.
For the first test case, this primitive is rendered to bitstream_a.
This primitive is not mutated and is statically rendered to bitstream_ or bitstream_b.
To generate test cases, a mutated primitive must be part of the request
(e.g., the Simple primitive or the BitstreamWord primitive).
https://boofuzz.readthedocs.io/en/stable/user/protocol-definition.html#making-your-own-block-primitive
"""
def __init__(self, name: str, file_name_a: str, file_name_b: str, *args, **kwargs):
with open(os.path.join(CONSTANTS.BITSTREAMS_DIR, file_name_a), "rb") as f:
self._bitstream_a = bytes(f.read())
with open(os.path.join(CONSTANTS.BITSTREAMS_DIR, file_name_b), "rb") as f:
self._bitstream_b = bytes(f.read())
# If the bitstream starts with 0x0009 this indicates that the bitstream contains a bitstream header.
# This is usually the case if the bitstream has been generated by Vivado or other official tools by Xilinx.
# We cut the header because everything before the sync word is ignored by the configuration engine anyways.
if self._bitstream_a.startswith(b"\x00\x09"):
self._bitstream_a = self._bitstream_a[
self._bitstream_a.index(SyncWord().render()) :
]
if self._bitstream_b.startswith(b"\x00\x09"):
self._bitstream_b = self._bitstream_b[
self._bitstream_b.index(SyncWord().render()) :
]
self._return_bitstream_a = False
self._current_mutation = None
super(AlternatingBitstream, self).__init__(
name=name,
default_value=None,
fuzzable=False,
fuzz_values=None,
*args,
**kwargs,
)
def encode(self, value, mutation_context):
# If the mutation changed, we are in a new test case and switch the returned bitstream.
if self._current_mutation != mutation_context.mutations:
self._current_mutation = mutation_context.mutations
self._return_bitstream_a = not self._return_bitstream_a
if self._return_bitstream_a:
return self._bitstream_a
else:
return self._bitstream_b
class EncryptedSeries7Block(FuzzableBlock):
"""Custom FuzzableBlock which encrypts its child objects.
https://boofuzz.readthedocs.io/en/stable/user/protocol-definition.html#boofuzz.FuzzableBlock
The content of this block will be encrypted and authenticated in a way
that it can be loaded on a Xilinx 7-series FPGA without producing an error.
The content is encrypted by using AES-CBC and authenticated by a HMAC using SHA-256.
Additionally necessary, unencrypted commands will be added to the bitstream.
The block content must consist of multiple 32-bit words so that the length of the block (in bytes) is a multiple of 4.
The pad_child_data argument can be used to automatically pad the content of the block with NOPs to match the HMAC blocksize.
Either a key_file_name of a .nky file in the STATIC_DIR or individual values for aes_key, aes_iv, and hmac_key have to be provieded.
The enable_encryption argument can be used to disable the automatic activation of the encryption settings.
By default the DEC option in the CTL0 register is activated
and the efuse_key argument is used to decide if the AES key is read from BBRAM or eFUSE.
If enable_encryption is disabled the encryption commands have to be set manually
in the bitstream before the EncryptedSeries7Block primitive.
If the return_plaintext argument is enabled the block is rendered in its final structure but unencrypted.
"""
def __init__(
self,
name: str = None,
request: Request = None,
children=None,
pad_child_data: bool = False,
key_file_name: str = None,
aes_key: str = None,
aes_iv: str = None,
hmac_key: str = None,
enable_encryption: bool = True,
efuse_key: bool = False,
return_plaintext: bool = False,
*args,
**kwargs,
):
self._pad_child_data = pad_child_data
if key_file_name:
self._parse_series_7_key_file(key_file_name)
elif aes_key and aes_iv and hmac_key:
self._key_file = Series7KeyFile(
device=None,
aes_key=bytes.fromhex(aes_key),
aes_iv=bytes.fromhex(aes_iv),
hmac_key=bytes.fromhex(hmac_key),
)
else:
raise ValueError("missing key material")
self._hmac_key_ipad = bytes(byte ^ 0x36 for byte in self._key_file.hmac_key)
self._hmac_key_opad = bytes(byte ^ 0x5C for byte in self._hmac_key_ipad)
self._aes_iv_swapped = swap_endianness_and_bits(self._key_file.aes_iv)
self._enable_encryption = enable_encryption
self._efuse_key = efuse_key
self._return_plaintext = return_plaintext
super(EncryptedSeries7Block, self).__init__(
name=name, request=request, children=children, *args, **kwargs
)
def encode(self, value, mutation_context):
encrypted_data = self._get_encrypted_data(self.get_child_data(mutation_context))
unencrypted_commands = self._get_enable_encryption_commands()
unencrypted_commands += [
Type1WritePacket(name="write_to_cbc", register_address=11, word_count=4),
Static(name="aes_iv", default_value=self._key_file.aes_iv),
Type1WritePacket(name="write_to_unknown_register_26", register_address=26),
Static(
name="encrypted_data_length_in_words",
default_value=(len(encrypted_data) // 4).to_bytes(4, "big"),
),
]
unencrypted_data = b"".join(
primitive.render() for primitive in unencrypted_commands
)
# Add 16 NOPs as in an original encrypted bitstream.
# At least two of these NOPs are actually necessary.
final_nops = NOP(16).render()
return unencrypted_data + encrypted_data + final_nops
def _parse_series_7_key_file(self, key_file_name: str) -> Series7KeyFile:
"""Parse a .nky file for 7-series devices."""
device = None
aes_key = None
aes_iv = None
hmac_key = None
with open(os.path.join(CONSTANTS.STATIC_DIR, key_file_name)) as f:
lines = f.readlines()
for line in lines:
line = line.strip(";\n").split()
if line[0] == "Device":
device = line[1]
elif line[0] == "Key" and line[1] == "0":
aes_key = bytes.fromhex(line[2])
elif line[0] == "Key" and line[1] == "StartCBC":
aes_iv = bytes.fromhex(line[2])
elif line[0] == "Key" and line[1] == "HMAC":
hmac_key = bytes.fromhex(line[2])
if aes_key and aes_iv and hmac_key:
self._key_file = Series7KeyFile(device, aes_key, aes_iv, hmac_key)
else:
raise ValueError("error when parsing .nky file: missing key(s)")
def _get_encrypted_data(self, data: bytes) -> bytes:
"""Encrypt the given data in a format that is valid for Xilinx 7-series FPGAs."""
data_length = len(data)
# We can not encrypt less than one 32-bit word.
if data_length < 4:
raise ValueError("data_length has to be >= 4")
# We can only encrypt a multiple of 32-bit words.
if data_length % 4 != 0:
raise ValueError("data_length must be a multiple of 4")
if self._pad_child_data:
# Pad with NOPs so that the length of child_data is a multiple of the HMAC blocksize.
# The HMAC blocksize is 64 byte.
data += NOP((64 - data_length % 64) // 4).render()
data_length = len(data)
if data_length % 64 != 0:
raise ValueError(
"data_length has to be a multiple of the HMAC blocksize (16 words / 64 bytes / 512 bits)"
)
hmac_tag = hmac.new(self._hmac_key_ipad, data, hashlib.sha256).digest()
data_to_encrypt = (
self._key_file.hmac_key
+ b"\x36" * 32
+ data
+ b"\x80"
+ b"\x00" * 59
+ ((data_length + 64) * 8).to_bytes(4, "big") # In bits
+ b"\x00" * 256
+ self._hmac_key_opad
+ b"\x5C" * 32
+ b"\x00" * 32
+ b"\x80"
+ b"\x00" * 29
+ b"\x03\x00"
+ hmac_tag
)
if self._return_plaintext:
return data_to_encrypt
data_to_encrypt = swap_endianness_and_bits(data_to_encrypt)
cipher = AES.new(self._key_file.aes_key, AES.MODE_CBC, self._aes_iv_swapped)
ciphertext = cipher.encrypt(data_to_encrypt)
return swap_endianness_and_bits(ciphertext)
def _get_enable_encryption_commands(self) -> list[Fuzzable]:
"""Returns a list of commands that are necessary to enable the encryption.
If the enable_encryption argument is False an empty list is returned.
The efuse_key parameter decides if the EFUSE_KEY bit in the CTL0 register is set.
"""
if self._enable_encryption:
if self._efuse_key:
# Set the EFUSE_KEY bit, disable ConfigFallback and set the DEC bit of the CTL0 register.
default_value = b"\x80\x00\x04\x40"
else:
# Only disable ConfigFallback and set the DEC bit of the CTL0 register.
default_value = b"\x00\x00\x04\x40"
return [
Type1WritePacket(name="write_to_mask", register_address=6),
Static(name="mask_value", default_value=default_value),
Type1WritePacket(name="write_to_ctl0", register_address=5),
Static(name="ctl0_value", default_value=default_value),
]
else:
return []
class AuthenticatedUltraScaleBlock(FuzzableBlock):
"""Custom FuzzableBlock which authenticates its child objects.
https://boofuzz.readthedocs.io/en/stable/user/protocol-definition.html#boofuzz.FuzzableBlock
This is a parent block for authenticated UltraScale(+) blocks.
There are three different authentication/encryption modes:
- AES-GCM + X-GHASH
- AES-GCM + RSA
- unencrypted + RSA
This block contains functions that are shared accross all three modes.
"""
def __init__(
self,
name: str,
request: Request,
children,
key_file_name: str,
key_file: UltraScaleKeyFile,
enable_encryption: bool,
efuse_key: bool,
*args,
**kwargs,
):
if key_file_name:
self._parse_ultrascale_key_file(key_file_name)
elif key_file:
self._key_file = key_file
else:
raise ValueError("key_file_name or key_file need to be provided")
self._enable_encryption = enable_encryption
self._set_aes_key_source(efuse_key)
super(AuthenticatedUltraScaleBlock, self).__init__(
name=name, request=request, children=children, *args, **kwargs
)
def _parse_ultrascale_key_file(self, key_file_name: str) -> UltraScaleKeyFile:
"""Parse a .nky file for UltraScale(+) devices."""
device = None
encrypt_key_select = None
rsa_public_key_modulus = None
rsa_public_key_digest = None
aes_keys = []
with open(os.path.join(CONSTANTS.STATIC_DIR, key_file_name)) as f:
lines = f.readlines()
for line in lines:
line = line.strip(";\n").split()
if line[0] == "Device":
device = line[1]
elif line[0] == "EncryptKeySelect":
# Apply upper() to be sure the if case in the init function matches.
encrypt_key_select = line[1].upper()
elif line[0] == "RsaPublicKeyModulus":
rsa_public_key_modulus = line[1].replace(":", "")
# The modulus in .nky files generated by Vivado actually is actually 2056 bits long
# because it has an additional \x00 byte at the beginning of this field.
# If this byte exists, cut it.
if len(
rsa_public_key_modulus
) == 514 and rsa_public_key_modulus.startswith("00"):
rsa_public_key_modulus = rsa_public_key_modulus[2:]
rsa_public_key_modulus = bytes.fromhex(rsa_public_key_modulus)
elif line[0] == "RsaPublicKeyDigest":
rsa_public_key_digest = bytes.fromhex(line[1])
elif line[0].startswith("Key"):
aes_key = bytes.fromhex(line[1])
elif line[0].startswith("StartIV"):
if aes_key:
# Unlinke the 7-series AES IV the AES IV for UltraScale devices is only 96 bits long.
# Therefore select only the first 12 bytes as IV because the IVs in the .nky files are padded
# with zeros to 16 bytes or include a length value for the rolling keys feature.
aes_iv_and_length = bytes.fromhex(line[1])
aes_keys.append(
AESKey(
aes_key, aes_iv_and_length[:12], aes_iv_and_length[12:]
)
)
aes_key = None
else:
raise ValueError(f'iv "{line[0]}" has no matching AES key')
if rsa_public_key_modulus or aes_keys:
self._key_file = UltraScaleKeyFile(
device,
encrypt_key_select,
rsa_public_key_modulus,
rsa_public_key_digest,
aes_keys,
)
else:
raise ValueError("error when parsing .nky file: missing key(s)")
def _set_aes_key_source(self, efuse_key: bool) -> None:
"""Set the right AES key source depending on the provided value or the .nky file."""
if efuse_key is not None:
self._efuse_key = efuse_key
elif self._key_file.encrypt_key_select == "BBRAM":
self._efuse_key = False
elif self._key_file.encrypt_key_select == "EFUSE":
self._efuse_key = True
else:
raise ValueError("unknown AES key source")
def _get_enable_encryption_commands(self) -> list[Fuzzable]:
"""Returns a list of commands that are necessary to enable the encryption.
If the enable_encryption argument is False an empty list is returned.
"""
if self._enable_encryption:
if self._efuse_key:
# Set the EFUSE_KEY bit, disable ConfigFallback and set the DEC bit of the CTL0 register.
default_value = b"\x80\x00\x04\x40"
else:
# Only disable ConfigFallback and set the DEC bit of the CTL0 register.
default_value = b"\x00\x00\x04\x40"
return [
Type1WritePacket(name="write_to_mask", register_address=6),
Static(name="mask_value", default_value=default_value),
Type1WritePacket(name="write_to_ctl0", register_address=5),
Static(name="ctl0_value", default_value=default_value),
]
else:
return []
class EncryptedXGHashUltraScaleBlock(AuthenticatedUltraScaleBlock):
"""This authenticated UltraScale(+) block implements the AES-GCM + X-GHASH mode.
The content of this block will be encrypted and authenticated in a way
that it can be loaded on a Xilinx UltraScale(+) FPGA without producing an error.
The content is encrypted by using AES-GCM and authenticated by a
modified version of the GHASH algorithm used in GCM. Ender et al. call this version X-GHASH.
More details about the UltraScale bitstream encryption and authentication
can be found in their paper: https://ieeexplore.ieee.org/document/9786118
Additionally necessary, unencrypted commands will be added to the bitstream.
A key_file_name of a .nky file in the STATIC_DIR has to be provided.
Alternatively it is possible to provide a UltraScaleKeyFile object via the key_file parameter.
The key_file argument is overruled by the key_file_name argument.
The enable_encryption argument can be used to disable the automatic activation of the encryption settings.
By default the DEC option in the CTL0 register is activated
and the EncryptKeySelect value from the .nky file determines if the AES key is read from BBRAM or eFUSE.
The efuse_key argument can be used to override the EncryptKeySelect value from the key file.
If enable_encryption is disabled the encryption commands have to be set manually
in the bitstream before the EncryptedXGHashUltraScaleBlock primitive.
If the return_plaintext argument is enabled the block is rendered in its final structure but unencrypted.
"""
def __init__(
self,
name: str = None,
request: Request = None,
children=None,
key_file_name: str = None,
key_file: UltraScaleKeyFile = None,
enable_encryption: bool = True,
efuse_key: bool = None,
return_plaintext: bool = False,
*args,
**kwargs,
):
super(EncryptedXGHashUltraScaleBlock, self).__init__(
name=name,
request=request,
children=children,
key_file_name=key_file_name,
key_file=key_file,
enable_encryption=enable_encryption,
efuse_key=efuse_key,
*args,
**kwargs,
)
# For this primitive we only need the first AES key and AES IV.
# The rolling keys feature for AES-GCM with XGHASH is not implemented yet.
# Check if there is at least one AES key because the key file could only contain RSA keys.
if not self._key_file.aes_keys:
raise ValueError("missing AES key material")
self._return_plaintext = return_plaintext
# Encrypt one block where every bit is set in AES-ECB mode.
# The resulting ciphertext is used to derive the hash key coefficients and initial checksum.
cipher = AES.new(self._key_file.aes_keys[0].key, AES.MODE_ECB)
ciphertext = cipher.encrypt(b"\xFF" * 16)
# Precalculate the hash key coefficients.
# These coefficients are used to calculate the checksums.
# Calculations are done in GF(2^32) with the irreducible polynomial 0x000000C5
# but the endianness and bits are swapped.
self._hash_key_coefficients = [int.from_bytes(ciphertext[:4], "big")]
for i in range(31):
# If the lowest bit of the checksum length is set a reduction is necessary and
# the bitswapped irreducible polynomial is XORed to the "halved" previous coefficient.
self._hash_key_coefficients.append(
-(self._hash_key_coefficients[i] & 0x1) & 0xA3000000
^ self._hash_key_coefficients[i] >> 1
)
# Reverse the coefficients list to match the order of the checksum bits.
self._hash_key_coefficients.reverse()
self._initial_checksum = int.from_bytes(ciphertext[4:8], "big")
self._initial_checksum_length = 0x80000000
def encode(self, value, mutation_context):
encrypted_data = self._get_encrypted_data(self.get_child_data(mutation_context))
unencrypted_commands = self._get_enable_encryption_commands()