- Notifications
You must be signed in to change notification settings - Fork 31.7k
/
Copy pathmultissltests.py
executable file
·546 lines (476 loc) · 16.2 KB
/
multissltests.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
#!./python
"""Run Python tests against multiple installations of OpenSSL and LibreSSL
The script
(1) downloads OpenSSL / LibreSSL tar bundle
(2) extracts it to ./src
(3) compiles OpenSSL / LibreSSL
(4) installs OpenSSL / LibreSSL into ../multissl/$LIB/$VERSION/
(5) forces a recompilation of Python modules using the
header and library files from ../multissl/$LIB/$VERSION/
(6) runs Python's test suite
The script must be run with Python's build directory as current working
directory.
The script uses LD_RUN_PATH, LD_LIBRARY_PATH, CPPFLAGS and LDFLAGS to bend
search paths for header files and shared libraries. It's known to work on
Linux with GCC and clang.
Please keep this script compatible with Python 2.7, and 3.4 to 3.7.
(c) 2013-2017 Christian Heimes <christian@python.org>
"""
from __future__ importprint_function
importargparse
fromdatetimeimportdatetime
importlogging
importos
try:
fromurllib.requestimporturlopen
fromurllib.errorimportHTTPError
exceptImportError:
fromurllib2importurlopen, HTTPError
importre
importshutil
importsubprocess
importsys
importtarfile
log=logging.getLogger("multissl")
OPENSSL_OLD_VERSIONS= [
"1.1.1w",
]
OPENSSL_RECENT_VERSIONS= [
"3.0.15",
"3.1.7",
"3.2.3",
"3.3.2",
]
LIBRESSL_OLD_VERSIONS= [
]
LIBRESSL_RECENT_VERSIONS= [
]
# store files in ../multissl
HERE=os.path.dirname(os.path.abspath(__file__))
PYTHONROOT=os.path.abspath(os.path.join(HERE, '..', '..'))
MULTISSL_DIR=os.path.abspath(os.path.join(PYTHONROOT, '..', 'multissl'))
parser=argparse.ArgumentParser(
prog='multissl',
description=(
"Run CPython tests with multiple OpenSSL and LibreSSL "
"versions."
)
)
parser.add_argument(
'--debug',
action='store_true',
help="Enable debug logging",
)
parser.add_argument(
'--disable-ancient',
action='store_true',
help="Don't test OpenSSL and LibreSSL versions without upstream support",
)
parser.add_argument(
'--openssl',
nargs='+',
default=(),
help=(
"OpenSSL versions, defaults to '{}' (ancient: '{}') if no "
"OpenSSL and LibreSSL versions are given."
).format(OPENSSL_RECENT_VERSIONS, OPENSSL_OLD_VERSIONS)
)
parser.add_argument(
'--libressl',
nargs='+',
default=(),
help=(
"LibreSSL versions, defaults to '{}' (ancient: '{}') if no "
"OpenSSL and LibreSSL versions are given."
).format(LIBRESSL_RECENT_VERSIONS, LIBRESSL_OLD_VERSIONS)
)
parser.add_argument(
'--tests',
nargs='*',
default=(),
help="Python tests to run, defaults to all SSL related tests.",
)
parser.add_argument(
'--base-directory',
default=MULTISSL_DIR,
help="Base directory for OpenSSL / LibreSSL sources and builds."
)
parser.add_argument(
'--no-network',
action='store_false',
dest='network',
help="Disable network tests."
)
parser.add_argument(
'--steps',
choices=['library', 'modules', 'tests'],
default='tests',
help=(
"Which steps to perform. 'library' downloads and compiles OpenSSL "
"or LibreSSL. 'module' also compiles Python modules. 'tests' builds "
"all and runs the test suite."
)
)
parser.add_argument(
'--system',
default='',
help="Override the automatic system type detection."
)
parser.add_argument(
'--force',
action='store_true',
dest='force',
help="Force build and installation."
)
parser.add_argument(
'--keep-sources',
action='store_true',
dest='keep_sources',
help="Keep original sources for debugging."
)
classAbstractBuilder(object):
library=None
url_templates=None
src_template=None
build_template=None
depend_target=None
install_target='install'
ifhasattr(os, 'process_cpu_count'):
jobs=os.process_cpu_count()
else:
jobs=os.cpu_count()
module_files= (
os.path.join(PYTHONROOT, "Modules/_ssl.c"),
os.path.join(PYTHONROOT, "Modules/_hashopenssl.c"),
)
module_libs= ("_ssl", "_hashlib")
def__init__(self, version, args):
self.version=version
self.args=args
# installation directory
self.install_dir=os.path.join(
os.path.join(args.base_directory, self.library.lower()), version
)
# source file
self.src_dir=os.path.join(args.base_directory, 'src')
self.src_file=os.path.join(
self.src_dir, self.src_template.format(version))
# build directory (removed after install)
self.build_dir=os.path.join(
self.src_dir, self.build_template.format(version))
self.system=args.system
def__str__(self):
return"<{0.__class__.__name__} for {0.version}>".format(self)
def__eq__(self, other):
ifnotisinstance(other, AbstractBuilder):
returnNotImplemented
return (
self.library==other.library
andself.version==other.version
)
def__hash__(self):
returnhash((self.library, self.version))
@property
defshort_version(self):
"""Short version for OpenSSL download URL"""
returnNone
@property
defopenssl_cli(self):
"""openssl CLI binary"""
returnos.path.join(self.install_dir, "bin", "openssl")
@property
defopenssl_version(self):
"""output of 'bin/openssl version'"""
cmd= [self.openssl_cli, "version"]
returnself._subprocess_output(cmd)
@property
defpyssl_version(self):
"""Value of ssl.OPENSSL_VERSION"""
cmd= [
sys.executable,
'-c', 'import ssl; print(ssl.OPENSSL_VERSION)'
]
returnself._subprocess_output(cmd)
@property
definclude_dir(self):
returnos.path.join(self.install_dir, "include")
@property
deflib_dir(self):
returnos.path.join(self.install_dir, "lib")
@property
defhas_openssl(self):
returnos.path.isfile(self.openssl_cli)
@property
defhas_src(self):
returnos.path.isfile(self.src_file)
def_subprocess_call(self, cmd, env=None, **kwargs):
log.debug("Call '{}'".format(" ".join(cmd)))
returnsubprocess.check_call(cmd, env=env, **kwargs)
def_subprocess_output(self, cmd, env=None, **kwargs):
log.debug("Call '{}'".format(" ".join(cmd)))
ifenvisNone:
env=os.environ.copy()
env["LD_LIBRARY_PATH"] =self.lib_dir
out=subprocess.check_output(cmd, env=env, **kwargs)
returnout.strip().decode("utf-8")
def_download_src(self):
"""Download sources"""
src_dir=os.path.dirname(self.src_file)
ifnotos.path.isdir(src_dir):
os.makedirs(src_dir)
data=None
forurl_templateinself.url_templates:
url=url_template.format(v=self.version, s=self.short_version)
log.info("Downloading from {}".format(url))
try:
req=urlopen(url)
# KISS, read all, write all
data=req.read()
exceptHTTPErrorase:
log.error(
"Download from {} has from failed: {}".format(url, e)
)
else:
log.info("Successfully downloaded from {}".format(url))
break
ifdataisNone:
raiseValueError("All download URLs have failed")
log.info("Storing {}".format(self.src_file))
withopen(self.src_file, "wb") asf:
f.write(data)
def_unpack_src(self):
"""Unpack tar.gz bundle"""
# cleanup
ifos.path.isdir(self.build_dir):
shutil.rmtree(self.build_dir)
os.makedirs(self.build_dir)
tf=tarfile.open(self.src_file)
name=self.build_template.format(self.version)
base=name+'/'
# force extraction into build dir
members=tf.getmembers()
formemberinlist(members):
ifmember.name==name:
members.remove(member)
elifnotmember.name.startswith(base):
raiseValueError(member.name, base)
member.name=member.name[len(base):].lstrip('/')
log.info("Unpacking files to {}".format(self.build_dir))
tf.extractall(self.build_dir, members)
def_build_src(self, config_args=()):
"""Now build openssl"""
log.info("Running build in {}".format(self.build_dir))
cwd=self.build_dir
cmd= [
"./config", *config_args,
"shared", "--debug",
"--prefix={}".format(self.install_dir)
]
# cmd.extend(["no-deprecated", "--api=1.1.0"])
env=os.environ.copy()
# set rpath
env["LD_RUN_PATH"] =self.lib_dir
ifself.system:
env['SYSTEM'] =self.system
self._subprocess_call(cmd, cwd=cwd, env=env)
ifself.depend_target:
self._subprocess_call(
["make", "-j1", self.depend_target], cwd=cwd, env=env
)
self._subprocess_call(["make", f"-j{self.jobs}"], cwd=cwd, env=env)
def_make_install(self):
self._subprocess_call(
["make", "-j1", self.install_target],
cwd=self.build_dir
)
self._post_install()
ifnotself.args.keep_sources:
shutil.rmtree(self.build_dir)
def_post_install(self):
pass
definstall(self):
log.info(self.openssl_cli)
ifnotself.has_opensslorself.args.force:
ifnotself.has_src:
self._download_src()
else:
log.debug("Already has src {}".format(self.src_file))
self._unpack_src()
self._build_src()
self._make_install()
else:
log.info("Already has installation {}".format(self.install_dir))
# validate installation
version=self.openssl_version
ifself.versionnotinversion:
raiseValueError(version)
defrecompile_pymods(self):
log.warning("Using build from {}".format(self.build_dir))
# force a rebuild of all modules that use OpenSSL APIs
forfnameinself.module_files:
os.utime(fname, None)
# remove all build artefacts
forroot, dirs, filesinos.walk('build'):
forfilenameinfiles:
iffilename.startswith(self.module_libs):
os.unlink(os.path.join(root, filename))
# overwrite header and library search paths
env=os.environ.copy()
env["CPPFLAGS"] ="-I{}".format(self.include_dir)
env["LDFLAGS"] ="-L{}".format(self.lib_dir)
# set rpath
env["LD_RUN_PATH"] =self.lib_dir
log.info("Rebuilding Python modules")
cmd= ["make", "sharedmods", "checksharedmods"]
self._subprocess_call(cmd, env=env)
self.check_imports()
defcheck_imports(self):
cmd= [sys.executable, "-c", "import _ssl; import _hashlib"]
self._subprocess_call(cmd)
defcheck_pyssl(self):
version=self.pyssl_version
ifself.versionnotinversion:
raiseValueError(version)
defrun_python_tests(self, tests, network=True):
ifnottests:
cmd= [
sys.executable,
os.path.join(PYTHONROOT, 'Lib/test/ssltests.py'),
'-j0'
]
elifsys.version_info< (3, 3):
cmd= [sys.executable, '-m', 'test.regrtest']
else:
cmd= [sys.executable, '-m', 'test', '-j0']
ifnetwork:
cmd.extend(['-u', 'network', '-u', 'urlfetch'])
cmd.extend(['-w', '-r'])
cmd.extend(tests)
self._subprocess_call(cmd, stdout=None)
classBuildOpenSSL(AbstractBuilder):
library="OpenSSL"
url_templates= (
"https://github.com/openssl/openssl/releases/download/openssl-{v}/openssl-{v}.tar.gz",
"https://www.openssl.org/source/openssl-{v}.tar.gz",
"https://www.openssl.org/source/old/{s}/openssl-{v}.tar.gz"
)
src_template="openssl-{}.tar.gz"
build_template="openssl-{}"
# only install software, skip docs
install_target='install_sw'
depend_target='depend'
def_post_install(self):
ifself.version.startswith("3."):
self._post_install_3xx()
def_build_src(self, config_args=()):
ifself.version.startswith("3."):
config_args+= ("enable-fips",)
super()._build_src(config_args)
def_post_install_3xx(self):
# create ssl/ subdir with example configs
# Install FIPS module
self._subprocess_call(
["make", "-j1", "install_ssldirs", "install_fips"],
cwd=self.build_dir
)
ifnotos.path.isdir(self.lib_dir):
# 3.0.0-beta2 uses lib64 on 64 bit platforms
lib64=self.lib_dir+"64"
os.symlink(lib64, self.lib_dir)
@property
defshort_version(self):
"""Short version for OpenSSL download URL"""
mo=re.search(r"^(\d+)\.(\d+)\.(\d+)", self.version)
parsed=tuple(int(m) forminmo.groups())
ifparsed< (1, 0, 0):
return"0.9.x"
ifparsed>= (3, 0, 0):
# OpenSSL 3.0.0 -> /old/3.0/
parsed=parsed[:2]
return".".join(str(i) foriinparsed)
classBuildLibreSSL(AbstractBuilder):
library="LibreSSL"
url_templates= (
"https://ftp.openbsd.org/pub/OpenBSD/LibreSSL/libressl-{v}.tar.gz",
)
src_template="libressl-{}.tar.gz"
build_template="libressl-{}"
defconfigure_make():
ifnotos.path.isfile('Makefile'):
log.info('Running ./configure')
subprocess.check_call([
'./configure', '--config-cache', '--quiet',
'--with-pydebug'
])
log.info('Running make')
subprocess.check_call(['make', '--quiet'])
defmain():
args=parser.parse_args()
ifnotargs.opensslandnotargs.libressl:
args.openssl=list(OPENSSL_RECENT_VERSIONS)
args.libressl=list(LIBRESSL_RECENT_VERSIONS)
ifnotargs.disable_ancient:
args.openssl.extend(OPENSSL_OLD_VERSIONS)
args.libressl.extend(LIBRESSL_OLD_VERSIONS)
logging.basicConfig(
level=logging.DEBUGifargs.debugelselogging.INFO,
format="*** %(levelname)s %(message)s"
)
start=datetime.now()
ifargs.stepsin {'modules', 'tests'}:
fornamein ['Makefile.pre.in', 'Modules/_ssl.c']:
ifnotos.path.isfile(os.path.join(PYTHONROOT, name)):
parser.error(
"Must be executed from CPython build dir"
)
ifnotos.path.samefile('python', sys.executable):
parser.error(
"Must be executed with ./python from CPython build dir"
)
# check for configure and run make
configure_make()
# download and register builder
builds= []
forversioninargs.openssl:
build=BuildOpenSSL(
version,
args
)
build.install()
builds.append(build)
forversioninargs.libressl:
build=BuildLibreSSL(
version,
args
)
build.install()
builds.append(build)
ifargs.stepsin {'modules', 'tests'}:
forbuildinbuilds:
try:
build.recompile_pymods()
build.check_pyssl()
ifargs.steps=='tests':
build.run_python_tests(
tests=args.tests,
network=args.network,
)
exceptExceptionase:
log.exception("%s failed", build)
print("{} failed: {}".format(build, e), file=sys.stderr)
sys.exit(2)
log.info("\n{} finished in {}".format(
args.steps.capitalize(),
datetime.now() -start
))
print('Python: ', sys.version)
ifargs.steps=='tests':
ifargs.tests:
print('Executed Tests:', ' '.join(args.tests))
else:
print('Executed all SSL tests.')
print('OpenSSL / LibreSSL versions:')
forbuildinbuilds:
print(" * {0.library} {0.version}".format(build))
if__name__=="__main__":
main()