This repository has been archived by the owner on Jul 27, 2021. It is now read-only.
/
sslscan.py
executable file
·403 lines (315 loc) · 11.1 KB
/
sslscan.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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
#!/usr/bin/env python
"""
Usage:
sslscan [-v] [--threads=<n>] <host>
sslscan info <type>
sslscan (-h | --help)
sslscan --version
Options:
-h --help Show this help screen
--version Show the version
-v Be more verbose
--threads=<n> Use the given number of threads (default: 5)
Info Types:
ciphers Ciphers supported by this version of OpenSSL
"""
from __future__ import print_function
__author__ = 'Andrew Dunham <andrew@du.nham.ca>'
__version__ = '0.0.1'
import sys
import socket
import threading
from concurrent import futures
from contextlib import contextmanager
from collections import namedtuple
from OpenSSL import SSL
try:
from http_parser.parser import HttpParser
except ImportError:
from http_parser.pyparser import HttpParser
from cryptography.hazmat.bindings.openssl.binding import Binding as OpenSSLBinding
from docopt import docopt
binding = OpenSSLBinding()
binding_ffi = binding.ffi
binding_lib = binding.lib
SSL_METHODS = ['SSLv2', 'SSLv3', 'TLSv1', 'TLSv1_1', 'TLSv1_2']
INSECURE_CIPHERS = [
]
Cipher = namedtuple('Cipher', ['method', 'name', 'bits'])
def cipher_as_str(c):
if c.bits == 'Anon':
return "%s (Anonymous cipher)" % (c.name,)
else:
return "%s (%s bits)" % (c.name, c.bits)
class HostInfo(object):
CIPHER_ACCEPTED = 0
CIPHER_REJECTED = 1
CIPHER_ERRORED = 2
def __init__(self, server, port):
# Host information
self.server = server
self.port = port
# Lock for complex operations
self.lock = threading.Lock()
# Format: (cipher, result)
self.ciphers = []
self.preferred_ciphers = {}
self.cert_chain = None
@property
def address(self):
return (self.server, self.port)
@contextmanager
def lock(self):
"""
Lock the structure for use with multiple threads.
"""
self.lock.acquire()
yield
self.lock.release()
def report_cipher(self, method, cipher, bits, result):
# For anonymous ciphers, we don't care about the key size
if 'ADH' in cipher or 'AECDH' in cipher:
bits = 'Anon'
elif bits == -1:
bits = 'Unknown'
else:
bits = str(bits)
self.ciphers.append((Cipher(method, cipher, bits), result))
def report_preferred(self, method, cipher, bits):
# For anonymous ciphers, we don't care about the key size
if 'ADH' in cipher or 'AECDH' in cipher:
bits = 'Anon'
elif bits == -1:
bits = 'Unknown'
else:
bits = str(bits)
self.preferred_ciphers[method] = Cipher(method, cipher, bits)
@property
def accepted_ciphers(self):
return (x[0] for x in self.ciphers if x[1] == self.CIPHER_ACCEPTED)
@property
def rejected_ciphers(self):
return (x[0] for x in self.ciphers if x[1] == self.CIPHER_REJECTED)
@property
def errored_ciphers(self):
return (x[0] for x in self.ciphers if x[1] == self.CIPHER_ERRORED)
def accepted_ciphers_for(self, method):
return (x for x in self.accepted_ciphers if x.method == method)
def rejected_ciphers_for(self, method):
return (x for x in self.rejected_ciphers if x.method == method)
def errored_ciphers_for(self, method):
return (x for x in self.errored_ciphers if x.method == method)
def get_all_ciphers(method):
"""
Get all ciphers supported by this version of OpenSSL.
"""
ssl_method = getattr(SSL, method.replace('.', '_') + '_METHOD')
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
context = SSL.Context(ssl_method)
context.set_cipher_list("ALL:COMPLEMENTOFALL")
sock = SSL.Connection(context, sock)
ciphers = sock.get_cipher_list()
except SSL.Error:
ciphers = []
finally:
sock.close()
return ciphers
def make_request(sock, server_name):
"""
Given an open socket, makes a simple HTTP request, parses the response, and
returns a dictionary containing the HTTP headers that were returned by the
server.
"""
p = HttpParser()
request = ('GET / HTTP/1.0\r\n' +
'User-Agent: pySSLScan\r\n' +
'Host: %s\r\n\r\n' % (server_name,))
sock.write(request.encode('ascii'))
headers = None
while True:
data = sock.recv(1024)
if not data:
break
recved = len(data)
nparsed = p.execute(data, recved)
assert nparsed == recved
if p.is_headers_complete():
headers = p.get_headers()
break
return headers
def get_cipher_bits(sock):
"""
Given a socket, gets the number of bits that the current cipher is using.
*Very* heavily dependent on the implementation of pyOpenSSL right now. :-(
"""
cipher = binding_lib.SSL_get_current_cipher(sock._ssl)
if cipher == binding_ffi.NULL:
return None
return binding_lib.SSL_CIPHER_get_bits(cipher, binding_ffi.NULL)
def test_single_cipher(host, method, cipher):
"""
Test to see if the server supports a given method/cipher combination.
"""
ssl_method = getattr(SSL, method.replace('.', '_') + '_METHOD')
context = SSL.Context(ssl_method)
context.set_cipher_list(cipher)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock = SSL.Connection(context, sock)
sock.connect(host.address)
headers = make_request(sock, host.server)
bits = get_cipher_bits(sock)
host.report_cipher(method, cipher, bits, HostInfo.CIPHER_ACCEPTED)
except SSL.Error as e:
host.report_cipher(method, cipher, -1, HostInfo.CIPHER_FAILED)
finally:
sock.close()
def test_preferred_cipher(host, method):
"""
Test what the server's preferred cipher is when a client will accept all
ciphers.
"""
ssl_method = getattr(SSL, method.replace('.', '_') + '_METHOD')
context = SSL.Context(ssl_method)
context.set_cipher_list("ALL:COMPLEMENTOFALL")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock = SSL.Connection(context, sock)
sock.connect(host.address)
headers = make_request(sock, host.server)
preferred = sock.cipher()
host.report_preferred(method, preferred[0], preferred[2])
except SSL.Error as e:
pass
finally:
sock.close()
def validate_cert_chain(host):
"""
Validate the server's certificate chain.
"""
context = SSL.Context(SSL.SSLv23_METHOD)
context.set_cipher_list("ALL:COMPLEMENTOFALL")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock = SSL.Connection(context, sock)
sock.connect(host.address)
headers = make_request(sock, host.server)
chain = sock.get_peer_cert_chain()
host.cert_chain = chain
except SSL.Error as e:
pass
finally:
sock.close()
def info(arguments):
ty = arguments['<type>']
if ty == 'ciphers':
for method in SSL_METHODS:
try:
supported_ciphers = get_all_ciphers(method)
except ValueError:
print("Method not supported: %s" % (method,))
continue
print("Method: %s" % (method,))
print("-" * 50)
for cipher in sorted(supported_ciphers):
print(cipher)
print('')
else:
print("Unknown info type: %s" % (ty,))
def main():
arguments = docopt(__doc__, version=__version__)
if arguments['info']:
return info(arguments)
# Get the address from the user.
server = arguments['<host>']
port = 443
if ':' in server:
server, port = server.split(':', 1)
port = int(port)
threads = arguments['--threads']
if threads is None:
threads = 5
else:
threads = int(threads)
ssl_version = SSL.SSLeay_version(SSL.SSLEAY_VERSION)
if not isinstance(ssl_version, str):
ssl_version = ssl_version.decode('ascii')
print_box = lambda s, **kw: print('| ' + s.ljust(59) + '|', **kw)
print("+" + "-" * 60 + "+")
print_box("pySSLScan version %s" % (__version__,))
print_box(" OpenSSL version: %s" % (ssl_version,))
print_box(" Threads: : %d" % (threads,))
print_box(" Verbose: : %s" % (bool(arguments['-v']),))
print("+" + "-" * 60 + "+")
print('')
# Create host structure.
host = HostInfo(server, port)
# Note that this statement will wait for all executed things to finish.
print("Scanning, please wait... ", end='')
sys.stdout.flush()
with futures.ThreadPoolExecutor(max_workers=threads) as executor:
# Validate certificate chain for the server.
executor.submit(validate_cert_chain, host)
for method in SSL_METHODS:
try:
supported_ciphers = get_all_ciphers(method)
except ValueError:
print("Method not supported: %s" % (method,))
continue
# Test each individual cipher.
for cipher in supported_ciphers:
executor.submit(test_single_cipher, host, method, cipher)
# Test for the preferred cipher suite for this method.
executor.submit(test_preferred_cipher, host, method)
print('done!\n')
# Print results.
for method in SSL_METHODS:
print("Ciphers for %s:" % (method,))
print("-" * 20)
for cipher in sorted(host.accepted_ciphers_for(method)):
print(' ' + cipher_as_str(cipher))
if arguments['-v']:
for cipher in sorted(host.rejected_ciphers_for(method)):
print(' (rejected) ' + cipher_as_str(cipher))
for cipher in sorted(host.errored_ciphers_for(method)):
print(' (errored) ' + cipher_as_str(cipher))
print('')
print('Preferred Ciphers:')
print('-' * 20)
for method in SSL_METHODS:
preferred = host.preferred_ciphers.get(method)
if preferred is not None:
print(" %s: %s" % (method, cipher_as_str(preferred)))
else:
print(" %s: None" % (method,))
print('')
# Lastly, print any problems found
print('Problems:')
print('-' * 20)
if len(list(host.accepted_ciphers_for('SSLv2'))) > 0:
print("- Host supports SSLv2")
anon_ciphers = []
weak_ciphers = []
for method in SSL_METHODS:
for cipher in sorted(host.accepted_ciphers_for(method)):
if cipher.bits == 'Anon':
anon_ciphers.append(cipher)
elif cipher.bits == 'Unknown':
# TODO: report?
pass
elif int(cipher.bits) < 128:
weak_ciphers.append(cipher)
if len(anon_ciphers) > 0:
print('- Host supports anonymous cipher suites')
for x in anon_ciphers:
print(' - %s' % (x,))
if len(weak_ciphers) > 0:
print('- Host supports weak cipher suites')
for x in weak_ciphers:
print(' - %s' % (x,))
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
pass