Debian Codegraph @

Tools/ssl/multissltests.py

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