-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathcryptosmt.py
More file actions
331 lines (265 loc) · 11.3 KB
/
Copy pathcryptosmt.py
File metadata and controls
331 lines (265 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
'''
Created on Mar 28, 2014
@author: stefan
'''
# Structured configuration refactoring
from cryptanalysis import search
import ciphers
from config import PATH_STP, PATH_CRYPTOMINISAT, PATH_BOOLECTOR, PATH_BITWUZLA, PATH_CVC5
from argparse import ArgumentParser, RawTextHelpFormatter
from dataclasses import dataclass, field, asdict
from typing import Dict, List, Optional, Any
import yaml
import os
import shutil
import logging
logger = logging.getLogger("cryptosmt")
@dataclass
class ToolParameters:
cipher: str = "simon"
rounds: int = 5
mode: int = 0
wordsize: int = 16
blocksize: int = 64
tweaksize: Optional[int] = None
keysize: Optional[int] = None
capacity: Optional[int] = None
rate: Optional[int] = None
sweight: int = 0
endweight: int = 1000
iterative: bool = False
boolector: bool = False
bitwuzla: bool = False
cvc5: bool = False
stp: bool = False
approxmc: bool = False
weightencoding: str = "bvplus"
threads: int = 1
dot: Optional[str] = None
latex: Optional[str] = None
nummessages: int = 1
timelimit: int = -1
fixedVariables: Dict[str, str] = field(default_factory=dict)
blockedCharacteristics: List[Any] = field(default_factory=list)
rotationconstants: Optional[List[int]] = None
verbose: bool = False
quiet: bool = False
list_ciphers: bool = False
is_interactive: bool = True
def startsearch(params: ToolParameters):
"""
Starts the search tool for the given parameters
"""
if params.list_ciphers:
cipher_suite = ciphers.get_cipher_suite()
print("Available ciphers:")
for name in sorted(cipher_suite.keys()):
print(f" - {name}")
return
cipher = ciphers.get_cipher(params.cipher)
if cipher is None:
logger.error(f"Cipher {params.cipher} not supported!")
return
# Structured dictionary for cipher/search modules
params_dict = asdict(params)
# Optional fields removal logic
if params.rotationconstants is None:
del params_dict["rotationconstants"]
if params.capacity is None:
del params_dict["capacity"]
if params.rate is None:
del params_dict["rate"]
# Remove CLI-only fields that shouldn't be passed to ciphers
for field_name in ["verbose", "quiet", "list_ciphers"]:
if field_name in params_dict:
del params_dict[field_name]
# Handle program flow
if params.mode == 0:
search.findMinWeightCharacteristic(cipher, params_dict)
elif params.mode == 1:
search.searchCharacteristics(cipher, params_dict)
elif params.mode == 2:
search.findAllCharacteristics(cipher, params_dict)
elif params.mode == 3:
search.findBestConstants(cipher, params_dict)
elif params.mode == 4:
search.computeProbabilityOfDifferentials(cipher, params_dict)
return
def checkenviroment():
"""
Basic checks if the enviroment is set up correctly
"""
if not os.path.exists("./tmp/"):
os.makedirs("./tmp/")
if not os.path.exists(PATH_STP):
logger.error(f"Could not find STP binary at {PATH_STP}, please check config.py")
exit()
if not os.path.exists(PATH_CRYPTOMINISAT):
logger.warning(f"Could not find CRYPTOMINISAT binary at {PATH_CRYPTOMINISAT}, please check config.py.")
if not os.path.exists(PATH_BOOLECTOR):
logger.warning(f"Could not find BOOLECTOR binary at {PATH_BOOLECTOR}, \"--boolector\" option not available.")
if not os.path.exists(PATH_BITWUZLA):
logger.warning(f"Could not find BITWUZLA binary at {PATH_BITWUZLA}, \"--bitwuzla\" option not available.")
if not os.path.exists(PATH_CVC5):
# cvc5 might be in PATH, so we only warn if it's not in PATH either
if shutil.which(PATH_CVC5) is None:
logger.warning(f"Could not find CVC5 binary at {PATH_CVC5}, \"--cvc5\" option not available.")
return
def loadparameters(args) -> ToolParameters:
"""
Get parameters from the argument list and inputfile.
"""
params = ToolParameters()
# Check if there is an input file specified
if args.inputfile:
with open(args.inputfile[0], 'r') as input_file:
doc = yaml.load(input_file, Loader=yaml.SafeLoader)
# Update params from yaml
for key, value in doc.items():
if hasattr(params, key):
if key == "fixedVariables":
fixed_vars = {}
if isinstance(value, list):
for variable in value:
fixed_vars.update(variable)
elif isinstance(value, dict):
fixed_vars = value
params.fixedVariables = fixed_vars
else:
setattr(params, key, value)
else:
# Allow passing unknown parameters to ciphers (like capacity/rate if they weren't in dataclass)
# but now we added them to dataclass.
pass
# Override parameters if they are set on commandline
if args.cipher is not None:
params.cipher = args.cipher[0]
if args.rounds is not None:
params.rounds = args.rounds[0]
if args.wordsize is not None:
params.wordsize = args.wordsize[0]
if args.blocksize is not None:
params.blocksize = args.blocksize[0]
if args.tweaksize is not None:
params.tweaksize = args.tweaksize[0]
if args.keysize is not None:
params.keysize = args.keysize[0]
if args.sweight is not None:
params.sweight = args.sweight[0]
if args.endweight is not None:
params.endweight = args.endweight[0]
if args.mode is not None:
params.mode = args.mode[0]
if args.timelimit is not None:
params.timelimit = args.timelimit[0]
if args.iterative:
params.iterative = args.iterative
if args.boolector:
params.boolector = args.boolector
if args.bitwuzla:
params.bitwuzla = args.bitwuzla
if args.cvc5:
params.cvc5 = args.cvc5
if args.stp:
params.stp = args.stp
if args.approxmc:
params.approxmc = args.approxmc
if args.weightencoding:
params.weightencoding = args.weightencoding
if args.threads is not None:
params.threads = args.threads[0]
if args.nummessages is not None:
params.nummessages = args.nummessages[0]
if args.dot is not None:
params.dot = args.dot[0]
if args.latex is not None:
params.latex = args.latex[0]
if args.verbose:
params.verbose = args.verbose
if args.quiet:
params.quiet = args.quiet
if args.list_ciphers:
params.list_ciphers = args.list_ciphers
import sys
params.is_interactive = sys.stdout.isatty()
return params
def main():
"""
Parse the arguments and start the request functionality with the provided
parameters.
"""
parser = ArgumentParser(description="This tool finds the best differential"
"trail in a cryptopgrahic primitive"
"using STP and CryptoMiniSat.",
formatter_class=RawTextHelpFormatter)
parser.add_argument('--cipher', nargs=1, help="Options: simon, speck, ...")
parser.add_argument('--sweight', nargs=1, type=int,
help="Starting weight for the trail search.")
parser.add_argument('--endweight', nargs=1, type=int,
help="Stop search after reaching endweight.")
parser.add_argument('--rounds', nargs=1, type=int,
help="The number of rounds for the cipher")
parser.add_argument('--wordsize', nargs=1, type=int,
help="Wordsize used for the cipher.")
parser.add_argument('--blocksize', nargs=1, type=int,
help="Blocksize used for the cipher.")
parser.add_argument('--tweaksize', nargs=1, type=int,
help="Tweaksize used for the cipher (e.g. for Skinny).")
parser.add_argument('--keysize', nargs=1, type=int,
help="Keysize used for the cipher.")
parser.add_argument('--nummessages', nargs=1, type=int,
help="Number of message blocks.")
parser.add_argument('--mode', nargs=1, type=int,
choices=[0, 1, 2, 3, 4], help=
"0 = search characteristic for fixed round\n"
"1 = search characteristic for all rounds starting at"
"the round specified\n"
"2 = search all characteristic for a specific weight\n"
"3 = used for key recovery\n"
"4 = determine the probability of the differential\n")
parser.add_argument('--timelimit', nargs=1, type=int,
help="Set a timelimit for the search in seconds.")
parser.add_argument('--iterative', action="store_true",
help="Only search for iterative characteristics")
parser.add_argument('--boolector', action="store_true",
help="Use boolector to find solutions")
parser.add_argument('--bitwuzla', action="store_true",
help="Use bitwuzla to find solutions")
parser.add_argument('--cvc5', action="store_true",
help="Use cvc5 to find solutions")
parser.add_argument('--stp', action="store_true",
help="Use STP to find solutions (default)")
parser.add_argument('--approxmc', action="store_true",
help="Use ApproxMC for model counting in Mode 4.")
parser.add_argument('--weightencoding', choices=['bvplus', 'sorter', 'totalizer'],
default='bvplus', help="Encoding used for weight computation.")
parser.add_argument('--threads', nargs=1, type=int, default=[1],
help="Number of threads to use for parallel search.")
parser.add_argument('--inputfile', nargs=1, help="Use an yaml input file to"
"read the parameters.")
parser.add_argument('--dot', nargs=1, help="Print the trail in .dot format.")
parser.add_argument('--latex', nargs=1, help="Print the trail in .tex format.")
parser.add_argument('--verbose', action="store_true", help="Show verbose output")
parser.add_argument('--quiet', action="store_true", help="Show only results")
parser.add_argument('--list-ciphers', action="store_true", help="List all available ciphers")
# Parse command line arguments and construct parameter list.
args = parser.parse_args()
params = loadparameters(args)
# Setup logging
log_level = logging.INFO
if args.verbose:
log_level = logging.DEBUG
elif args.quiet:
log_level = logging.WARNING
if params.is_interactive:
from rich.logging import RichHandler
logging.basicConfig(level=log_level, format="%(message)s",
datefmt="[%X]", handlers=[RichHandler(rich_tracebacks=True)])
else:
logging.basicConfig(level=log_level, format='INFO: %(message)s')
# Check if enviroment is setup correctly.
checkenviroment()
# Start the solver
startsearch(params)
if __name__ == '__main__':
main()