-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathcapture.py
executable file
·2310 lines (1958 loc) · 101 KB
/
capture.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 lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
import binascii
import random
import signal
import sys
import time
from datetime import datetime
from enum import Enum
from functools import partial
from pathlib import Path
from types import SimpleNamespace
import chipwhisperer as cw
import numpy as np
import scared
import typer
import yaml
from chipwhisperer.common.traces import Trace
from Crypto.Cipher import AES
from Crypto.Hash import KMAC128, SHA3_256
from cw_segmented import CwSegmented
from tqdm import tqdm
from waverunner import WaveRunner
from util import device, plot
class ScopeType(str, Enum):
cw = "cw"
waverunner = "waverunner"
app = typer.Typer(add_completion=False)
# To be able to define subcommands for the "capture" command.
app_capture = typer.Typer()
app.add_typer(app_capture, name="capture", help="Capture traces for SCA")
# Shared options for capture commands
opt_force_program_bitstream = typer.Option(None, help=("Force program FPGA with the bitstream."))
opt_num_traces = typer.Option(None, help="Number of traces to capture.")
opt_plot_traces = typer.Option(None, help="Number of traces to plot.")
opt_scope_type = typer.Option(ScopeType.cw, help=("Scope type"))
opt_ciphertexts_store = typer.Option(False, help=("Store all ciphertexts for batch capture."))
def create_waverunner(ot, capture_cfg):
"""Create a WaveRunner object to be used for batch capture."""
return WaveRunner(capture_cfg["waverunner_ip"])
def create_cw_segmented(ot, capture_cfg, device_cfg):
"""Create CwSegmented object to be used for batch capture."""
return CwSegmented(num_samples=ot.num_samples,
offset_samples=ot.offset_samples,
scope_gain=capture_cfg["scope_gain"],
scope=ot.scope,
clkgen_freq=ot.clkgen_freq,
adc_mul=ot.adc_mul)
SCOPE_FACTORY = {
ScopeType.cw: create_cw_segmented,
ScopeType.waverunner: create_waverunner,
}
def abort_handler(project, sig, frame):
""" Handler for ctrl-c keyboard interrupts:
Saves capture project before exiting, in case abort is intended.
Needs to be registered in every capture function before capture loop.
To register handler use:
signal.signal(signal.SIGINT, partial(abort_handler, project))
where 'project' is the variable for the capture project """
if project is not None:
print("\nCaught keyboard interrupt -> saving project (traces)...")
project.close(save=True)
sys.exit(0)
def save_metadata(project, device_cfg, capture_cfg, trigger_cycles, sample_rate):
# Save metadata to project file
if sample_rate is not None:
project.settingsDict['sample_rate'] = sample_rate
if device_cfg is not None:
for entry in device_cfg:
project.settingsDict[entry] = device_cfg[entry]
if capture_cfg is not None:
for entry in capture_cfg:
project.settingsDict[entry] = capture_cfg[entry]
# store last number of cycles where the trigger signal was high to metadata
if trigger_cycles is not None:
project.settingsDict['samples_trigger_high'] = trigger_cycles
project.settingsDict['datetime'] = datetime.now().strftime("%m/%d/%Y, %H:%M:%S")
# Note: initialize_capture and plot_results are also used by other scripts.
def initialize_capture(device_cfg, capture_cfg):
"""Initialize capture."""
ot = device.OpenTitan(device_cfg["fpga_bitstream"],
device_cfg["force_program_bitstream"],
device_cfg["fw_bin"],
device_cfg["pll_frequency"],
device_cfg["target_clk_mult"],
device_cfg["baudrate"],
capture_cfg["scope_gain"],
capture_cfg["num_cycles"],
capture_cfg["offset_cycles"],
capture_cfg["output_len_bytes"])
print(f'Scope setup with sampling rate {ot.scope.clock.adc_freq} S/s')
# Ping target
print('Reading from FPGA using simpleserial protocol.')
version = None
ping_cnt = 0
while not version:
if ping_cnt == 3:
raise RuntimeError(
f'No response from the target (attempts: {ping_cnt}).')
ot.target.write('v' + '\n')
ping_cnt += 1
time.sleep(0.5)
version = ot.target.read().strip()
print(f'Target simpleserial version: {version} (attempts: {ping_cnt}).')
return ot
def check_range(waves, bits_per_sample):
""" The ADC output is in the interval [0, 2**bits_per_sample-1]. Check that the recorded
traces are within [1, 2**bits_per_sample-2] to ensure the ADC doesn't saturate. """
adc_range = np.array([0, 2**bits_per_sample])
if not (np.all(np.greater(waves[:], adc_range[0])) and
np.all(np.less(waves[:], adc_range[1] - 1))):
print('\nWARNING: Some samples are outside the range [' +
str(adc_range[0] + 1) + ', ' + str(adc_range[1] - 2) + '].')
print('The ADC has a max range of [' +
str(adc_range[0]) + ', ' + str(adc_range[1] - 1) + '] and might saturate.')
print('It is recommended to reduce the scope gain (see device.py).')
def plot_results(plot_cfg, project_name):
"""Plots traces from `project_name` using `plot_cfg` settings."""
project = cw.open_project(project_name)
if len(project.waves) == 0:
print('Project contains no traces. Did the capture fail?')
return
plot.save_plot_to_file(project.waves, None, plot_cfg["num_traces"],
plot_cfg["trace_image_filename"])
print(
f'Created plot with {plot_cfg["num_traces"]} traces: '
f'{Path(plot_cfg["trace_image_filename"]).resolve()}'
)
@app.command()
def init(ctx: typer.Context):
"""Initalize target for SCA."""
initialize_capture(ctx.obj.cfg["device"], ctx.obj.cfg["capture"])
def capture_init(ctx, force_program_bitstream, num_traces, plot_traces):
"""Initializes the user data stored in the context and programs the target."""
cfg = ctx.obj.cfg
if force_program_bitstream is not None:
cfg["device"]["force_program_bitstream"] = force_program_bitstream
if num_traces:
cfg["capture"]["num_traces"] = num_traces
if plot_traces:
cfg["plot_capture"]["show"] = True
cfg["plot_capture"]["num_traces"] = plot_traces
# Key and plaintext generator
ctx.obj.ktp = cw.ktp.Basic()
# This is a workaroung for https://github.com/lowRISC/ot-sca/issues/116
if "use_fixed_key_iter" in cfg["capture"]: # for backwarts compatibility
ctx.obj.ktp.fixed_key = cfg["capture"]["use_fixed_key_iter"]
# ktp.key_len is only evaluated if ktp.fixed_key is set to False
ctx.obj.ktp.key_len = cfg["capture"]["key_len_bytes"]
ctx.obj.ktp.text_len = cfg["capture"]["plain_text_len_bytes"]
ctx.obj.ot = initialize_capture(cfg["device"], cfg["capture"])
def capture_loop(trace_gen, ot, capture_cfg, device_cfg):
"""Main capture loop.
Args:
trace_gen: A trace generator.
capture_cfg: Capture configuration.
"""
project = cw.create_project(capture_cfg["project_name"], overwrite=True)
# register ctrl-c handler to not lose already recorded traces if measurement is aborted
signal.signal(signal.SIGINT, partial(abort_handler, project))
for _ in tqdm(range(capture_cfg["num_traces"]), desc='Capturing', ncols=80):
traces = next(trace_gen)
check_range(traces.wave, ot.scope.adc.bits_per_sample)
project.traces.append(traces, dtype=np.uint16)
sample_rate = int(round(ot.scope.clock.adc_freq, -6))
save_metadata(project, device_cfg, capture_cfg, None, sample_rate)
project.save()
def capture_end(cfg):
if cfg["plot_capture"]["show"]:
plot_results(cfg["plot_capture"], cfg["capture"]["project_name"])
if "project_export" in cfg["capture"] and cfg["capture"]["project_export"]:
project = cw.open_project(cfg["capture"]["project_name"])
project.export(cfg["capture"]["project_export_filename"])
project.close(save=False)
def capture_aes_static(ot):
"""A generator for capturing AES traces for fixed key and test.
Args:
ot: Initialized OpenTitan target.
"""
key = bytearray([0x81, 0x1E, 0x37, 0x31, 0xB0, 0x12, 0x0A, 0x78,
0x42, 0x78, 0x1E, 0x22, 0xB2, 0x5C, 0xDD, 0xF9])
text = bytearray([0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA,
0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA])
tqdm.write(f'Fixed key: {binascii.b2a_hex(bytes(key))}')
while True:
cipher = AES.new(bytes(key), AES.MODE_ECB)
ret = cw.capture_trace(ot.scope, ot.target, text, key, ack=False, as_int=True)
if not ret:
raise RuntimeError('Capture failed.')
expected = binascii.b2a_hex(cipher.encrypt(bytes(text)))
got = binascii.b2a_hex(ret.textout)
if got != expected:
raise RuntimeError(f'Bad ciphertext: {got} != {expected}.')
yield ret
@app_capture.command()
def aes_static(ctx: typer.Context,
force_program_bitstream: bool = opt_force_program_bitstream,
num_traces: int = opt_num_traces,
plot_traces: int = opt_plot_traces):
"""Capture AES traces from a target that runs the `aes_serial` program."""
capture_init(ctx, force_program_bitstream, num_traces, plot_traces)
capture_loop(capture_aes_static(ctx.obj.ot), ctx.obj.ot,
ctx.obj.cfg["capture"], ctx.obj.cfg["device"])
capture_end(ctx.obj.cfg)
def capture_aes_random(ot, ktp):
"""A generator for capturing AES traces.
Fixed key, Random texts.
Args:
ot: Initialized OpenTitan target.
ktp: Key and plaintext generator.
"""
key, _ = ktp.next()
tqdm.write(f'Using key: {binascii.b2a_hex(bytes(key))}')
cipher = AES.new(bytes(key), AES.MODE_ECB)
# Select the trigger type:
# 0 - precise, hardware-generated trigger - default
# 1 - fully software-controlled trigger
ot.target.simpleserial_write("t", bytearray([0x00]))
while True:
_, text = ktp.next()
ret = cw.capture_trace(ot.scope, ot.target, text, key, ack=False, as_int=True)
if not ret:
raise RuntimeError('Capture failed.')
expected = binascii.b2a_hex(cipher.encrypt(bytes(text)))
got = binascii.b2a_hex(ret.textout)
if got != expected:
raise RuntimeError(f'Bad ciphertext: {got} != {expected}.')
yield ret
@app_capture.command()
def aes_random(ctx: typer.Context,
force_program_bitstream: bool = opt_force_program_bitstream,
num_traces: int = opt_num_traces,
plot_traces: int = opt_plot_traces):
"""Capture AES traces from a target that runs the `aes_serial` program."""
capture_init(ctx, force_program_bitstream, num_traces, plot_traces)
capture_loop(capture_aes_random(ctx.obj.ot, ctx.obj.ktp), ctx.obj.ot,
ctx.obj.cfg["capture"], ctx.obj.cfg["device"])
capture_end(ctx.obj.cfg)
def optimize_cw_capture(project, num_segments_storage):
"""Optimize cw capture by managing API."""
# Make sure to allocate sufficient memory for the storage segment array during the
# first resize operation. By default, the ChipWhisperer API starts every new segment
# with 1 trace and then increases it on demand by 25 traces at a time. This results in
# frequent array resizing and decreasing capture rate.
# See addWave() in chipwhisperer/common/traces/_base.py.
if project.traces.cur_seg.tracehint < project.traces.seg_len:
project.traces.cur_seg.setTraceHint(project.traces.seg_len)
# Only keep the latest two trace storage segments enabled. By default the ChipWhisperer
# API keeps all segments enabled and after appending a new trace, the trace ranges are
# updated for all segments. This leads to a decreasing capture rate after time.
# See:
# - _updateRanges() in chipwhisperer/common/api/TraceManager.py.
# - https://github.com/newaetech/chipwhisperer/issues/344
if num_segments_storage != len(project.segments):
if num_segments_storage >= 2:
project.traces.tm.setTraceSegmentStatus(num_segments_storage - 2, False)
num_segments_storage = len(project.segments)
return num_segments_storage
def check_ciphertext(ot, expected_last_ciphertext, ciphertext_len):
"""Check the first word of the last ciphertext in a batch to make sure we are in sync."""
actual_last_ciphertext = ot.target.simpleserial_read("r", ciphertext_len, ack=False)
assert actual_last_ciphertext == expected_last_ciphertext[0:ciphertext_len], (
f"Incorrect encryption result!\n"
f"actual: {actual_last_ciphertext}\n"
f"expected: {expected_last_ciphertext}"
)
def capture_aes_random_batch(ot, ktp, capture_cfg, scope_type, device_cfg):
"""A generator for capturing AES traces in batch mode.
Fixed key, Random texts.
Args:
ot: Initialized OpenTitan target.
ktp: Key and plaintext generator.
capture_cfg: Capture configuration.
scope_type: cw or waverunner as a scope for batch capture.
"""
# Seed host's PRNG.
# TODO: Replace this with a dedicated PRNG to avoid other packages breaking our code.
random.seed(capture_cfg["batch_prng_seed"])
# Set the target's key
key = ktp.next_key()
tqdm.write(f'Using key: {binascii.b2a_hex(bytes(key))}')
ot.target.simpleserial_write("k", key)
# Seed the target's PRNG
ot.target.simpleserial_write("s", capture_cfg["batch_prng_seed"].to_bytes(4, "little"))
# Create the ChipWhisperer project.
project = cw.create_project(capture_cfg["project_name"], overwrite=True)
# Capture traces.
rem_num_traces = capture_cfg["num_traces"]
num_segments_storage = 1
# cw and waverunner scopes are supported fot batch capture.
scope = SCOPE_FACTORY[scope_type](ot, capture_cfg, device_cfg)
# register ctrl-c handler to not lose already recorded traces if measurement is aborted
signal.signal(signal.SIGINT, partial(abort_handler, project))
with tqdm(total=rem_num_traces, desc="Capturing", ncols=80, unit=" traces") as pbar:
while rem_num_traces > 0:
# Determine the number of traces for this batch and arm the oscilloscope.
scope.num_segments = min(rem_num_traces, scope.num_segments_max)
scope.arm()
# Start batch encryption.
ot.target.simpleserial_write(
"b", scope.num_segments_actual.to_bytes(4, "little")
)
# Transfer traces
waves = scope.capture_and_transfer_waves()
assert waves.shape[0] == scope.num_segments
# Check that the ADC didn't saturate when recording this batch.
check_range(waves, ot.scope.adc.bits_per_sample)
# Generate plaintexts and ciphertexts to compare with the batch encryption results.
plaintexts = [ktp.next()[1] for _ in range(scope.num_segments_actual)]
ciphertexts = [
bytearray(c)
for c in scared.aes.base.encrypt(
np.asarray(plaintexts), np.asarray(key)
)
]
check_ciphertext(ot, ciphertexts[-1], 4)
num_segments_storage = optimize_cw_capture(project, num_segments_storage)
# Add traces of this batch to the project.
for wave, plaintext, ciphertext in zip(waves, plaintexts, ciphertexts):
project.traces.append(
cw.common.traces.Trace(wave, plaintext, ciphertext, key),
dtype=np.uint16
)
# Update the loop variable and the progress bar.
rem_num_traces -= scope.num_segments
pbar.update(scope.num_segments)
# Before saving the project, re-enable all trace storage segments.
for s in range(len(project.segments)):
project.traces.tm.setTraceSegmentStatus(s, True)
assert len(project.traces) == capture_cfg["num_traces"]
# Save metadata to project file
sample_rate = int(round(scope._scope.clock.adc_freq, -6))
save_metadata(project, device_cfg, capture_cfg, None, sample_rate)
# Save the project to disk.
project.save()
@app_capture.command()
def aes_random_batch(ctx: typer.Context,
force_program_bitstream: bool = opt_force_program_bitstream,
num_traces: int = opt_num_traces,
plot_traces: int = opt_plot_traces,
scope_type: ScopeType = opt_scope_type):
"""Capture AES traces in batch mode. Fixed key random texts."""
capture_init(ctx, force_program_bitstream, num_traces, plot_traces)
capture_aes_random_batch(ctx.obj.ot, ctx.obj.ktp, ctx.obj.cfg["capture"],
scope_type, ctx.obj.cfg["device"])
capture_end(ctx.obj.cfg)
def capture_aes_fvsr_key(ot):
"""A generator for capturing AES traces for fixed vs random key test.
The data collection method is based on the derived test requirements (DTR) for TVLA:
https://www.rambus.com/wp-content/uploads/2015/08/TVLA-DTR-with-AES.pdf
The measurements are taken by using either fixed or randomly selected key.
In order to simplify the analysis, the first sample has to use fixed key.
The initial key and plaintext values as well as the derivation methods are as specified in the
DTR.
Args:
ot: Initialized OpenTitan target.
"""
key_generation = bytearray([0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF1,
0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xE0, 0xF0])
cipher_gen = AES.new(bytes(key_generation), AES.MODE_ECB)
text_fixed = bytearray([0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA,
0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA])
text_random = bytearray([0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC,
0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC])
key_fixed = bytearray([0x81, 0x1E, 0x37, 0x31, 0xB0, 0x12, 0x0A, 0x78,
0x42, 0x78, 0x1E, 0x22, 0xB2, 0x5C, 0xDD, 0xF9])
key_random = bytearray([0x53, 0x53, 0x53, 0x53, 0x53, 0x53, 0x53, 0x53,
0x53, 0x53, 0x53, 0x53, 0x53, 0x53, 0x53, 0x53])
tqdm.write(f'Fixed key: {binascii.b2a_hex(bytes(key_fixed))}')
sample_fixed = 1
while True:
if sample_fixed:
text_fixed = bytearray(cipher_gen.encrypt(text_fixed))
key, text = key_fixed, text_fixed
else:
text_random = bytearray(cipher_gen.encrypt(text_random))
key_random = bytearray(cipher_gen.encrypt(key_random))
key, text = key_random, text_random
sample_fixed = random.randint(0, 1)
cipher = AES.new(bytes(key), AES.MODE_ECB)
ret = cw.capture_trace(ot.scope, ot.target, text, key, ack=False, as_int=True)
if not ret:
raise RuntimeError('Capture failed.')
expected = binascii.b2a_hex(cipher.encrypt(bytes(text)))
got = binascii.b2a_hex(ret.textout)
if got != expected:
raise RuntimeError(f'Bad ciphertext: {got} != {expected}.')
yield ret
@app_capture.command()
def aes_fvsr_key(ctx: typer.Context,
force_program_bitstream: bool = opt_force_program_bitstream,
num_traces: int = opt_num_traces,
plot_traces: int = opt_plot_traces):
"""Capture AES traces from a target that runs the `aes_serial` program."""
capture_init(ctx, force_program_bitstream, num_traces, plot_traces)
capture_loop(capture_aes_fvsr_key(ctx.obj.ot), ctx.obj.ot,
ctx.obj.cfg["capture"], ctx.obj.cfg["device"])
capture_end(ctx.obj.cfg)
def capture_aes_fvsr_key_batch(ot, ktp, capture_cfg, scope_type, gen_ciphertexts, device_cfg):
"""A generator for capturing AES traces for fixed vs random key test in batch mode.
The data collection method is based on the derived test requirements (DTR) for TVLA:
https://www.rambus.com/wp-content/uploads/2015/08/TVLA-DTR-with-AES.pdf
The measurements are taken by using either fixed or randomly selected key in batches.
In order to simplify the analysis, the first encryption has to use fixed key.
To generate random keys and texts internal PRNG's are used instead of AES functions as specified
in the DTR.
Args:
ot: Initialized OpenTitan target.
ktp: Key and plaintext generator.
capture_cfg: Capture configuration.
scope_type: cw or waverunner as a scope for batch capture.
"""
# Seed host's PRNG.
# TODO: Replace this with a dedicated PRNG to avoid other packages breaking our code.
random.seed(capture_cfg["batch_prng_seed"])
# Seed the target's PRNGs
ot.target.simpleserial_write("l", capture_cfg["lfsr_seed"].to_bytes(4, "little"))
ot.target.simpleserial_write("s", capture_cfg["batch_prng_seed"].to_bytes(4, "little"))
# Set and transfer the fixed key.
# Without the sleep statement, the CW305 seems to fail to configure the batch PRNG
# seed and/or the fixed key and then gets completely out of sync.
time.sleep(0.5)
key_fixed = bytearray([0x81, 0x1E, 0x37, 0x31, 0xB0, 0x12, 0x0A, 0x78,
0x42, 0x78, 0x1E, 0x22, 0xB2, 0x5C, 0xDD, 0xF9])
tqdm.write(f'Fixed key: {binascii.b2a_hex(bytes(key_fixed))}')
ot.target.simpleserial_write("f", key_fixed)
sample_fixed = 1
is_first_batch = True
# Create the ChipWhisperer project.
project = cw.create_project(capture_cfg["project_name"], overwrite=True)
# Capture traces.
rem_num_traces = capture_cfg["num_traces"]
num_segments_storage = 1
# cw and waverunner scopes are supported for batch capture.
scope = SCOPE_FACTORY[scope_type](ot, capture_cfg, device_cfg)
# register ctrl-c handler to not lose already recorded traces if measurement is aborted
signal.signal(signal.SIGINT, partial(abort_handler, project))
with tqdm(total=rem_num_traces, desc="Capturing", ncols=80, unit=" traces") as pbar:
while rem_num_traces > 0:
# Determine the number of traces for this batch and arm the oscilloscope.
scope.num_segments = min(rem_num_traces, scope.num_segments_max)
scope.arm()
# Start batch encryption. In order to increase capture rate, after the first batch
# encryption, the device will start automatically to generate random keys and plaintexts
# when this script is getting waves from the scope.
if is_first_batch:
ot.target.simpleserial_write("g", scope.num_segments_actual.to_bytes(4, "little"))
is_first_batch = False
ot.target.simpleserial_write("e", scope.num_segments_actual.to_bytes(4, "little"))
# Transfer traces.
waves = scope.capture_and_transfer_waves()
assert waves.shape[0] == scope.num_segments
# Check that the ADC didn't saturate when recording this batch.
check_range(waves, ot.scope.adc.bits_per_sample)
# Generate keys, plaintexts and ciphertexts
keys = []
plaintexts = []
ciphertexts = []
for ii in range(scope.num_segments_actual):
if sample_fixed:
key = np.asarray(key_fixed)
else:
key = np.asarray(ktp.next()[1])
plaintext = np.asarray(ktp.next()[1])
keys.append(key)
plaintexts.append(plaintext)
if gen_ciphertexts:
ciphertext = np.asarray(scared.aes.base.encrypt(plaintext, key))
ciphertexts.append(ciphertext)
sample_fixed = plaintext[0] & 0x1
if gen_ciphertexts:
expected_last_ciphertext = ciphertexts[-1]
else:
expected_last_ciphertext = np.asarray(scared.aes.base.encrypt(plaintext, key))
check_ciphertext(ot, expected_last_ciphertext, 4)
num_segments_storage = optimize_cw_capture(project, num_segments_storage)
# Add traces of this batch to the project. By default we don't store the ciphertexts as
# generating them on the host as well as transferring them over from the target
# substantially reduces capture performance. It should therefore only be enabled if
# absolutely needed.
if gen_ciphertexts:
for wave, plaintext, ciphertext, key in zip(waves, plaintexts, ciphertexts, keys):
project.traces.append(
cw.common.traces.Trace(wave, plaintext, ciphertext, key),
dtype=np.uint16
)
else:
for wave, plaintext, key in zip(waves, plaintexts, keys):
project.traces.append(
cw.common.traces.Trace(wave, plaintext, None, key),
dtype=np.uint16
)
# Update the loop variable and the progress bar.
rem_num_traces -= scope.num_segments
pbar.update(scope.num_segments)
# Before saving the project, re-enable all trace storage segments.
for s in range(len(project.segments)):
project.traces.tm.setTraceSegmentStatus(s, True)
assert len(project.traces) == capture_cfg["num_traces"]
# Save metadata to project file
sample_rate = int(round(scope._scope.clock.adc_freq, -6))
save_metadata(project, device_cfg, capture_cfg, None, sample_rate)
# Save the project to disk.
project.save()
@app_capture.command()
def aes_fvsr_key_batch(ctx: typer.Context,
force_program_bitstream: bool = opt_force_program_bitstream,
num_traces: int = opt_num_traces,
plot_traces: int = opt_plot_traces,
scope_type: ScopeType = opt_scope_type,
gen_ciphertexts: bool = opt_ciphertexts_store):
"""Capture AES traces in batch mode. Fixed vs random keys, random texts."""
capture_init(ctx, force_program_bitstream, num_traces, plot_traces)
capture_aes_fvsr_key_batch(ctx.obj.ot, ctx.obj.ktp, ctx.obj.cfg["capture"],
scope_type, gen_ciphertexts,
ctx.obj.cfg["device"])
capture_end(ctx.obj.cfg)
@app_capture.command()
def aes_mix_column(ctx: typer.Context,
force_program_bitstream: bool = opt_force_program_bitstream,
num_traces: int = opt_num_traces,
plot_traces: int = opt_plot_traces):
"""Capture AES traces. Fixed key, Random texts. 4 sets of traces. Mix Column HD CPA Attack.
Attack implemented by ChipWhisperer:
Repo: https://github.com/newaetech/chipwhisperer-jupyter/blob/master/experiments/MixColumn%20Attack.ipynb # noqa: E501
Reference: https://eprint.iacr.org/2019/343.pdf
See mix_columns_cpa_attack.py for attack portion.
"""
capture_init(ctx, force_program_bitstream, num_traces, plot_traces)
ctx.obj.ktp = cw.ktp.VarVec()
ctx.obj.ktp.key_len = ctx.obj.cfg['capture']['key_len_bytes']
ctx.obj.ktp.text_len = ctx.obj.cfg['capture']['plain_text_len_bytes']
project_name = ctx.obj.cfg["capture"]['project_name']
# For each iteration, run a capture where only the bytes specified in
# `text_range` are set to random values. All other bytes are set to a
# fixed value.
for var_vec in range(4):
ctx.obj.cfg['capture']['project_name'] = f'{project_name}_{var_vec}'
ctx.obj.ktp.var_vec = var_vec
capture_loop(capture_aes_random(
ctx.obj.ot, ctx.obj.ktp), ctx.obj.ot, ctx.obj.cfg["capture"], ctx.obj.cfg["device"]
)
capture_end(ctx.obj.cfg)
def capture_sha3_random(ot, ktp, capture_cfg):
"""A generator for capturing sha3 traces.
Fixed key, Random texts.
Args:
ot: Initialized OpenTitan target.
ktp: Key and plaintext generator.
"""
# if masks_off is true:
# configure target to disable masking and reuse constant fast entropy
if capture_cfg["masks_off"] is True:
print("Warning: Configure device to use constant, fast entropy!")
ot.target.simpleserial_write("m", bytearray([0x01]))
else:
ot.target.simpleserial_write("m", bytearray([0x00]))
ack_ret = ot.target.simpleserial_wait_ack(5000)
if ack_ret is None:
raise Exception("Batch mode acknowledge error: Device and host not in sync")
tqdm.write("No key used, as we are doing sha3 hashing")
while True:
_, text = ktp.next()
ret = cw.capture_trace(ot.scope, ot.target, text, key=None, ack=False, as_int=True)
if not ret:
raise RuntimeError('Capture failed.')
sha3 = SHA3_256.new(text)
expected = binascii.b2a_hex(sha3.digest())
got = binascii.b2a_hex(ret.textout)
if got != expected:
raise RuntimeError(f'Bad digest: {got} != {expected}.')
yield ret
def capture_sha3_fvsr_data_batch(ot, ktp, capture_cfg, scope_type, device_cfg):
"""A generator for fast capturing sha3 traces.
The data collection method is based on the derived test requirements (DTR) for TVLA:
https://www.rambus.com/wp-content/uploads/2015/08/TVLA-DTR-with-AES.pdf
The measurements are taken by using either fixed or randomly selected message.
In order to simplify the analysis, the first sample has to use fixed message.
Args:
ot: Initialized OpenTitan target.
ktp: Key and plaintext generator.
capture_cfg: Capture configuration.
scope_type: cw or waverunner as a scope for batch capture.
"""
# if masks_off is true:
# configure target to disable masking and reuse constant fast entropy
if capture_cfg["masks_off"] is True:
print("Warning: Configure device to use constant, fast entropy!")
ot.target.simpleserial_write("m", bytearray([0x01]))
else:
ot.target.simpleserial_write("m", bytearray([0x00]))
ack_ret = ot.target.simpleserial_wait_ack(5000)
if ack_ret is None:
raise Exception("Batch mode acknowledge error: Device and host not in sync")
# Value defined under Section 5.3 in the derived test requirements (DTR) for TVLA.
plaintext_fixed = bytearray([0xDA, 0x39, 0xA3, 0xEE, 0x5E, 0x6B, 0x4B, 0x0D,
0x32, 0x55, 0xBF, 0xEF, 0x95, 0x60, 0x18, 0x90])
# Note that - at least on FPGA - the DTR value above may lead to "fake" leakage as for the
# fixed trace set, the number of bits set in the first (37) and second 64-bit word (31), as
# well as in the Hamming distance between the two (30) is different from the statistical
# mean (32). As a result, the loading of the fixed message into the SHA3 core on average
# discharges the power rails slightly less than loading a random message. Until the SHA3 core
# starts processing, the power rails will recharge but they might not be able to reach the same
# levels for the fixed and random trace set, potentially leading to a small vertical offset
# between the two trace sets. This offset is detectable by TVLA and covers actual leakage
# happening during the SHA3 processing. The effect is most easliy visible between loading the
# plaintext and appending the padding, i.e., when the target is completely idle and waiting for
# the 40 clock cycle timer delay between the RUN and PROCESS command to expire.
#
# Crafted plaintext value with 4 bits set per byte, and where the Hamming distance between the
# first and second 64-bit word is exatly 4 bits per byte. This can optionally be used for
# debugging such "fake" leakage issues.
# plaintext_fixed = bytearray([0xA5, 0xC3, 0x5A, 0x3C, 0x96, 0x0F, 0x69, 0xF0,
# 0xC3, 0xA5, 0x3C, 0x5A, 0x0F, 0x96, 0xF0, 0x69])
ot.target.simpleserial_write("f", plaintext_fixed)
plaintext = plaintext_fixed
random.seed(capture_cfg["batch_prng_seed"])
ot.target.simpleserial_write("l", capture_cfg["lfsr_seed"].to_bytes(4, "little"))
ot.target.simpleserial_write("s", capture_cfg["batch_prng_seed"].to_bytes(4, "little"))
# Create the ChipWhisperer project.
project_file = capture_cfg["project_name"]
project = cw.create_project(project_file, overwrite=True)
# Capture traces.
rem_num_traces = capture_cfg["num_traces"]
num_segments_storage = 1
sample_fixed = False
# cw and waverunner scopes are supported fot batch capture.
scope = SCOPE_FACTORY[scope_type](ot, capture_cfg, device_cfg)
# register ctrl-c handler to not lose already recorded traces if measurement is aborted
signal.signal(signal.SIGINT, partial(abort_handler, project))
with tqdm(total=rem_num_traces, desc="Capturing", ncols=80, unit=" traces") as pbar:
while rem_num_traces > 0:
# Determine the number of traces for this batch and arm the oscilloscope.
scope.num_segments = min(rem_num_traces, scope.num_segments_max)
scope.arm()
# Start batch encryption.
ot.target.simpleserial_write(
"b", scope.num_segments_actual.to_bytes(4, "little")
)
# This wait ist crucial to be in sync with the device
ack_ret = ot.target.simpleserial_wait_ack(5000)
if ack_ret is None:
raise Exception("Batch mode acknowledge error: Device and host not in sync")
plaintexts = []
ciphertexts = []
batch_digest = None
for i in range(scope.num_segments_actual):
if sample_fixed:
plaintext = plaintext_fixed
else:
random_plaintext = ktp.next()[1]
plaintext = random_plaintext
# needed to be in sync with ot lfsr and for sample_fixed generation
dummy_plaintext = ktp.next()[1]
sha3 = SHA3_256.new(plaintext)
ciphertext = sha3.digest()
batch_digest = (ciphertext if batch_digest is None else
bytes(a ^ b for (a, b) in zip(ciphertext, batch_digest)))
plaintexts.append(plaintext)
ciphertexts.append(binascii.b2a_hex(ciphertext))
sample_fixed = dummy_plaintext[0] & 1
# Transfer traces
waves = scope.capture_and_transfer_waves()
assert waves.shape[0] == scope.num_segments
# Check that the ADC didn't saturate when recording this batch.
check_range(waves, ot.scope.adc.bits_per_sample)
# Check the batch digest to make sure we are in sync.
check_ciphertext(ot, batch_digest, 32)
num_segments_storage = optimize_cw_capture(project, num_segments_storage)
# Add traces of this batch to the project.
for wave, plaintext, ciphertext in zip(waves, plaintexts, ciphertexts):
project.traces.append(
cw.common.traces.Trace(wave, plaintext, bytearray(ciphertext), None),
dtype=np.uint16
)
# Update the loop variable and the progress bar.
rem_num_traces -= scope.num_segments
pbar.update(scope.num_segments)
# Before saving the project, re-enable all trace storage segments.
for s in range(len(project.segments)):
project.traces.tm.setTraceSegmentStatus(s, True)
assert len(project.traces) == capture_cfg["num_traces"]
# Save metadata to project file
sample_rate = int(round(scope._scope.clock.adc_freq, -6))
save_metadata(project, device_cfg, capture_cfg, None, sample_rate)
# Save the project to disk.
project.save()
@app_capture.command()
def sha3_random(ctx: typer.Context,
force_program_bitstream: bool = opt_force_program_bitstream,
num_traces: int = opt_num_traces,
plot_traces: int = opt_plot_traces):
"""Capture sha3 traces from a target that runs the `sha3_serial` program."""
capture_init(ctx, force_program_bitstream, num_traces, plot_traces)
capture_loop(capture_sha3_random(ctx.obj.ot, ctx.obj.ktp, ctx.obj.cfg["capture"]),
ctx.obj.ot, ctx.obj.cfg["capture"], ctx.obj.cfg["device"])
capture_end(ctx.obj.cfg)
def capture_sha3_fvsr_data(ot, capture_cfg):
"""A generator for capturing sha3 traces.
The data collection method is based on the derived test requirements (DTR) for TVLA:
https://www.rambus.com/wp-content/uploads/2015/08/TVLA-DTR-with-AES.pdf
The measurements are taken by using either fixed or randomly selected message.
In order to simplify the analysis, the first sample has to use fixed message.
Args:
ot: Initialized OpenTitan target.
"""
# we are using AES in ECB mode for generating random texts
key_generation = bytearray([0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF1,
0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xE0, 0xF0])
cipher = AES.new(bytes(key_generation), AES.MODE_ECB)
text_fixed = bytearray([0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA,
0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA])
text_random = bytearray([0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC,
0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC])
sha3 = SHA3_256.new(text_fixed)
digest_fixed = binascii.b2a_hex(sha3.digest())
# if masks_off is true:
# configure target to disable masking and reuse constant fast entropy
if capture_cfg["masks_off"] is True:
print("Warning: Configure device to use constant, fast entropy!")
ot.target.simpleserial_write("m", bytearray([0x01]))
else:
ot.target.simpleserial_write("m", bytearray([0x00]))
ack_ret = ot.target.simpleserial_wait_ack(5000)
if ack_ret is None:
raise Exception("Batch mode acknowledge error: Device and host not in sync")
tqdm.write("No key used, as we are doing sha3 hashing")
ot.target.simpleserial_write("l", capture_cfg["lfsr_seed"].to_bytes(4, "little"))
# Start sampling with the fixed key.
sample_fixed = 1
while True:
if sample_fixed:
ret = cw.capture_trace(ot.scope, ot.target, text_fixed, key=None, ack=False,
as_int=True)
if not ret:
raise RuntimeError('Capture failed.')
expected = digest_fixed
got = binascii.b2a_hex(ret.textout)
else:
text_random = bytearray(cipher.encrypt(text_random))
ret = cw.capture_trace(ot.scope, ot.target, text_random, key=None, ack=False,
as_int=True)
if not ret:
raise RuntimeError('Capture failed.')
sha3 = SHA3_256.new(text_random)
expected = binascii.b2a_hex(sha3.digest())
got = binascii.b2a_hex(ret.textout)
sample_fixed = random.randint(0, 1)
if got != expected:
raise RuntimeError(f'Bad digest: {got} != {expected}.')
yield ret
@app_capture.command()
def sha3_fvsr_data(ctx: typer.Context,
force_program_bitstream: bool = opt_force_program_bitstream,
num_traces: int = opt_num_traces,
plot_traces: int = opt_plot_traces):
"""Capture sha3 traces from a target that runs the `sha3_serial` program."""
capture_init(ctx, force_program_bitstream, num_traces, plot_traces)
capture_loop(capture_sha3_fvsr_data(ctx.obj.ot, ctx.obj.cfg["capture"]),
ctx.obj.ot, ctx.obj.cfg["capture"], ctx.obj.cfg["device"])
capture_end(ctx.obj.cfg)
@app_capture.command()
def sha3_fvsr_data_batch(ctx: typer.Context,
force_program_bitstream: bool = opt_force_program_bitstream,
num_traces: int = opt_num_traces,
plot_traces: int = opt_plot_traces,
scope_type: ScopeType = opt_scope_type):
"""Capture sha3 traces in batch mode. Fixed vs Random."""
capture_init(ctx, force_program_bitstream, num_traces, plot_traces)
capture_sha3_fvsr_data_batch(ctx.obj.ot, ctx.obj.ktp,
ctx.obj.cfg["capture"],
scope_type,
ctx.obj.cfg["device"])
capture_end(ctx.obj.cfg)
def capture_kmac_random(ot, ktp):
"""A generator for capturing KMAC-128 traces.
Fixed key, Random texts.
Args:
ot: Initialized OpenTitan target.
ktp: Key and plaintext generator.
"""
key, _ = ktp.next()
tqdm.write(f'Using key: {binascii.b2a_hex(bytes(key))}')
while True:
_, text = ktp.next()
ret = cw.capture_trace(ot.scope, ot.target, text, key, ack=False, as_int=True)
if not ret:
raise RuntimeError('Capture failed.')
mac = KMAC128.new(key=key, mac_len=32)
mac.update(text)
expected = mac.hexdigest()
expected = expected.encode('ascii')
got = binascii.b2a_hex(ret.textout)
if got != expected:
raise RuntimeError(f'Bad digest: {got} != {expected}.')
yield ret
def capture_kmac_fvsr_key_batch(ot, ktp, capture_cfg, scope_type, device_cfg):
"""A generator for fast capturing KMAC-128 traces.
The data collection method is based on the derived test requirements (DTR) for TVLA:
https://www.rambus.com/wp-content/uploads/2015/08/TVLA-DTR-with-AES.pdf
The measurements are taken by using either fixed or randomly selected key.
In order to simplify the analysis, the first sample has to use fixed key.
The initial key and plaintext values as well as the derivation methods are as specified in the
DTR.
Args:
ot: Initialized OpenTitan target.
ktp: Key and plaintext generator.
capture_cfg: Capture configuration.
scope_type: cw or waverunner as a scope for batch capture.
"""
key_fixed = bytearray([0x81, 0x1E, 0x37, 0x31, 0xB0, 0x12, 0x0A, 0x78,
0x42, 0x78, 0x1E, 0x22, 0xB2, 0x5C, 0xDD, 0xF9])
ot.target.simpleserial_write("f", key_fixed)
key = key_fixed
random.seed(capture_cfg["batch_prng_seed"])
ot.target.simpleserial_write("l", capture_cfg["lfsr_seed"].to_bytes(4, "little"))
ot.target.simpleserial_write("s", capture_cfg["batch_prng_seed"].to_bytes(4, "little"))
# Create the ChipWhisperer project.
project_file = capture_cfg["project_name"]
project = cw.create_project(project_file, overwrite=True)
# Capture traces.
rem_num_traces = capture_cfg["num_traces"]
num_segments_storage = 1
sample_fixed = False
# cw and waverunner scopes are supported fot batch capture.
scope = SCOPE_FACTORY[scope_type](ot, capture_cfg, device_cfg)
# register ctrl-c handler to not lose already recorded traces if measurement is aborted
signal.signal(signal.SIGINT, partial(abort_handler, project))
with tqdm(total=rem_num_traces, desc="Capturing", ncols=80, unit=" traces") as pbar:
while rem_num_traces > 0:
# Determine the number of traces for this batch and arm the oscilloscope.
scope.num_segments = min(rem_num_traces, scope.num_segments_max)
scope.arm()
# Start batch encryption.