forked from lowRISC/ot-sca
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcapture_otbn.py
executable file
·778 lines (664 loc) · 30.7 KB
/
capture_otbn.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
#!/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 logging
import random
import signal
import sys
from dataclasses import dataclass
from datetime import datetime
from functools import partial
from pathlib import Path
from typing import Optional
import numpy as np
import yaml
from lib.ot_communication import OTOTBNVERT, OTUART
from project_library.project import ProjectConfig, SCAProject
from scopes.cycle_converter import convert_num_cycles, convert_offset_cycles
from scopes.scope import Scope, ScopeConfig, determine_sampling_rate
from tqdm import tqdm
import util.helpers as helpers
from target.cw_fpga import CWFPGA
from util import check_version
from util import data_generator as dg
from util import plot
"""OTBN vertical SCA capture script.
Captures power traces during OTBN operations.
The data format of the crypto material (ciphertext, plaintext, and key) inside
the script is stored in plain integer arrays.
Typical usage:
>>> ./capture_otbn.py -c configs/otbn_vertical_keygen_sca_cw310.yaml \
-p projects/otbn_vertical_sca_cw310_keygen
"""
logger = logging.getLogger()
def abort_handler_during_loop(this_project, sig, frame):
""" Abort capture and store traces.
Args:
this_project: Project instance.
"""
if this_project is not None:
logger.info("\nHandling keyboard interrupt")
this_project.close(save=True)
sys.exit(0)
@dataclass
class CaptureConfig:
""" Configuration class for the current capture.
"""
capture_mode: str
batch_mode: bool
num_traces: int
num_segments: int
output_len: int
text_fixed: bytearray
key_fixed: bytearray
key_len_bytes: int
text_len_bytes: int
C: Optional[bytearray]
seed_fixed: Optional[bytearray]
expected_fixed_key: Optional[bytearray]
k_fixed: Optional[bytearray]
expected_fixed_output: Optional[int]
protocol: str
port: Optional[str] = "None"
@dataclass
class CurveConfig:
""" Configuration class for curve dependant parameters.
"""
curve_order_n: int
key_bytes: int
seed_bytes: int
modinv_share_bytes: int
modinv_mask_bytes: int
def setup(cfg: dict, project: Path):
""" Setup target, scope, and project.
Args:
cfg: The configuration for the current experiment.
project: The path for the project file.
Returns:
The target, scope, and project.
"""
# Calculate pll_frequency of the target.
# target_freq = pll_frequency * target_clk_mult
# target_clk_mult is a hardcoded constant in the FPGA bitstream.
cfg["target"]["pll_frequency"] = cfg["target"]["target_freq"] / cfg[
"target"]["target_clk_mult"]
# Init target.
logger.info(f"Initializing target {cfg['target']['target_type']} ...")
target = CWFPGA(bitstream=cfg["target"]["fpga_bitstream"],
force_programming=cfg["target"]["force_program_bitstream"],
firmware=cfg["target"]["fw_bin"],
pll_frequency=cfg["target"]["pll_frequency"],
baudrate=cfg["target"]["baudrate"],
output_len=cfg["target"]["output_len_bytes"],
protocol=cfg["target"]["protocol"])
# Init scope.
scope_type = cfg["capture"]["scope_select"]
# Determine sampling rate, if necessary.
cfg[scope_type]["sampling_rate"] = determine_sampling_rate(cfg, scope_type)
# Convert number of cycles into number of samples, if necessary.
cfg[scope_type]["num_samples"] = convert_num_cycles(cfg, scope_type)
# Convert offset in cycles into offset in samples, if necessary.
cfg[scope_type]["offset_samples"] = convert_offset_cycles(cfg, scope_type)
logger.info(
f"Initializing scope {scope_type} with a sampling rate of {cfg[scope_type]['sampling_rate']}..." # noqa: E501
)
# Create scope config & setup scope.
scope_cfg = ScopeConfig(
scope_type=scope_type,
acqu_channel=cfg[scope_type].get("channel"),
ip=cfg[scope_type].get("waverunner_ip"),
num_samples=cfg[scope_type]["num_samples"],
offset_samples=cfg[scope_type]["offset_samples"],
sampling_rate=cfg[scope_type].get("sampling_rate"),
num_segments=cfg[scope_type]["num_segments"],
sparsing=cfg[scope_type].get("sparsing"),
scope_gain=cfg[scope_type].get("scope_gain"),
pll_frequency=cfg["target"]["pll_frequency"],
)
scope = Scope(scope_cfg)
# OTBN's public-key operations might not fit into the sample buffer of the scope
# These two parameters allows users to conrol the sampling frequency
# `adc_mul` affects the sample frequency (clock_freq = adc_mul * pll_freq)
# `decimate` is the ADC downsampling factor that allows us to sample at
# every `decimate` cycles.
if scope_type == "husky":
if "adc_mul" in cfg["husky"]:
scope.scope.scope.clock.adc_mul = cfg["husky"]["adc_mul"]
if "decimate" in cfg["husky"]:
scope.scope.scope.adc.decimate = cfg["husky"]["decimate"]
# Print final scope parameter
logger.info(
f'Scope setup with final sampling rate of {scope.scope.scope.clock.adc_freq} S/s'
)
# Init project.
project_cfg = ProjectConfig(
type=cfg["capture"]["trace_db"],
path=project,
wave_dtype=np.uint16,
overwrite=True,
trace_threshold=cfg["capture"].get("trace_threshold"))
project = SCAProject(project_cfg)
project.create_project()
return target, scope, project
def configure_cipher(cfg: dict, target,
capture_cfg: CaptureConfig) -> OTOTBNVERT:
""" Configure the OTBN app.
Establish communication with the OTBN keygen app and configure the seed.
Args:
cfg: The configuration for the current experiment.
target: The OT target.
curve_cfg: The curve config.
capture_cfg: The configuration of the capture.
Returns:
ot_otbn_vert: The communication interface to the OTBN app.
curve_cfg: The curve configuration values.
"""
# Establish UART for uJSON command interface. Returns None for simpleserial.
ot_uart = OTUART(protocol=capture_cfg.protocol, port=capture_cfg.port)
# Create communication interface to OTBN.
ot_otbn_vert = OTOTBNVERT(target=target.target,
protocol=capture_cfg.protocol,
port=ot_uart.uart)
# Seed host's PRNG.
random.seed(cfg["test"]["batch_prng_seed"])
# Seed the target's PRNGs
ot_otbn_vert.write_batch_prng_seed(cfg["test"]["batch_prng_seed"].to_bytes(
4, "little"))
# select the otbn app on the device (0 -> keygen, 1 -> modinv)
ot_otbn_vert.choose_otbn_app(cfg["test"]["app"])
# Initialize some curve-dependent parameters.
if cfg["test"]["curve"] == 'p256':
# Create curve config object
curve_cfg = CurveConfig(
curve_order_n=
0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551,
key_bytes=256 // 8,
seed_bytes=320 // 8,
modinv_share_bytes=320 // 8,
modinv_mask_bytes=128 // 8)
else:
# Create curve config object
curve_cfg = CurveConfig(curve_order_n=0,
key_bytes=0,
seed_bytes=0,
modinv_share_bytes=0,
modinv_mask_bytes=0)
# TODO: add support for P384
raise NotImplementedError(
f'Curve {cfg["test"]["curve"]} is not supported')
if capture_cfg.capture_mode == "keygen":
if capture_cfg.batch_mode:
# TODO: add support for batch mode
raise NotImplementedError('Batch mode not yet supported.')
else:
# Generate fixed constants for all traces of the keygen operation.
if cfg["test"]["test_type"] == 'KEY':
# In fixed-vs-random KEY mode we use two fixed constants:
# 1. C - a 320 bit constant redundancy
# 2. fixed_number - a 256 bit number used to derive the fixed key
# for the fixed set of measurements. Note that in
# this set, the fixed key is equal to
# (C + fixed_number) mod curve_order_n
r1, r2, r3 = dg.get_random()
capture_cfg.C = (bytearray(r1) + bytearray(r2) +
bytearray(r3))[:curve_cfg.seed_bytes]
r1, r2, r3 = dg.get_random()
fixed_number = (bytearray(r1) + bytearray(r2) +
bytearray(r3))[:curve_cfg.key_bytes]
seed_fixed_int = int.from_bytes(capture_cfg.C, byteorder='little') + \
int.from_bytes(fixed_number, byteorder='little')
capture_cfg.seed_fixed = seed_fixed_int.to_bytes(
curve_cfg.seed_bytes, byteorder='little')
else:
# In fixed-vs-random SEED mode we use only one fixed constant:
# 1. seed_fixed - A 320 bit constant used to derive the fixed key
# for the fixed set of measurements. Note that in
# this set, the fixed key is equal to:
# seed_fixed mod curve_order_n
r1, r2, r3 = dg.get_random()
capture_cfg.seed_fixed = (bytearray(r1) + bytearray(r2) +
bytearray(r3))[:curve_cfg.seed_bytes]
# Expected key is `seed mod n`, where n is the order of the curve and
# `seed` is interpreted as little-endian.
capture_cfg.expected_fixed_key = int.from_bytes(
capture_cfg.seed_fixed,
byteorder='little') % curve_cfg.curve_order_n
elif capture_cfg.capture_mode == "modinv":
if capture_cfg.batch_mode:
# TODO: add support for batch mode
raise NotImplementedError('Batch mode not supported.')
else:
# set fixed key and share inputs
# (uncomment the desired fixed shares depending on whether
# you want a random fixed key or a hardcoded fixed key)
# r1, r2, r3 = dg.get_random()
# capture_cfg.k_fixed = (bytearray(r1) + bytearray(r2) +
# bytearray(r3))[:curve_cfg.key_bytes]
capture_cfg.k_fixed = bytearray((
0x2648d0d248b70944dfd84c2f85ea5793729112e7cafa50abdf7ef8b7594fa2a1
).to_bytes(curve_cfg.key_bytes, 'little'))
k_fixed_int = int.from_bytes(capture_cfg.k_fixed,
byteorder='little')
# Expected fixed output is `(k)^(-1) mod n`, where n is the curve order n
capture_cfg.expected_fixed_output = pow(k_fixed_int, -1,
curve_cfg.curve_order_n)
return ot_otbn_vert, curve_cfg
def generate_ref_crypto_keygen(cfg: dict, sample_fixed, curve_cfg: CurveConfig,
capture_cfg: CaptureConfig):
""" Generate cipher material for keygen application.
Args:
cfg: The configuration for the current experiment.
sample_fixed: Use fixed key or new key.
curve_cfg: The curve config.
capture_cfg: The configuration of the capture.
Returns:
seed_used: The next seed.
mask: The next mask.
expected_key: The next expected key.
sample_fixed: Is the next sample fixed or not?
"""
if capture_cfg.batch_mode:
# TODO: add support for batch mode
raise NotImplementedError('Batch mode not yet supported.')
else:
if cfg["test"]["masks_off"] == 'True':
# Use a constant mask for each trace
mask = bytearray(curve_cfg.seed_bytes) # all zeros
else:
# Generate a new random mask for each trace.
r1, r2, r3 = dg.get_random()
mask = (bytearray(r1) + bytearray(r2) +
bytearray(r3))[:curve_cfg.seed_bytes]
# Generate fixed constants for all traces of the keygen operation.
if cfg["test"]["test_type"] == 'KEY':
# In fixed-vs-random KEY mode, the fixed set of measurements is
# generated using the fixed 320 bit seed. The random set of
# measurements is generated in two steps:
# 1. Choose a random 256 bit number r
# 2. Compute the seed as (C + r) where C is the fixed 320 bit
# constant. Note that in this case the used key is equal to
# (C + r) mod curve_order_n
if sample_fixed:
seed_used = capture_cfg.seed_fixed
expected_key = capture_cfg.expected_fixed_key
else:
r1, r2, r3 = dg.get_random()
random_number = (bytearray(r1) + bytearray(r2) +
bytearray(r3))[:curve_cfg.key_bytes]
seed_used_int = int.from_bytes(capture_cfg.C, byteorder='little') + \
int.from_bytes(random_number, byteorder='little')
seed_used = seed_used_int.to_bytes(curve_cfg.seed_bytes,
byteorder='little')
expected_key = int.from_bytes(seed_used, byteorder='little') % \
curve_cfg.curve_order_n
else:
# In fixed-vs-random SEED mode, the fixed set of measurements is
# generated using the fixed 320 bit seed. The random set of
# measurements is generated using a random 320 bit seed. In both
# cases, the used key is equal to:
# seed mod curve_order_n
if sample_fixed:
seed_used = capture_cfg.seed_fixed
expected_key = capture_cfg.expected_fixed_key
else:
r1, r2, r3 = dg.get_random()
seed_used = (bytearray(r1) + bytearray(r2) +
bytearray(r3))[:curve_cfg.seed_bytes]
expected_key = int.from_bytes(seed_used, byteorder='little') % \
curve_cfg.curve_order_n
# The next sample is either fixed or random.
r1, r2, r3 = dg.get_random()
sample_fixed = r1[0] & 0x1
return seed_used, mask, expected_key, sample_fixed
def generate_ref_crypto_modinv(cfg: dict, sample_fixed, curve_cfg: CurveConfig,
capture_cfg: CaptureConfig):
""" Generate cipher material for the modular inverse operation.
Args:
cfg: The configuration for the current experiment.
sample_fixed: Use fixed key or new key.
curve_cfg: The curve config.
capture_cfg: The configuration of the capture.
Returns:
k_used: The next scalar value.
input_k0_used: The next first share of k_used.
input_k1_used: The next second share of k_used.
expected_output: The next expected modinv output.
sample_fixed: Is the next sample fixed or not?
"""
if capture_cfg.batch_mode:
# TODO: add support for batch mode
raise NotImplementedError('Batch mode not yet supported.')
else:
if sample_fixed:
# Compute the fixed input shares:
# generate two random 320-bit shares
r1, r2, r3 = dg.get_random()
input_k0_fixed = (bytearray(r1) + bytearray(r2) +
bytearray(r3))[:curve_cfg.modinv_share_bytes]
r1, r2, r3 = dg.get_random()
input_k1_fixed = (bytearray(r1) + bytearray(r2) +
bytearray(r3))[:curve_cfg.modinv_share_bytes]
k0_fixed = int.from_bytes(input_k0_fixed, byteorder='little')
k1_fixed = int.from_bytes(input_k1_fixed, byteorder='little')
# adapt share k1 so that k = (k0 + k1) mod n
k_tmp = (k0_fixed + k1_fixed) % curve_cfg.curve_order_n
k_tmp_diff = (
int.from_bytes(capture_cfg.k_fixed, byteorder='little') -
k_tmp) % curve_cfg.curve_order_n
k1_fixed += k_tmp_diff
if k1_fixed >= pow(2, 320):
k1_fixed -= curve_cfg.curve_order_n
input_k1_fixed = bytearray(
(k1_fixed).to_bytes(curve_cfg.modinv_share_bytes, 'little'))
# Use the fixed input.
input_k0_used = input_k0_fixed
input_k1_used = input_k1_fixed
k_used = capture_cfg.k_fixed
expected_output = capture_cfg.expected_fixed_output
else:
# Use a random input.
r1, r2, r3 = dg.get_random()
input_k0_used = (bytearray(r1) + bytearray(r2) +
bytearray(r3))[:curve_cfg.modinv_share_bytes]
r1, r2, r3 = dg.get_random()
input_k1_used = (bytearray(r1) + bytearray(r2) +
bytearray(r3))[:curve_cfg.modinv_share_bytes]
# calculate the key from the shares
k_used_int = (int.from_bytes(input_k0_used, byteorder='little') +
int.from_bytes(input_k1_used, byteorder='little')
) % curve_cfg.curve_order_n
k_used = bytearray(
k_used_int.to_bytes(curve_cfg.key_bytes, 'little'))
expected_output = pow(k_used_int, -1, curve_cfg.curve_order_n)
# The next sample is either fixed or random.
r1, r2, r3 = dg.get_random()
sample_fixed = r1[0] & 0x1
return k_used, input_k0_used, input_k1_used, expected_output, sample_fixed
def check_ciphertext_keygen(ot_otbn_vert: OTOTBNVERT, expected_key,
curve_cfg: CurveConfig):
""" Compares the received with the generated key.
Key shares are read from the device and compared against the pre-computed
generated key. In batch mode, only the last key is compared.
Asserts on mismatch.
Args:
ot_otbn_vert: The OpenTitan OTBN vertical communication interface.
expected_key: The pre-computed key.
curve_cfg: The curve config.
Returns:
share0: First share of the received key.
share1: Second share of the received key.
"""
# Read the output, unmask the key, and check if it matches
# expectations.
share0 = ot_otbn_vert.read_output(curve_cfg.seed_bytes)
share1 = ot_otbn_vert.read_output(curve_cfg.seed_bytes)
if share0 is None:
raise RuntimeError('Random share0 is none')
if share1 is None:
raise RuntimeError('Random share1 is none')
d0 = int.from_bytes(share0, byteorder='little')
d1 = int.from_bytes(share1, byteorder='little')
actual_key = (d0 + d1) % curve_cfg.curve_order_n
assert actual_key == expected_key, (f"Incorrect encryption result!\n"
f"actual: {actual_key}\n"
f"expected: {expected_key}")
return share0, share1
def check_ciphertext_modinv(ot_otbn_vert: OTOTBNVERT, expected_output,
curve_cfg: CurveConfig):
""" Compares the received modular inverse output with the generated output.
Args:
ot_otbn_vert: The OpenTitan OTBN vertical communication interface.
expected_key: The pre-computed key.
curve_cfg: The curve config.
Returns:
actual_output: The received output of the modinv operation.
"""
# Read the output, unmask it, and check if it matches expectations.
kalpha_inv = ot_otbn_vert.read_output(curve_cfg.key_bytes)
alpha = ot_otbn_vert.read_output(curve_cfg.modinv_mask_bytes)
if kalpha_inv is None:
raise RuntimeError('kaplpha_inv is none')
if alpha is None:
raise RuntimeError('alpha is none')
# Actual result (kalpha_inv*alpha) mod n:
actual_output = int.from_bytes(
kalpha_inv, byteorder='little') * int.from_bytes(
alpha, byteorder='little') % curve_cfg.curve_order_n
assert actual_output == expected_output, (f"Incorrect modinv result!\n"
f"actual: {actual_output}\n"
f"expected: {expected_output}")
return actual_output
def capture_keygen(cfg: dict, scope: Scope, ot_otbn_vert: OTOTBNVERT,
capture_cfg: CaptureConfig, curve_cfg: CurveConfig,
project: SCAProject, cwtarget: CWFPGA):
""" Capture power consumption during selected OTBN operation.
Args:
cfg: The configuration for the current experiment.
scope: The scope class representing a scope (Husky or WaveRunner).
ot_otbn_vert: The OpenTitan OTBN vertical communication interface.
capture_cfg: The configuration of the capture.
curve_cfg: The curve config.
project: The SCA project.
cwtarget: The CW FPGA target.
"""
# Initial seed.
seed_used = capture_cfg.seed_fixed
# Initial mask.
mask = bytearray(curve_cfg.seed_bytes) # all zeros
# Initial expected key.
expected_key = capture_cfg.expected_fixed_key
# FVSR setup.
sample_fixed = 1
# Optimization for CW trace library.
num_segments_storage = 1
# Register ctrl-c handler to store traces on abort.
signal.signal(signal.SIGINT, partial(abort_handler_during_loop, project))
# Main capture with progress bar.
remaining_num_traces = capture_cfg.num_traces
with tqdm(total=remaining_num_traces,
desc="Capturing",
ncols=80,
unit=" traces") as pbar:
while remaining_num_traces > 0:
# Arm the scope.
scope.arm()
seed_used, mask, expected_key, sample_fixed = generate_ref_crypto_keygen(
cfg, sample_fixed, curve_cfg, capture_cfg)
# Trigger encryption.
if capture_cfg.batch_mode:
# TODO: add support for batch mode
raise NotImplementedError('Batch mode not yet supported.')
else:
# Send the seed to ibex.
# Ibex receives the seed and the mask and computes the two shares as:
# Share0 = seed XOR mask
# Share1 = mask
# These shares are then forwarded to OTBN.
ot_otbn_vert.write_keygen_seed(seed_used)
ot_otbn_vert.start_keygen(mask)
# Capture traces.
waves = scope.capture_and_transfer_waves(cwtarget.target)
assert waves.shape[0] == capture_cfg.num_segments
# Compare received key with generated key.
share0, share1 = check_ciphertext_keygen(
ot_otbn_vert, expected_key, curve_cfg)
# Store trace into database.
project.append_trace(wave=waves[0, :],
plaintext=mask,
ciphertext=share0 + share1,
key=seed_used)
# Memory allocation optimization for CW trace library.
num_segments_storage = project.optimize_capture(
num_segments_storage)
# Update the loop variable and the progress bar.
remaining_num_traces -= capture_cfg.num_segments
pbar.update(capture_cfg.num_segments)
def capture_modinv(cfg: dict, scope: Scope, ot_otbn_vert: OTOTBNVERT,
capture_cfg: CaptureConfig, curve_cfg: CurveConfig,
project: SCAProject, cwtarget: CWFPGA):
""" Capture power consumption during selected OTBN operation.
Args:
cfg: The configuration for the current experiment.
scope: The scope class representing a scope (Husky or WaveRunner).
ot_otbn_vert: The OpenTitan OTBN vertical communication interface.
capture_cfg: The configuration of the capture.
curve_cfg: The curve config.
project: The SCA project.
cwtarget: The CW FPGA target.
"""
# Initial scalar k.
k_used = capture_cfg.k_fixed
# Initial expected key.
expected_output = capture_cfg.expected_fixed_output
# FVSR setup.
sample_fixed = 1
# Optimization for CW trace library.
num_segments_storage = 1
# Register ctrl-c handler to store traces on abort.
signal.signal(signal.SIGINT, partial(abort_handler_during_loop, project))
# Main capture with progress bar.
remaining_num_traces = capture_cfg.num_traces
with tqdm(total=remaining_num_traces,
desc="Capturing",
ncols=80,
unit=" traces") as pbar:
while remaining_num_traces > 0:
# Arm the scope.
scope.arm()
k_used, input_k0_used, input_k1_used, expected_output, sample_fixed = \
generate_ref_crypto_modinv(cfg, sample_fixed, curve_cfg, capture_cfg)
# Trigger encryption.
if capture_cfg.batch_mode:
# TODO: add support for batch mode
raise NotImplementedError('Batch mode not supported.')
else:
# Start modinv device computation
ot_otbn_vert.start_modinv(input_k0_used, input_k1_used)
# Capture traces.
waves = scope.capture_and_transfer_waves(cwtarget.target)
assert waves.shape[0] == capture_cfg.num_segments
# Compare received key with generated key.
actual_output = check_ciphertext_modinv(
ot_otbn_vert, expected_output, curve_cfg)
# Store trace into database.
project.append_trace(wave=waves[0, :],
plaintext=k_used,
ciphertext=bytearray(
actual_output.to_bytes(
curve_cfg.key_bytes, 'little')),
key=k_used)
# Memory allocation optimization for CW trace library.
num_segments_storage = project.optimize_capture(
num_segments_storage)
# Update the loop variable and the progress bar.
remaining_num_traces -= capture_cfg.num_segments
pbar.update(capture_cfg.num_segments)
def print_plot(project: SCAProject, config: dict, file: Path) -> None:
""" Print plot of traces.
Printing the plot helps to adjust the scope gain and check for clipping.
Args:
project: The project containing the traces.
config: The capture configuration.
file: The output file path.
"""
if config["capture"]["show_plot"]:
plot.save_plot_to_file(project.get_waves(0, config["capture"]["plot_traces"]),
set_indices = None,
num_traces = config["capture"]["plot_traces"],
outfile = file,
add_mean_stddev=True)
logger.info(f'Created plot with {config["capture"]["plot_traces"]} traces: '
f'{Path(str(file) + ".html").resolve()}')
def main(argv=None):
# Configure the logger.
logger.setLevel(logging.INFO)
console = logging.StreamHandler()
logger.addHandler(console)
# Parse the provided arguments.
args = helpers.parse_arguments(argv)
# Check the ChipWhisperer version.
check_version.check_cw("5.7.0")
# Load configuration from file.
with open(args.cfg) as f:
cfg = yaml.load(f, Loader=yaml.FullLoader)
# Determine the capture mode and configure the current capture.
mode = cfg["test"]["app"]
batch = cfg["test"]["batch_mode"]
if batch is False:
# For non-batch mode, make sure that num_segments = 1.
cfg[cfg["capture"]["scope_select"]]["num_segments"] = 1
logger.info(
"num_segments needs to be 1 in non-batch mode. Setting num_segments=1."
)
# Setup the target, scope and project.
target, scope, project = setup(cfg, args.project)
# Create capture config object.
capture_cfg = CaptureConfig(
capture_mode=mode,
batch_mode=batch,
num_traces=cfg["capture"]["num_traces"],
num_segments=cfg[cfg["capture"]["scope_select"]]["num_segments"],
output_len=cfg["target"]["output_len_bytes"],
text_fixed=bytearray(),
key_fixed=bytearray(),
key_len_bytes=cfg["test"]["key_len_bytes"],
text_len_bytes=cfg["test"]["text_len_bytes"],
protocol=cfg["target"]["protocol"],
C=bytearray(),
seed_fixed=bytearray(),
expected_fixed_key=bytearray(),
k_fixed=bytearray(),
expected_fixed_output=0)
logger.info(
f"Setting up capture {capture_cfg.capture_mode} batch={capture_cfg.batch_mode}..."
)
# Configure cipher.
ot_otbn_vert, curve_cfg = configure_cipher(cfg, target, capture_cfg)
# Capture traces.
if mode == "keygen":
capture_keygen(cfg, scope, ot_otbn_vert, capture_cfg, curve_cfg,
project, target)
elif mode == "modinv":
capture_modinv(cfg, scope, ot_otbn_vert, capture_cfg, curve_cfg,
project, target)
else:
# TODO: add support for modinv app
raise NotImplementedError('Cofigured OTBN app not yet supported.')
# Print plot.
print_plot(project, cfg, args.project)
# Save metadata.
metadata = {}
metadata["datetime"] = datetime.now().strftime("%m/%d/%Y, %H:%M:%S")
metadata["cfg"] = cfg
metadata["num_samples"] = scope.scope_cfg.num_samples
metadata["offset_samples"] = scope.scope_cfg.offset_samples
metadata["scope_gain"] = scope.scope_cfg.scope_gain
if cfg["capture"]["scope_select"] == "husky":
metadata[
"sampling_rate"] = scope.scope.scope.clock.adc_freq / scope.scope.scope.adc.decimate
metadata["samples_trigger_high"] = scope.scope.scope.adc.trig_count
else:
metadata["sampling_rate"] = scope.scope_cfg.sampling_rate
metadata["num_traces"] = capture_cfg.num_traces
metadata["cfg_file"] = str(args.cfg)
# Store bitstream information.
metadata["fpga_bitstream_path"] = cfg["target"]["fpga_bitstream"]
metadata["fpga_bitstream_crc"] = helpers.file_crc(cfg["target"]["fpga_bitstream"])
if args.save_bitstream:
metadata["fpga_bitstream"] = helpers.get_binary_blob(cfg["target"]["fpga_bitstream"])
# Store binary information.
metadata["fw_bin_path"] = cfg["target"]["fw_bin"]
metadata["fw_bin_crc"] = helpers.file_crc(cfg["target"]["fw_bin"])
if args.save_binary:
metadata["fw_bin"] = helpers.get_binary_blob(cfg["target"]["fw_bin"])
# Store user provided notes.
metadata["notes"] = args.notes
# Store the Git hash.
metadata["git_hash"] = helpers.get_git_hash()
# Write metadata into project database.
project.write_metadata(metadata)
# Save and close project.
project.save()
if __name__ == "__main__":
main()