Debian Codegraph @

cpython27/Tools/ssl/multissltests.py

raw symbols SCIP
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 except ImportError:
34 from urllib2 import urlopen
35 import subprocess
36 import shutil
37 import sys
38 import tarfile
39
40
41 log = logging.getLogger("multissl")
42
43 OPENSSL_OLD_VERSIONS = [
44 "1.0.1u",
45 "1.0.2o",
46 ]
47
48 OPENSSL_RECENT_VERSIONS = [
49 "1.0.2t",
50 "1.1.0l",
51 "1.1.1f",
52 ]
53
54 LIBRESSL_OLD_VERSIONS = [
55 "2.3.10",
56 "2.4.5",
57 ]
58
59 LIBRESSL_RECENT_VERSIONS = [
60 "2.5.5",
61 "2.6.5",
62 "2.7.4",
63 ]
64
65 # store files in ../multissl
66 HERE = os.path.dirname(os.path.abspath(__file__))
67 PYTHONROOT = os.path.abspath(os.path.join(HERE, '..', '..'))
68 MULTISSL_DIR = os.path.abspath(os.path.join(PYTHONROOT, '..', 'multissl'))
69
70
71 parser = argparse.ArgumentParser(
72 prog='multissl',
73 description=(
74 "Run CPython tests with multiple OpenSSL and LibreSSL "
75 "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 < 1.0.2 and LibreSSL < 2.5.3.",
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
134 parser.add_argument(
135 '--force',
136 action='store_true',
137 dest='force',
138 help="Force build and installation."
139 )
140 parser.add_argument(
141 '--keep-sources',
142 action='store_true',
143 dest='keep_sources',
144 help="Keep original sources for debugging."
145 )
146
147 class AbstractBuilder(object):
148 library = None
149 url_template = None
150 src_template = None
151 build_template = None
152 install_target = 'install'
153
154 module_files = ("Modules/_ssl.c",
155 "Modules/_hashopenssl.c")
156 module_libs = ("_ssl", "_hashlib")
157
158 def __init__(self, version, args):
159 self.version = version
160 self.args = args
161 # installation directory
162 self.install_dir = os.path.join(
163 os.path.join(args.base_directory, self.library.lower()), version
164 )
165 # source file
166 self.src_dir = os.path.join(args.base_directory, 'src')
167 self.src_file = os.path.join(
168 self.src_dir, self.src_template.format(version))
169 # build directory (removed after install)
170 self.build_dir = os.path.join(
171 self.src_dir, self.build_template.format(version))
172
173 def __str__(self):
174 return "<{0.__class__.__name__} for {0.version}>".format(self)
175
176 def __eq__(self, other):
177 if not isinstance(other, AbstractBuilder):
178 return NotImplemented
179 return (
180 self.library == other.library
181 and self.version == other.version
182 )
183
184 def __hash__(self):
185 return hash((self.library, self.version))
186
187 @property
188 def openssl_cli(self):
189 """openssl CLI binary"""
190 return os.path.join(self.install_dir, "bin", "openssl")
191
192 @property
193 def openssl_version(self):
194 """output of 'bin/openssl version'"""
195 cmd = [self.openssl_cli, "version"]
196 return self._subprocess_output(cmd)
197
198 @property
199 def pyssl_version(self):
200 """Value of ssl.OPENSSL_VERSION"""
201 cmd = [
202 sys.executable,
203 '-c', 'import ssl; print(ssl.OPENSSL_VERSION)'
204 ]
205 return self._subprocess_output(cmd)
206
207 @property
208 def include_dir(self):
209 return os.path.join(self.install_dir, "include")
210
211 @property
212 def lib_dir(self):
213 return os.path.join(self.install_dir, "lib")
214
215 @property
216 def has_openssl(self):
217 return os.path.isfile(self.openssl_cli)
218
219 @property
220 def has_src(self):
221 return os.path.isfile(self.src_file)
222
223 def _subprocess_call(self, cmd, env=None, **kwargs):
224 log.debug("Call '{}'".format(" ".join(cmd)))
225 return subprocess.check_call(cmd, env=env, **kwargs)
226
227 def _subprocess_output(self, cmd, env=None, **kwargs):
228 log.debug("Call '{}'".format(" ".join(cmd)))
229 if env is None:
230 env = os.environ.copy()
231 env["LD_LIBRARY_PATH"] = self.lib_dir
232 out = subprocess.check_output(cmd, env=env, **kwargs)
233 return out.strip().decode("utf-8")
234
235 def _download_src(self):
236 """Download sources"""
237 src_dir = os.path.dirname(self.src_file)
238 if not os.path.isdir(src_dir):
239 os.makedirs(src_dir)
240 url = self.url_template.format(self.version)
241 log.info("Downloading from {}".format(url))
242 req = urlopen(url)
243 # KISS, read all, write all
244 data = req.read()
245 log.info("Storing {}".format(self.src_file))
246 with open(self.src_file, "wb") as f:
247 f.write(data)
248
249 def _unpack_src(self):
250 """Unpack tar.gz bundle"""
251 # cleanup
252 if os.path.isdir(self.build_dir):
253 shutil.rmtree(self.build_dir)
254 os.makedirs(self.build_dir)
255
256 tf = tarfile.open(self.src_file)
257 name = self.build_template.format(self.version)
258 base = name + '/'
259 # force extraction into build dir
260 members = tf.getmembers()
261 for member in list(members):
262 if member.name == name:
263 members.remove(member)
264 elif not member.name.startswith(base):
265 raise ValueError(member.name, base)
266 member.name = member.name[len(base):].lstrip('/')
267 log.info("Unpacking files to {}".format(self.build_dir))
268 tf.extractall(self.build_dir, members)
269
270 def _build_src(self):
271 """Now build openssl"""
272 log.info("Running build in {}".format(self.build_dir))
273 cwd = self.build_dir
274 cmd = [
275 "./config",
276 "shared", "--debug",
277 "--prefix={}".format(self.install_dir)
278 ]
279 env = os.environ.copy()
280 # set rpath
281 env["LD_RUN_PATH"] = self.lib_dir
282 self._subprocess_call(cmd, cwd=cwd)
283 # Old OpenSSL versions do not support parallel builds.
284 self._subprocess_call(["make", "-j1"], cwd=cwd)
285
286 def _make_install(self):
287 self._subprocess_call(
288 ["make", "-j1", self.install_target],
289 cwd=self.build_dir
290 )
291 if not self.args.keep_sources:
292 shutil.rmtree(self.build_dir)
293
294 def install(self):
295 log.info(self.openssl_cli)
296 if not self.has_openssl or self.args.force:
297 if not self.has_src:
298 self._download_src()
299 else:
300 log.debug("Already has src {}".format(self.src_file))
301 self._unpack_src()
302 self._build_src()
303 self._make_install()
304 else:
305 log.info("Already has installation {}".format(self.install_dir))
306 # validate installation
307 version = self.openssl_version
308 if self.version not in version:
309 raise ValueError(version)
310
311 def recompile_pymods(self):
312 log.warning("Using build from {}".format(self.build_dir))
313 # force a rebuild of all modules that use OpenSSL APIs
314 for fname in self.module_files:
315 os.utime(fname, None)
316 # remove all build artefacts
317 for root, dirs, files in os.walk('build'):
318 for filename in files:
319 if filename.startswith(self.module_libs):
320 os.unlink(os.path.join(root, filename))
321
322 # overwrite header and library search paths
323 env = os.environ.copy()
324 env["CPPFLAGS"] = "-I{}".format(self.include_dir)
325 env["LDFLAGS"] = "-L{}".format(self.lib_dir)
326 # set rpath
327 env["LD_RUN_PATH"] = self.lib_dir
328
329 log.info("Rebuilding Python modules")
330 cmd = [sys.executable, "setup.py", "build"]
331 self._subprocess_call(cmd, env=env)
332 self.check_imports()
333
334 def check_imports(self):
335 cmd = [sys.executable, "-c", "import _ssl; import _hashlib"]
336 self._subprocess_call(cmd)
337
338 def check_pyssl(self):
339 version = self.pyssl_version
340 if self.version not in version:
341 raise ValueError(version)
342
343 def run_python_tests(self, tests, network=True):
344 if not tests:
345 cmd = [sys.executable, 'Lib/test/ssltests.py', '-j0']
346 elif sys.version_info < (3, 3):
347 cmd = [sys.executable, '-m', 'test.regrtest']
348 else:
349 cmd = [sys.executable, '-m', 'test', '-j0']
350 if network:
351 cmd.extend(['-u', 'network', '-u', 'urlfetch'])
352 cmd.extend(['-w', '-r'])
353 cmd.extend(tests)
354 self._subprocess_call(cmd, stdout=None)
355
356
357 class BuildOpenSSL(AbstractBuilder):
358 library = "OpenSSL"
359 url_template = "https://www.openssl.org/source/openssl-{}.tar.gz"
360 src_template = "openssl-{}.tar.gz"
361 build_template = "openssl-{}"
362 # only install software, skip docs
363 install_target = 'install_sw'
364
365
366 class BuildLibreSSL(AbstractBuilder):
367 library = "LibreSSL"
368 url_template = (
369 "https://ftp.openbsd.org/pub/OpenBSD/LibreSSL/libressl-{}.tar.gz")
370 src_template = "libressl-{}.tar.gz"
371 build_template = "libressl-{}"
372
373
374 def configure_make():
375 if not os.path.isfile('Makefile'):
376 log.info('Running ./configure')
377 subprocess.check_call([
378 './configure', '--config-cache', '--quiet',
379 '--with-pydebug'
380 ])
381
382 log.info('Running make')
383 subprocess.check_call(['make', '--quiet'])
384
385
386 def main():
387 args = parser.parse_args()
388 if not args.openssl and not args.libressl:
389 args.openssl = list(OPENSSL_RECENT_VERSIONS)
390 args.libressl = list(LIBRESSL_RECENT_VERSIONS)
391 if not args.disable_ancient:
392 args.openssl.extend(OPENSSL_OLD_VERSIONS)
393 args.libressl.extend(LIBRESSL_OLD_VERSIONS)
394
395 logging.basicConfig(
396 level=logging.DEBUG if args.debug else logging.INFO,
397 format="*** %(levelname)s %(message)s"
398 )
399
400 start = datetime.now()
401
402 if args.steps in {'modules', 'tests'}:
403 for name in ['setup.py', 'Modules/_ssl.c']:
404 if not os.path.isfile(os.path.join(PYTHONROOT, name)):
405 parser.error(
406 "Must be executed with ./python from CPython build dir"
407 )
408 if not os.path.samefile('python', sys.executable):
409 parser.error(
410 "Must be executed with ./python from CPython build dir"
411 )
412
413 # check for configure and run make
414 configure_make()
415
416 # download and register builder
417 builds = []
418
419 for version in args.openssl:
420 build = BuildOpenSSL(
421 version,
422 args
423 )
424 build.install()
425 builds.append(build)
426
427 for version in args.libressl:
428 build = BuildLibreSSL(
429 version,
430 args
431 )
432 build.install()
433 builds.append(build)
434
435 if args.steps in {'modules', 'tests'}:
436 for build in builds:
437 try:
438 build.recompile_pymods()
439 build.check_pyssl()
440 if args.steps == 'tests':
441 build.run_python_tests(
442 tests=args.tests,
443 network=args.network,
444 )
445 except Exception as e:
446 log.exception("%s failed", build)
447 print("{} failed: {}".format(build, e), file=sys.stderr)
448 sys.exit(2)
449
450 log.info("\n{} finished in {}".format(
451 args.steps.capitalize(),
452 datetime.now() - start
453 ))
454 print('Python: ', sys.version)
455 if args.steps == 'tests':
456 if args.tests:
457 print('Executed Tests:', ' '.join(args.tests))
458 else:
459 print('Executed all SSL tests.')
460
461 print('OpenSSL / LibreSSL versions:')
462 for build in builds:
463 print(" * {0.library} {0.version}".format(build))
464
465
466 if __name__ == "__main__":
467 main()