Debian Codegraph @

blaeu-cert

raw symbols SCIP
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3
4 """ Python code to start a RIPE Atlas UDM (User-Defined
5 Measurement). This one is to test X.509/PKIX certificates in TLS servers.
6
7 You'll need an API key in ~/.atlas/auth.
8
9 After launching the measurement, it downloads the results and analyzes
10 them, displaying the name ("subject" in X.509 parlance) or issuer.
11
12 Stéphane Bortzmeyer <[email protected]>
13 """
14
15 import json
16 import time
17 import os
18 import string
19 import sys
20 import time
21 import socket
22 import collections
23 import copy
24
25 import Blaeu
26 from Blaeu import Host_Type
27
28 # https://github.com/pyca/pyopenssl https://pyopenssl.readthedocs.org/en/stable/
29 import OpenSSL.crypto
30 import cryptography
31
32 config = Blaeu.Config()
33 # Default values
34 config.display = "n" #Name
35 config.sni = True
36 config.hostname = None
37 config.entire_chain = False
38 # Override what's in the Blaeu package
39 config.port = 443
40
41 X509DATETIME = "%Y%m%d%H%M%SZ"
42 RFC3339DATETIME = "%Y-%m-%dT%H:%M:%SZ"
43
44 class Set():
45 def __init__(self):
46 self.total = 0
47
48 def usage(msg=None):
49 print("Usage: %s target-name-or-IP" % sys.argv[0], file=sys.stderr)
50 config.usage(msg)
51 print("""Also:
52 --issuer or -I : displays the issuer (default is to display the name)
53 --key or -k : displays the public key (default is to display the name)
54 --serial or -S : displays the serial number (default is to display the name)
55 --expiration or -E : displays the expiration datetime (default is to display the name)
56 --entire-chain : displays all the certificates (default is to display the first)
57 --hostname : hostname to send for SNI (default is to use the target)
58 --no-sni : do not send the SNI (Server Name Indication) (default is to send it)""",
59 file=sys.stderr)
60
61 def format_name(n):
62 result = ""
63 components = n.get_components()
64 for (k, v) in components:
65 result += "/%s=%s" % (k.decode(), v.decode())
66 return result
67
68 def specificParse(config, option, value):
69 result = True
70 if option == "--issuer" or option == "-I":
71 config.display = "i"
72 elif option == "--key" or option == "-k":
73 config.display = "k"
74 elif option == "--serial" or option == "-S":
75 config.display = "s"
76 elif option == "--expiration" or option == "-E":
77 config.display = "e"
78 elif option == "--entire-chain":
79 config.entire_chain = True
80 elif option == "--hostname":
81 config.hostname = value
82 elif option == "--no-sni":
83 config.sni = False
84 else:
85 result = False
86 return result
87
88 (args, data) = config.parse("IkSE", ["issuer", "serial", "expiration", "key", "entire-chain",
89 "hostname=", "no-sni"],
90 specificParse, usage)
91
92 if len(args) != 1:
93 usage("Not the good number of arguments")
94 sys.exit(1)
95 target = args[0]
96
97 if config.measurement_id is None:
98 data["definitions"][0]["target"] = target
99 data["definitions"][0]["type"] = "sslcert"
100 data["definitions"][0]["description"] = "X.509 cert of %s" % target
101 del data["definitions"][0]["size"] # Meaningless argument
102 target_type = Blaeu.host_type(target)
103 # RFC 6066 say that we cannot accept a literal IP
104 # address as hostname.
105 if target_type != Host_Type.Name and config.hostname is None and config.sni:
106 usage("If the target is an IP address, we need --hostname (or --no-sni)")
107 sys.exit(1)
108 if target_type == Host_Type.IPv6:
109 config.ipv4 = False
110 af = 6
111 if config.include is not None:
112 data["probes"][0]["tags"]["include"] = copy.copy(config.include)
113 data["probes"][0]["tags"]["include"].append("system-ipv6-works")
114 else:
115 data["probes"][0]["tags"]["include"] = ["system-ipv6-works",]
116 elif target_type == Host_Type.IPv4:
117 config.ipv4 = True
118 af = 4
119 if config.include is not None:
120 data["probes"][0]["tags"]["include"] = copy.copy(config.include)
121 data["probes"][0]["tags"]["include"].append("system-ipv4-works")
122 else:
123 data["probes"][0]["tags"]["include"] = ["system-ipv4-works",]
124 else:
125 # Hostname
126 if config.ipv4:
127 af = 4
128 else:
129 af = 6
130 data["definitions"][0]['af'] = af
131 if config.sni: # See above about RFC 6066
132 if config.hostname is not None: # Even if the target is a host
133 # name, we honor --hostname.
134 data["definitions"][0]['hostname'] = config.hostname
135 else:
136 data["definitions"][0]['hostname'] = target
137
138 if config.verbose:
139 print(data)
140
141 try:
142 measurement = Blaeu.Measurement(data)
143 except Blaeu.RequestSubmissionError as error:
144 print(Blaeu.format_error(error), file=sys.stderr)
145 sys.exit(1)
146 if config.verbose:
147 print("Measurement #%s to %s uses %i probes" % (measurement.id, target,
148 measurement.num_probes))
149 rdata = measurement.results(wait=True, percentage_required=config.percentage_required)
150 else:
151 measurement = Blaeu.Measurement(data=None, id=config.measurement_id)
152 rdata = measurement.results(wait=False)
153
154 sets = collections.defaultdict(Set)
155 if config.display_probe_asns:
156 config.display_probes = True
157 if config.display_probes:
158 probes_sets = collections.defaultdict(Set)
159 print(("%s probes reported" % len(rdata)))
160 for result in rdata:
161 if config.display_probes:
162 probe_id = result["prb_id"]
163 if config.display_probe_asns:
164 details = Blaeu.ProbeCache.cache_probe_id(config.cache_probes, probe_id) \
165 if config.cache_probes else Blaeu.Probe(probe_id)
166 asn = getattr(details, "asn_v%i" % (4 if config.ipv4 else 6), None)
167 if 'cert' in result:
168 value = []
169 if config.entire_chain:
170 num = len(result['cert'])
171 else:
172 num = 1
173 for i in range(0, num):
174 x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
175 str(result['cert'][i]))
176 detail = ""
177 content = format_name(x509.get_subject())
178 if config.display == "i":
179 content += format_name(x509.get_issuer())
180 elif config.display == "k":
181 key = x509.get_pubkey()
182 content = "%s, type %s, %s bits" % \
183 (key.to_cryptography_key().public_bytes(cryptography.hazmat.primitives.serialization.Encoding.PEM, cryptography.hazmat.primitives.serialization.PublicFormat.SubjectPublicKeyInfo).decode().replace("\n", " ").replace("-----BEGIN PUBLIC KEY----- ", "")[:80] + "...",
184 key.type(), key.bits())
185 elif config.display == "s":
186 content = format(x509.get_serial_number(), '05x')
187 elif config.display == "e":
188 if x509.has_expired():
189 detail = " (EXPIRED)"
190 t = time.strptime(x509.get_notAfter().decode(), X509DATETIME)
191 content = "%s%s" % (time.strftime(RFC3339DATETIME, t), detail)
192 value.append("%s%s" % (content, detail))
193 value = "; ".join(value)
194 else:
195 if 'err' in result:
196 error = result['err']
197 elif 'alert' in result:
198 error = result['alert']
199 else:
200 error = "UNKNOWN ERROR"
201 value = "FAILED TO GET A CERT: %s" % error
202 sets[value].total += 1
203 if config.display_probes:
204 if config.display_probe_asns:
205 info = [probe_id, asn]
206 else:
207 info = probe_id
208 if value in probes_sets:
209 probes_sets[value].append(info)
210 else:
211 probes_sets[value] = [info,]
212 sets_data = sorted(sets, key=lambda s: sets[s].total, reverse=False)
213 for myset in sets_data:
214 detail = ""
215 if config.display_probes:
216 detail = "(probes %s)" % probes_sets[myset]
217 print("[%s] : %i occurrences %s" % (myset, sets[myset].total, detail))
218
219 print(("Test #%s done at %s" % (measurement.id,
220 time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))))
221 print(f"Results on atlas.ripe.net : https://atlas.ripe.net/measurements/{measurement.id}")