Debian Codegraph @

Tools/ssl/multissltests.py

raw
1 #!./python
2 """Run Python tests against multiple installations of OpenSSL and LibreSSL
3
4 The script
5
6 (1) downloads OpenSSL / LibreSSL tar bundle
7 (2) extracts it to ./src
8 (3) compiles OpenSSL / LibreSSL
9 (4) installs OpenSSL / LibreSSL into ../multissl/$LIB/$VERSION/
10 (5) forces a recompilation of Python modules using the
11 header and library files from ../multissl/$LIB/$VERSION/
12 (6) runs Python's test suite
13
14 The script must be run with Python's build directory as current working
15 directory.
16
17 The script uses LD_RUN_PATH, LD_LIBRARY_PATH, CPPFLAGS and LDFLAGS to bend
18 search paths for header files and shared libraries. It's known to work on
19 Linux with GCC and clang.
20
21 Please keep this script compatible with Python 2.7, and 3.4 to 3.7.
22
23 (c) 2013-2017 Christian Heimes <[email protected]>
24 """
25 from __future__ import print_function
26
27 import argparse
28 from datetime import datetime
29 import logging
30 import os
31 try:
32 from urllib.request import urlopen
33 from urllib.error import HTTPError
34 except ImportError:
35 from urllib2 import urlopen, HTTPError
36 import re
37 import shutil
38 import subprocess
39 import sys
40 import tarfile
41
42
43 log = logging.getLogger("multissl")
44
45 OPENSSL_OLD_VERSIONS = [
46 "1.1.1w",
47 "3.1.8",
48 "3.2.6",
49 "3.3.7",
50 ]
51
52 OPENSSL_RECENT_VERSIONS = [
53 "3.0.21",
54 "3.4.6",
55 "3.5.7",
56 "3.6.3",
57 # See make_ssl_data.py for notes on adding a new version.
58 ]
59
60 LIBRESSL_OLD_VERSIONS = [
61 ]
62
63 LIBRESSL_RECENT_VERSIONS = [
64 ]
65
66 # store files in ../multissl
67 HERE = os.path.dirname(os.path.abspath(__file__))
68 PYTHONROOT = os.path.abspath(os.path.join(HERE, '..', '..'))
69 MULTISSL_DIR = os.path.abspath(os.path.join(PYTHONROOT, '..', 'multissl'))
70
71
72 parser = argparse.ArgumentParser(
73 prog='multissl',
74 description=(
75 "Run CPython tests with multiple cryptography libraries/versions."
76 ),
77 )
78 parser.add_argument(
79 '--debug',
80 action='store_true',
81 help="Enable debug logging",
82 )
83 parser.add_argument(
84 '--disable-ancient',
85 action='store_true',
86 help="Don't test OpenSSL and LibreSSL versions without upstream support",
87 )
88 parser.add_argument(
89 '--openssl',
90 nargs='+',
91 default=(),
92 help=(
93 "OpenSSL versions, defaults to '{}' (ancient: '{}') if no "
94 "OpenSSL and LibreSSL versions are given."
95 ).format(OPENSSL_RECENT_VERSIONS, OPENSSL_OLD_VERSIONS)
96 )
97 parser.add_argument(
98 '--libressl',
99 nargs='+',
100 default=(),
101 help=(
102 "LibreSSL versions, defaults to '{}' (ancient: '{}') if no "
103 "OpenSSL and LibreSSL versions are given."
104 ).format(LIBRESSL_RECENT_VERSIONS, LIBRESSL_OLD_VERSIONS)
105 )
106 parser.add_argument(
107 '--tests',
108 nargs='*',
109 default=(),
110 help="Python tests to run, defaults to all SSL related tests.",
111 )
112 parser.add_argument(
113 '--base-directory',
114 default=MULTISSL_DIR,
115 help="Base directory for OpenSSL / LibreSSL sources and builds."
116 )
117 parser.add_argument(
118 '--no-network',
119 action='store_false',
120 dest='network',
121 help="Disable network tests."
122 )
123 parser.add_argument(
124 '--steps',
125 choices=['library', 'modules', 'tests'],
126 default='tests',
127 help=(
128 "Which steps to perform. 'library' downloads and compiles OpenSSL "
129 "or LibreSSL. 'module' also compiles Python modules. 'tests' builds "
130 "all and runs the test suite."
131 )
132 )
133 parser.add_argument(
134 '--system',
135 default='',
136 help="Override the automatic system type detection."
137 )
138 parser.add_argument(
139 '--force',
140 action='store_true',
141 dest='force',
142 help="Force build and installation."
143 )
144 parser.add_argument(
145 '--keep-sources',
146 action='store_true',
147 dest='keep_sources',
148 help="Keep original sources for debugging."
149 )
150 parser.add_argument(
151 '--tsan',
152 action='store_true',
153 dest='tsan',
154 help="Build with thread sanitizer. (Disables fips in OpenSSL 3.x)."
155 )
156
157
158 class AbstractBuilder(object):
159 library = None
160 url_templates = None
161 src_template = None
162 build_template = None
163 depend_target = None
164 install_target = 'install'
165 if hasattr(os, 'process_cpu_count'):
166 jobs = os.process_cpu_count()
167 else:
168 jobs = os.cpu_count()
169
170 module_files = (
171 os.path.join(PYTHONROOT, "Modules/_ssl.c"),
172 os.path.join(PYTHONROOT, "Modules/_hashopenssl.c"),
173 )
174 module_libs = ("_ssl", "_hashlib")
175
176 def __init__(self, version, args):
177 self.version = version
178 self.args = args
179 # installation directory
180 self.install_dir = os.path.join(
181 os.path.join(args.base_directory, self.library.lower()), version
182 )
183 # source file
184 self.src_dir = os.path.join(args.base_directory, 'src')
185 self.src_file = os.path.join(
186 self.src_dir, self.src_template.format(version))
187 # build directory (removed after install)
188 self.build_dir = os.path.join(
189 self.src_dir, self.build_template.format(version))
190 self.system = args.system
191
192 def __str__(self):
193 return "<{0.__class__.__name__} for {0.version}>".format(self)
194
195 def __eq__(self, other):
196 if not isinstance(other, AbstractBuilder):
197 return NotImplemented
198 return (
199 self.library == other.library
200 and self.version == other.version
201 )
202
203 def __hash__(self):
204 return hash((self.library, self.version))
205
206 @property
207 def short_version(self):
208 """Short version for OpenSSL download URL"""
209 return None
210
211 @property
212 def openssl_cli(self):
213 """openssl CLI binary"""
214 return os.path.join(self.install_dir, "bin", "openssl")
215
216 @property
217 def openssl_version(self):
218 """output of 'bin/openssl version'"""
219 cmd = [self.openssl_cli, "version"]
220 return self._subprocess_output(cmd)
221
222 @property
223 def pyssl_version(self):
224 """Value of ssl.OPENSSL_VERSION"""
225 cmd = [
226 sys.executable,
227 '-c', 'import ssl; print(ssl.OPENSSL_VERSION)'
228 ]
229 return self._subprocess_output(cmd)
230
231 @property
232 def include_dir(self):
233 return os.path.join(self.install_dir, "include")
234
235 @property
236 def lib_dir(self):
237 return os.path.join(self.install_dir, "lib")
238
239 @property
240 def has_openssl(self):
241 return os.path.isfile(self.openssl_cli)
242
243 @property
244 def has_src(self):
245 return os.path.isfile(self.src_file)
246
247 def _subprocess_call(self, cmd, env=None, **kwargs):
248 log.debug("Call '{}'".format(" ".join(cmd)))
249 return subprocess.check_call(cmd, env=env, **kwargs)
250
251 def _subprocess_output(self, cmd, env=None, **kwargs):
252 log.debug("Call '{}'".format(" ".join(cmd)))
253 if env is None:
254 env = os.environ.copy()
255 env["LD_LIBRARY_PATH"] = self.lib_dir
256 out = subprocess.check_output(cmd, env=env, **kwargs)
257 return out.strip().decode("utf-8")
258
259 def _download_src(self):
260 """Download sources"""
261 src_dir = os.path.dirname(self.src_file)
262 if not os.path.isdir(src_dir):
263 os.makedirs(src_dir)
264 data = None
265 for url_template in self.url_templates:
266 url = url_template.format(v=self.version, s=self.short_version)
267 log.info("Downloading from {}".format(url))
268 try:
269 req = urlopen(url)
270 # KISS, read all, write all
271 data = req.read()
272 except HTTPError as e:
273 log.error(
274 "Download from {} has from failed: {}".format(url, e)
275 )
276 else:
277 log.info("Successfully downloaded from {}".format(url))
278 break
279 if data is None:
280 raise ValueError("All download URLs have failed")
281 log.info("Storing {}".format(self.src_file))
282 with open(self.src_file, "wb") as f:
283 f.write(data)
284
285 def _unpack_src(self):
286 """Unpack tar.gz bundle"""
287 # cleanup
288 if os.path.isdir(self.build_dir):
289 shutil.rmtree(self.build_dir)
290 os.makedirs(self.build_dir)
291
292 tf = tarfile.open(self.src_file)
293 name = self.build_template.format(self.version)
294 base = name + '/'
295 # force extraction into build dir
296 members = tf.getmembers()
297 for member in list(members):
298 if member.name == name:
299 members.remove(member)
300 elif not member.name.startswith(base):
301 raise ValueError(member.name, base)
302 member.name = member.name[len(base):].lstrip('/')
303 log.info("Unpacking files to {}".format(self.build_dir))
304 tf.extractall(self.build_dir, members, filter='data')
305
306 def _build_src(self, config_args=()):
307 """Now build openssl"""
308 log.info("Running build in {}".format(self.build_dir))
309 cwd = self.build_dir
310 if self.args.tsan:
311 config_args += ("-fsanitize=thread",)
312 cmd = [
313 "./config", *config_args,
314 "shared", "--debug",
315 "--prefix={}".format(self.install_dir)
316 ]
317 # cmd.extend(["no-deprecated", "--api=1.1.0"])
318 env = os.environ.copy()
319 # set rpath
320 env["LD_RUN_PATH"] = self.lib_dir
321 if self.system:
322 env['SYSTEM'] = self.system
323 self._subprocess_call(cmd, cwd=cwd, env=env)
324 if self.depend_target:
325 self._subprocess_call(
326 ["make", "-j1", self.depend_target], cwd=cwd, env=env
327 )
328 self._subprocess_call(["make", f"-j{self.jobs}"], cwd=cwd, env=env)
329
330 def _make_install(self):
331 self._subprocess_call(
332 ["make", "-j1", self.install_target],
333 cwd=self.build_dir
334 )
335 self._post_install()
336 if not self.args.keep_sources:
337 shutil.rmtree(self.build_dir)
338
339 def _post_install(self):
340 pass
341
342 def install(self):
343 log.info(self.openssl_cli)
344 if not self.has_openssl or self.args.force:
345 if not self.has_src:
346 self._download_src()
347 else:
348 log.debug("Already has src {}".format(self.src_file))
349 self._unpack_src()
350 self._build_src()
351 self._make_install()
352 else:
353 log.info("Already has installation {}".format(self.install_dir))
354 # validate installation
355 version = self.openssl_version
356 if self.version not in version:
357 raise ValueError(version)
358
359 def recompile_pymods(self):
360 log.warning("Using build from {}".format(self.build_dir))
361 # force a rebuild of all modules that use OpenSSL APIs
362 for fname in self.module_files:
363 os.utime(fname, None)
364 # remove all build artefacts
365 for root, dirs, files in os.walk('build'):
366 for filename in files:
367 if filename.startswith(self.module_libs):
368 os.unlink(os.path.join(root, filename))
369
370 # overwrite header and library search paths
371 env = os.environ.copy()
372 env["CPPFLAGS"] = "-I{}".format(self.include_dir)
373 env["LDFLAGS"] = "-L{}".format(self.lib_dir)
374 # set rpath
375 env["LD_RUN_PATH"] = self.lib_dir
376
377 log.info("Rebuilding Python modules")
378 cmd = ["make", "sharedmods", "checksharedmods"]
379 self._subprocess_call(cmd, env=env)
380 self.check_imports()
381
382 def check_imports(self):
383 cmd = [sys.executable, "-c", "import _ssl; import _hashlib"]
384 self._subprocess_call(cmd)
385
386 def check_pyssl(self):
387 version = self.pyssl_version
388 if self.version not in version:
389 raise ValueError(version)
390
391 def run_python_tests(self, tests, network=True):
392 if not tests:
393 cmd = [
394 sys.executable,
395 os.path.join(PYTHONROOT, 'Lib/test/ssltests.py'),
396 '-j0'
397 ]
398 elif sys.version_info < (3, 3):
399 cmd = [sys.executable, '-m', 'test.regrtest']
400 else:
401 cmd = [sys.executable, '-m', 'test', '-j0']
402 if network:
403 cmd.extend(['-u', 'network', '-u', 'urlfetch'])
404 cmd.extend(['-w', '-r'])
405 cmd.extend(tests)
406 self._subprocess_call(cmd, stdout=None)
407
408
409 class BuildOpenSSL(AbstractBuilder):
410 library = "OpenSSL"
411 url_templates = (
412 "https://github.com/openssl/openssl/releases/download/openssl-{v}/openssl-{v}.tar.gz",
413 "https://www.openssl.org/source/openssl-{v}.tar.gz",
414 "https://www.openssl.org/source/old/{s}/openssl-{v}.tar.gz"
415 )
416 src_template = "openssl-{}.tar.gz"
417 build_template = "openssl-{}"
418 # only install software, skip docs
419 install_target = 'install_sw'
420 depend_target = 'depend'
421
422 def _post_install(self):
423 if self.version.startswith("3."):
424 self._post_install_3xx()
425
426 def _build_src(self, config_args=()):
427 if self.version.startswith("3."):
428 config_args += ("enable-fips",)
429 super()._build_src(config_args)
430
431 def _post_install_3xx(self):
432 # create ssl/ subdir with example configs
433 # Install FIPS module
434 self._subprocess_call(
435 ["make", "-j1", "install_ssldirs", "install_fips"],
436 cwd=self.build_dir
437 )
438 if not os.path.isdir(self.lib_dir):
439 # 3.0.0-beta2 uses lib64 on 64 bit platforms
440 lib64 = self.lib_dir + "64"
441 os.symlink(lib64, self.lib_dir)
442
443 @property
444 def short_version(self):
445 """Short version for OpenSSL download URL"""
446 mo = re.search(r"^(\d+)\.(\d+)\.(\d+)", self.version)
447 parsed = tuple(int(m) for m in mo.groups())
448 if parsed < (1, 0, 0):
449 return "0.9.x"
450 if parsed >= (3, 0, 0):
451 # OpenSSL 3.0.0 -> /old/3.0/
452 parsed = parsed[:2]
453 return ".".join(str(i) for i in parsed)
454
455
456 class BuildLibreSSL(AbstractBuilder):
457 library = "LibreSSL"
458 url_templates = (
459 "https://ftp.openbsd.org/pub/OpenBSD/LibreSSL/libressl-{v}.tar.gz",
460 )
461 src_template = "libressl-{}.tar.gz"
462 build_template = "libressl-{}"
463
464
465 def configure_make():
466 if not os.path.isfile('Makefile'):
467 log.info('Running ./configure')
468 subprocess.check_call([
469 './configure', '--config-cache', '--quiet',
470 '--with-pydebug'
471 ])
472
473 log.info('Running make')
474 subprocess.check_call(['make', '--quiet'])
475
476
477 def main():
478 args = parser.parse_args()
479 if not args.openssl and not args.libressl:
480 args.openssl = list(OPENSSL_RECENT_VERSIONS)
481 args.libressl = list(LIBRESSL_RECENT_VERSIONS)
482 if not args.disable_ancient:
483 args.openssl.extend(OPENSSL_OLD_VERSIONS)
484 args.libressl.extend(LIBRESSL_OLD_VERSIONS)
485
486 logging.basicConfig(
487 level=logging.DEBUG if args.debug else logging.INFO,
488 format="*** %(levelname)s %(message)s"
489 )
490
491 start = datetime.now()
492
493 if args.steps in {'modules', 'tests'}:
494 for name in ['Makefile.pre.in', 'Modules/_ssl.c']:
495 if not os.path.isfile(os.path.join(PYTHONROOT, name)):
496 parser.error(
497 "Must be executed from CPython build dir"
498 )
499 if not os.path.samefile('python', sys.executable):
500 parser.error(
501 "Must be executed with ./python from CPython build dir"
502 )
503 # check for configure and run make
504 configure_make()
505
506 # download and register builder
507 builds = []
508
509 for version in args.openssl:
510 build = BuildOpenSSL(
511 version,
512 args
513 )
514 build.install()
515 builds.append(build)
516
517 for version in args.libressl:
518 build = BuildLibreSSL(
519 version,
520 args
521 )
522 build.install()
523 builds.append(build)
524
525 if args.steps in {'modules', 'tests'}:
526 for build in builds:
527 try:
528 build.recompile_pymods()
529 build.check_pyssl()
530 if args.steps == 'tests':
531 build.run_python_tests(
532 tests=args.tests,
533 network=args.network,
534 )
535 except Exception as e:
536 log.exception("%s failed", build)
537 print("{} failed: {}".format(build, e), file=sys.stderr)
538 sys.exit(2)
539
540 log.info("\n{} finished in {}".format(
541 args.steps.capitalize(),
542 datetime.now() - start
543 ))
544 print('Python: ', sys.version)
545 if args.steps == 'tests':
546 if args.tests:
547 print('Executed Tests:', ' '.join(args.tests))
548 else:
549 print('Executed all SSL tests.')
550
551 print('OpenSSL / LibreSSL versions:')
552 for build in builds:
553 print(" * {0.library} {0.version}".format(build))
554
555
556 if __name__ == "__main__":
557 main()