forked from NotSqrt/sslrate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsslrate.py
326 lines (263 loc) · 9.5 KB
/
sslrate.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
#!/usr/bin/env python
from __future__ import print_function, unicode_literals
import tempfile
import re
import sys
import subprocess
import os
import logging
import argparse
from lxml import etree as ET
from functools import wraps
# Init logging
logging.basicConfig()
logger = logging.getLogger(__file__)
logger.setLevel(logging.INFO)
def log(text):
def outer_wrap(f):
@wraps(f)
def wrapper(*args, **kwargs):
result = f(*args, **kwargs)
logger.info('%s: %s', text, result)
return result
return wrapper
return outer_wrap
# Tools
def execute(cmd):
proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
return stdout.strip(), stderr.strip()
def wildcard_match(expression, hostname):
expression = r'^%s$' % (expression.replace('.', r'\.').replace(r'*\.', r'([^.]*\.)?'))
return re.match(expression, hostname, re.I) is not None
# Cipher utils
class Cipher(object):
def __init__(self, node):
self.node = node
self.name = node.attrib['name']
self.protocol = node.getparent().getparent().attrib['title'].split(' ', 1)[0].replace('_', '.')
def is_anonymous_diffie_hellman(self):
return 'ADH' in self.name
def is_export_suite(self):
return 'EXPORT' in self.name
def bitsize(self):
if 'keySize' not in self.node.attrib:
return None
bits = self.node.attrib['keySize']
if bits == 'Anon':
return 0
return int(bits.split(' ')[0])
def get_ciphers(tree, unique=True):
ciphers = []
names = set()
for node in tree.findall('.//acceptedCipherSuites/cipherSuite'):
cipher = Cipher(node)
if unique:
if cipher.name in names:
continue
else:
names.add(cipher.name)
ciphers.append(cipher)
return ciphers
# Scorer base
class Scorer(object):
def __init__(self):
pass
def describe(self, why, score):
logger.info('%s: %d', why, score)
return score
# Check cipher
class CipherScorer(Scorer):
def __init__(self, tree):
self.tree = tree
self.ciphers = get_ciphers(tree)
super(CipherScorer, self).__init__()
@staticmethod
def bit_score(bits):
if bits == 0:
return 0
elif 0 < bits < 128:
return 20
elif 128 <= bits < 256:
return 80
else:
return 100
@log('Total cipher score')
def score(self):
if len(self.ciphers) == 0:
raise Exception('No ciphers')
bitsizes = {}
for c in self.ciphers:
bitsizes.setdefault(c.bitsize(), set()).add(c.name)
weakest_bitsize = min(bitsizes)
weakest = self.describe('Weakest cipher bitsize (%s)' % ", ".join(bitsizes[weakest_bitsize]), weakest_bitsize)
strongest_bitsize = max(bitsizes)
strongest = self.describe('Strongest cipher bitsize (%s)' % ", ".join(bitsizes[strongest_bitsize]), strongest_bitsize)
return (CipherScorer.bit_score(weakest) + CipherScorer.bit_score(strongest)) / 2.0
# Rate protocol
class ProtocolScorer(Scorer):
def __init__(self, tree):
self.tree = tree
self.ciphers = get_ciphers(tree, unique=False)
super(ProtocolScorer, self).__init__()
@staticmethod
def score_protocol_name(name):
if name == 'SSLV2':
return 0
elif name == 'SSLV3':
return 80
elif name == 'TLSV1':
return 90
elif name == 'TLSV1.1':
return 95
elif name == 'TLSV1.2':
return 100
@log('Total protocol score')
def score(self):
if len(self.ciphers) == 0:
raise Exception('No ciphers accepted')
names = set([c.protocol for c in self.ciphers])
weakest = min([ProtocolScorer.score_protocol_name(c.protocol) for c in self.ciphers])
strongest = max([ProtocolScorer.score_protocol_name(c.protocol) for c in self.ciphers])
logger.info('Weakest protocol score: %s', weakest)
logger.info('strongest protocol score: %s', strongest)
return (weakest + strongest) / 2.0
# Rate key exchange
class KeyExchangeScorer(Scorer):
def __init__(self, tree):
self.tree = tree
self.ciphers = get_ciphers(tree, unique=False)
super(KeyExchangeScorer, self).__init__()
def cert(self):
try:
return self.tree.find('.//results/target/certinfo_basic/receivedCertificateChain/certificate[1]/asPEM').text
except Exception:
return None
@log('Public key size')
def get_key_size(self):
return int(self.tree.find('.//publicKeySize').text.split(' ')[0].strip())
@log('Has anonymous Diffie-Hellman suite')
def has_anonymous_diffie_hellman(self):
return any([c.is_anonymous_diffie_hellman() for c in self.ciphers])
@log('Has EXPORT key exchange suite')
def has_export_suite(self):
return any([c.is_export_suite() for c in self.ciphers])
@log('Is blacklisted (weak) key')
def is_blacklisted_key(self):
path = None
if not execute("which openssl-vulnkey")[0]:
logger.error("openssl-vulnkey is not installed")
return True
try:
with tempfile.NamedTemporaryFile(mode="w+", delete=False) as f:
path = f.name
f.write(self.cert())
stdout, stderr = execute("cat %s | openssl-vulnkey -" % path)
if b"Skipped" in stderr:
logger.warn("openssl-vulnkey: %s", stderr)
else:
return stdout[0:3].lower() != 'not'
finally:
if path is not None:
os.unlink(path)
@log('Total key exchange score')
def score(self):
if self.is_blacklisted_key():
return self.describe('Blacklisted key', 0)
if self.has_anonymous_diffie_hellman():
return self.describe('Anonymous Diffie-Hellman', 0)
if self.has_export_suite():
return self.describe('Export key exchange suite', 40)
key_size = self.get_key_size()
if key_size < 512:
return self.describe('Keysize < 512 bits', 20)
elif key_size < 1024:
return self.describe('Keysize < 1024 bits', 40)
elif key_size < 2048:
return self.describe('Keysize < 2048 bits', 80)
elif key_size < 4096:
return self.describe('Keysize < 4096 bits', 90)
else:
return self.describe('Keysize >= 4096 bits', 100)
# Rate cert
class CertificateScorer(Scorer):
def __init__(self, tree):
self.tree = tree
super(CertificateScorer, self).__init__()
@log('Hostname is valid')
def hostname_valid(self, hostname):
# Check subject common name
node = self.tree.find('.//subject/commonName')
if node is not None and wildcard_match(node.text, hostname):
return True
# Check SAN
nodes = self.tree.findall('.//X509v3SubjectAlternativeName/DNS/listEntry')
for node in nodes:
if wildcard_match(node.text, hostname):
return True
return False
@log('Certificate is valid and issued by trusted CA')
def is_valid(self):
'''
Sort-of a catch-all test for many of the other tests here
'''
node = self.tree.find('.//pathValidation')
return node is not None and node.attrib['validationResult'] == 'ok'
@log('Self-signed certificate')
def is_self_signed(self):
node = self.tree.find('.//pathValidation')
return node is not None and node.attrib['validationResult'] == 'self signed certificate'
@log('Is insecure signature')
def is_insecure_signature(self):
node = self.tree.find('.//signatureAlgorithm')
return node is not None and node.text.lower() in ['md2', 'md5']
# Process
def process_report(path, hostname=None):
with open(path, 'rb') as f:
data = f.read()
tree = ET.fromstring(data)
error = tree.find('.//invalidTarget')
if error is not None:
return (error.text, None, error.attrib['error'])
host = tree.find('.//target').attrib['host']
cert = CertificateScorer(tree)
if hostname is not None and not cert.hostname_valid(hostname):
return (host, 0, 'Hostname does not match certificate')
if not cert.is_valid():
return (host, 0, 'Certificate is not trusted')
if cert.is_insecure_signature():
return (host, 0, 'Signature is insecure')
protocol = ProtocolScorer(tree)
p_score = protocol.score()
kx = KeyExchangeScorer(tree)
kx_score = kx.score()
cipher = CipherScorer(tree)
c_score = cipher.score()
return (
host,
0.3 * p_score +
0.3 * kx_score +
0.4 * c_score,
'Protocol: %s, key exchange: %s, cipher: %s' % (p_score, kx_score, c_score)
)
def grade(score):
if score >= 80:
return "A"
if score >= 65:
return "B"
if score >= 50:
return "C"
if score >= 35:
return "D"
if score >= 20:
return "E"
return "F"
def main(path, hostname=None):
host, score, description = process_report(path, hostname)
print('%s\t%s\t%s\tGrade: %s' % (host, score, description, grade(score)))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('path')
parser.add_argument('hostname', nargs='?')
args = parser.parse_args()
sys.exit(main(**vars(args)))