ยปCore Development>Code coverage>Tools/scripts/get-remote-certificate.py

Python code coverage for Tools/scripts/get-remote-certificate.py

#countcontent
1n/a#!/usr/bin/env python3
2n/a#
3n/a# fetch the certificate that the server(s) are providing in PEM form
4n/a#
5n/a# args are HOST:PORT [, HOST:PORT...]
6n/a#
7n/a# By Bill Janssen.
8n/a
9n/aimport re
10n/aimport os
11n/aimport sys
12n/aimport tempfile
13n/a
14n/a
15n/adef fetch_server_certificate (host, port):
16n/a
17n/a def subproc(cmd):
18n/a from subprocess import Popen, PIPE, STDOUT
19n/a proc = Popen(cmd, stdout=PIPE, stderr=STDOUT, shell=True)
20n/a status = proc.wait()
21n/a output = proc.stdout.read()
22n/a return status, output
23n/a
24n/a def strip_to_x509_cert(certfile_contents, outfile=None):
25n/a m = re.search(br"^([-]+BEGIN CERTIFICATE[-]+[\r]*\n"
26n/a br".*[\r]*^[-]+END CERTIFICATE[-]+)$",
27n/a certfile_contents, re.MULTILINE | re.DOTALL)
28n/a if not m:
29n/a return None
30n/a else:
31n/a tn = tempfile.mktemp()
32n/a fp = open(tn, "wb")
33n/a fp.write(m.group(1) + b"\n")
34n/a fp.close()
35n/a try:
36n/a tn2 = (outfile or tempfile.mktemp())
37n/a status, output = subproc(r'openssl x509 -in "%s" -out "%s"' %
38n/a (tn, tn2))
39n/a if status != 0:
40n/a raise RuntimeError('OpenSSL x509 failed with status %s and '
41n/a 'output: %r' % (status, output))
42n/a fp = open(tn2, 'rb')
43n/a data = fp.read()
44n/a fp.close()
45n/a os.unlink(tn2)
46n/a return data
47n/a finally:
48n/a os.unlink(tn)
49n/a
50n/a if sys.platform.startswith("win"):
51n/a tfile = tempfile.mktemp()
52n/a fp = open(tfile, "w")
53n/a fp.write("quit\n")
54n/a fp.close()
55n/a try:
56n/a status, output = subproc(
57n/a 'openssl s_client -connect "%s:%s" -showcerts < "%s"' %
58n/a (host, port, tfile))
59n/a finally:
60n/a os.unlink(tfile)
61n/a else:
62n/a status, output = subproc(
63n/a 'openssl s_client -connect "%s:%s" -showcerts < /dev/null' %
64n/a (host, port))
65n/a if status != 0:
66n/a raise RuntimeError('OpenSSL connect failed with status %s and '
67n/a 'output: %r' % (status, output))
68n/a certtext = strip_to_x509_cert(output)
69n/a if not certtext:
70n/a raise ValueError("Invalid response received from server at %s:%s" %
71n/a (host, port))
72n/a return certtext
73n/a
74n/a
75n/aif __name__ == "__main__":
76n/a if len(sys.argv) < 2:
77n/a sys.stderr.write(
78n/a "Usage: %s HOSTNAME:PORTNUMBER [, HOSTNAME:PORTNUMBER...]\n" %
79n/a sys.argv[0])
80n/a sys.exit(1)
81n/a for arg in sys.argv[1:]:
82n/a host, port = arg.split(":")
83n/a sys.stdout.buffer.write(fetch_server_certificate(host, int(port)))
84n/a sys.exit(0)