forked from bitlogik/lattice-attack
-
Notifications
You must be signed in to change notification settings - Fork 2
/
gen_input.py
187 lines (149 loc) · 5.92 KB
/
gen_input.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
#!/usr/bin/env python3
# Extract data from real traces for Lattice ECDSA Attack
# Copyright (C) 2021 Antoine Ferron - BitLogiK
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
# Compute data input from the power analysis study :
# Return of ECC dummy point additions
# Simple Power Analysis on efficient P-256 implementation
#
# by Andy Russon
# Paper :
# https://www.sstic.org/media/SSTIC2021/SSTIC-actes/return_of_ecc_dummy_point_additions_simple_power_a/SSTIC2021-Article-return_of_ecc_dummy_point_additions_simple_power_analysis_on_efficient_p-256_implementation-russon.pdf
#
# Get raw data traces online and generate LatticeAttack compatible json input file
import argparse
import base64
import functools
import json
import hashlib
import os
import tarfile
import urllib.request
# Original data set for traces get from :
RESOURCE_URL = (
"https://github.com/orangecertcc/ecdummyrpa/raw/"
"main/sample.tar.gz"
)
# Helpers from ecdsa_lib
def sha2(raw_message):
# SHA-2 256
return hashlib.sha256(raw_message).digest()
def sha2_int(data):
return int.from_bytes(sha2(data), "big")
# Special helpers for this case
def sigDER_to_ints(sigDER):
lenr = int(sigDER[3])
lens = int(sigDER[5 + lenr])
r = int.from_bytes(sigDER[4 : lenr + 4], "big")
s = int.from_bytes(sigDER[lenr + 6 : lenr + 6 + lens], "big")
return r, s
def pubkeyPEM_to_X962(PEMstring):
PEMparts = PEMstring.split("-----")
pubkey_b64 = PEMparts[2].strip("\r\n")
# end of DER is X962 public key
return base64.b64decode(pubkey_b64)[-65:]
def pubkeyX962_to_intpair(DERpubk):
x_int = int.from_bytes(DERpubk[1:33], "big")
y_int = int.from_bytes(DERpubk[33:], "big")
return [x_int, y_int]
def pubkeyPEM_to_xy(PEMstr):
return pubkeyX962_to_intpair(pubkeyPEM_to_X962(PEMstr))
def load_traces():
# Reads traces from this RPA campain
# Prepare to an almost compliant with LatticeAttack
# But it requires then filtering to compute "kp" from "trace"
files = os.listdir("test")
nsig = len(files) // 3
print(f"{len(files)} files detected for {nsig} signatures")
traces = []
for i in range(nsig):
with open(f"test/trace_{i}.txt", "r") as tracef:
data_trace = [float(line) for line in tracef]
with open(f"test/signature_{i}.bin", "rb") as sigf:
DERsig = sigf.read()
with open(f"test/message_{i}.txt", "rb") as msgf:
msg = msgf.read()
trace_data = {}
sig_ints = sigDER_to_ints(DERsig)
trace_data["hash"] = sha2_int(msg)
trace_data["r"] = sig_ints[0]
trace_data["s"] = sig_ints[1]
trace_data["trace"] = data_trace
traces.append(trace_data)
return traces
KNOWN_BITS = 7
def mean_compute(table_array):
# compute arithmetic mean value to get the height of the valley
return functools.reduce(lambda i, j: i + j, table_array) / len(table_array)
def select_sig(sig_candidate):
# Filtering the good signatures
# mean value < limit
# "A valley considerably lower than the others indicating a nonce that has
# its 7 least significant bits set to 0."
LIMIT = 20
DISCARD_SIZE = 0.25 # Discard first and last 25% = keeps "half" middle
trace_len = len(sig_candidate["trace"])
start_idx = int(trace_len * DISCARD_SIZE)
trace_interest = sig_candidate["trace"][start_idx : trace_len - start_idx]
val = mean_compute(trace_interest)
return val < LIMIT
def compute_kp(onesig):
# Generate final data objects (with kp)
sigout = {}
sigout["hash"] = onesig["hash"]
sigout["r"] = onesig["r"]
sigout["s"] = onesig["s"]
sigout["kp"] = 0
return sigout
def get_data_source(res_url):
# Get tar gz file at given url and extract files locally
# Use this only on known trusted or friendly TAR files,
# as this can write files anywhere locally
with urllib.request.urlopen(
urllib.request.Request(res_url, headers={"User-Agent": "Mozilla"})
) as remote_data:
tardata = tarfile.open(fileobj=remote_data, mode="r:gz")
print("Extracting data files ...")
tardata.extractall()
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Load ecdummyRPA traces mesurements for ECDSA attack file format."
)
parser.add_argument(
"-f",
default="data.json",
help="File name output",
metavar="fileout",
)
arg = parser.parse_args()
# Test if data were downloaded by testing presence of pubkey file
if not os.path.exists("pubkey.pem"):
print("Downloading raw data ...")
get_data_source(RESOURCE_URL)
print("Loading files ...")
sigs_data = load_traces()
print("Filtering signatures traces")
sigs_data_selected = [compute_kp(asig) for asig in sigs_data if select_sig(asig)]
with open("pubkey.pem", "r") as pkf:
pubkey_pem = pkf.read()
global_data = {
"curve": "SECP256R1",
"public_key": pubkeyPEM_to_xy(pubkey_pem),
"known_type": "LSB",
"known_bits": KNOWN_BITS,
"signatures": sigs_data_selected,
}
with open(arg.f, "w") as fout:
json.dump(global_data, fout)
print(f"File {arg.f} written with all data.")