source: trunk/lib/bletchley/ssltls.py @ 126

Last change on this file since 126 was 126, checked in by tim, 7 years ago

.

File size: 9.6 KB
Line 
1'''
2Utilities for manipulating certificates and SSL/TLS connections.
3
4Copyright (C) 2014,2016 Blindspot Security LLC
5Author: Timothy D. Morgan
6
7 This program is free software: you can redistribute it and/or modify
8 it under the terms of the GNU Lesser General Public License, version 3,
9 as published by the Free Software Foundation.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program.  If not, see <http://www.gnu.org/licenses/>.
18'''
19
20import sys
21import argparse
22import traceback
23import random
24import socket
25try:
26    import OpenSSL
27    from OpenSSL import SSL
28except:
29    sys.stderr.write('ERROR: Could not locate pyOpenSSL module.  Under Debian-based systems, try:\n')
30    sys.stderr.write('       # apt-get install python3-openssl\n')
31    sys.stderr.write('NOTE: pyOpenSSL version 0.14 or later is required!\n')
32    sys.exit(2)
33try:
34    import cffi
35except:
36    sys.stderr.write('ERROR: Could not locate cffi module.  Under Debian-based systems, try:\n')
37    sys.stderr.write('       # apt-get install python3-cffi\n')
38    sys.stderr.write('NOTE: This is a requirement because pyOpenSSL does not provide '
39                     'certificate extension removal procedures.  Consider lobbying for the '
40                     'implementation of this:\n  https://github.com/pyca/pyopenssl/issues/152\n')
41    sys.exit(2)
42
43
44def createContext(method=SSL.TLSv1_METHOD, key=None, certChain=[]):
45    context = SSL.Context(method)
46    context.set_verify(SSL.VERIFY_NONE, (lambda a,b,c,d,e: True))
47
48    if key and len(certChain) > 0:
49        context.use_privatekey(key)
50        context.use_certificate(certChain[0])
51        for c in certChain[1:]:
52            context.add_extra_chain_cert(c)
53   
54    return context
55
56
57def startSSLTLS(sock, mode='client', protocol=SSL.TLSv1_METHOD, key=None, certChain=[], cipher_list=None, timeout=None):
58    '''
59    cipher_list names drawn from:
60      openssl ciphers -v "ALL:@SECLEVEL=0"
61    '''
62   
63    context = createContext(protocol, key=key, certChain=certChain)
64    if cipher_list:
65        context.set_cipher_list(cipher_list)
66    if timeout:
67        context.set_timeout(timeout)
68       
69    #if not key and mode == 'server':
70    #context.set_options(OpenSSL.SSL.OP_SINGLE_DH_USE)
71    #context.set_options(OpenSSL.SSL.OP_EPHEMERAL_RSA)
72   
73    conn = SSL.Connection(context, sock)
74    if mode == 'client':
75        conn.set_connect_state()
76        conn.do_handshake()
77    else:
78        conn.set_accept_state()
79   
80    return conn
81
82
83def ConnectSSLTLS(host, port, cipher_list=None, timeout=None, handshake_callback=None, verbose=True):
84    backup_cipher_list = b'DES-CBC3-SHA:RC4-MD5:RC4-SHA:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES128-SHA:ADH-AES256-GCM-SHA384'
85    protocols = [("SSL 2/3", SSL.SSLv23_METHOD, None),
86                 ("SSL 2/3", SSL.SSLv23_METHOD, backup_cipher_list),
87                 ("TLS 1.0", SSL.TLSv1_METHOD, None),
88                 ("TLS 1.0", SSL.TLSv1_METHOD, backup_cipher_list), 
89                 ("TLS 1.1", SSL.TLSv1_1_METHOD, None),
90                 ("TLS 1.1", SSL.TLSv1_1_METHOD, backup_cipher_list),
91                 ("TLS 1.2", SSL.TLSv1_2_METHOD, None),
92                 ("TLS 1.2", SSL.TLSv1_2_METHOD, backup_cipher_list),
93                 ("SSL 3.0", SSL.SSLv3_METHOD, None),
94                 ("SSL 3.0", SSL.SSLv3_METHOD, backup_cipher_list),
95                 ("SSL 2.0", SSL.SSLv2_METHOD, None),
96                 ("SSL 2.0", SSL.SSLv2_METHOD, backup_cipher_list)]
97
98    conn = None
99    for pname,p,cl in protocols:
100        serverSock = socket.socket()
101        serverSock.connect((host,port))
102        if timeout:
103            serverSock.settimeout(timeout)
104
105        try:
106            if handshake_callback:
107                if not handshake_callback(serverSock):
108                    return None
109        except Exception as e:
110            traceback.print_exc(file=sys.stderr)
111            return None
112           
113        try:
114            conn = startSSLTLS(serverSock, mode='client', protocol=p, cipher_list=cl, timeout=timeout)
115            break
116        except ValueError as e:
117            if verbose:
118                sys.stderr.write("%s protocol not supported by your openssl library, trying others...\n" % pname)
119        except SSL.Error as e:
120            if verbose:
121                sys.stderr.write("Exception during %s handshake with server." % pname)
122                sys.stderr.write("\nThis could happen because the server requires "
123                                 "certain SSL/TLS versions or a client certificiate."
124                                 "  Have no fear, we'll keep trying...\n")
125        except Exception as e:
126            sys.stderr.write("Unknown exception during %s handshake with server: \n" % pname)
127            traceback.print_exc(file=sys.stderr)
128
129    return conn
130
131
132def fetchCertificateChain(connection):
133    chain = connection.get_peer_cert_chain()
134    if chain:
135        return chain
136    return None
137
138
139def normalizeCertificateName(cert_name):
140    n = cert_name.get_components()
141    n.sort()
142    return tuple(n)
143
144
145def normalizeCertificateChain(chain):
146    # Organize certificates by subject and issuer for quick lookups
147    subject_table = {}
148    issuer_table = {}
149    for c in chain:
150        subject_table[normalizeCertificateName(c.get_subject())] = c
151        issuer_table[normalizeCertificateName(c.get_issuer())] = c
152
153    # Now find root or highest-level intermediary
154    root = None
155    for c in chain:
156        i = normalizeCertificateName(c.get_issuer())
157        s = normalizeCertificateName(c.get_subject())
158        if (i == s) or (i not in subject_table):
159            if root != None:
160                sys.stderr.write("WARN: Multiple root certificates found or broken certificate chain detected.")
161            else:
162                # Go with the first identified "root", since that's more likely to link up with the server cert
163                root = c
164
165    # Finally, build the chain from the top-down in the correct order
166    new_chain = []
167    nxt = root
168    while nxt != None:
169        new_chain = [nxt] + new_chain
170        s = normalizeCertificateName(nxt.get_subject())
171        nxt = issuer_table.get(s)
172   
173    return new_chain
174   
175
176def genFakeKey(certificate):
177    fake_key = OpenSSL.crypto.PKey()
178    old_pubkey = certificate.get_pubkey()
179    fake_key.generate_key(old_pubkey.type(), old_pubkey.bits())
180
181    return fake_key
182
183
184def getDigestAlgorithm(certificate):
185    # XXX: ugly hack because openssl API for this is limited
186    algo = certificate.get_signature_algorithm()
187    if b'With' in algo:
188        return algo.split(b'With', 1)[0].decode('utf-8')
189    return None
190
191
192def deleteExtension(certificate, index):
193    '''
194    A dirty hack until this is implemented in pyOpenSSL. See:
195    https://github.com/pyca/pyopenssl/issues/152
196    '''
197    ffi = cffi.FFI()
198    ffi.cdef('''void* X509_delete_ext(void* x, int loc);''')
199
200    # Try to load libssl using several recent names because package
201    # maintainers have the blinders on and don't have a universal
202    # symlink to the most recent version.
203    libssl = None
204    for libname in ('libssl.so','libssl.so.1.0.2', 'libssl.so.1.0.1', 'libssl.so.1.0.0','libssl.so.0.9.8'):
205        try:
206            libssl = ffi.dlopen(libname)
207            break
208        except OSError as e:
209            pass
210   
211    ext = libssl.X509_delete_ext(certificate._x509, index)
212    #XXX: memory leak.  supposed to free ext here
213
214
215def removePeskyExtensions(certificate):
216    #for index in range(0,certificate.get_extension_count()):
217    #    e = certificate.get_extension(index)
218    #    print("extension %d: %s\n" % (index, e.get_short_name()), e)
219
220    index = 0
221    while index < certificate.get_extension_count():
222        e = certificate.get_extension(index)
223        if e.get_short_name() in (b'subjectKeyIdentifier', b'authorityKeyIdentifier'):
224            deleteExtension(certificate, index)
225            #XXX: would be nice if each of these extensions were re-added with appropriate values
226            index -= 1
227        index += 1
228   
229    #for index in range(0,certificate.get_extension_count()):
230    #    e = certificate.get_extension(index)
231    #    print("extension %d: %s\n" % (index, e.get_short_name()), e)
232
233
234def randomizeSerialNumber(certificate):
235    certificate.set_serial_number(random.randint(0,2**64))
236   
237def genFakeCertificateChain(cert_chain):
238    ret_val = []
239    cert_chain.reverse() # start with highest level authority
240
241    c = cert_chain[0]
242    i = normalizeCertificateName(c.get_issuer())
243    s = normalizeCertificateName(c.get_subject())
244    if s != i:
245        # XXX: consider retrieving root locally and including a forged version instead
246        c.set_issuer(c.get_subject())
247    k = genFakeKey(c)
248    c.set_pubkey(k)
249    removePeskyExtensions(c)
250    randomizeSerialNumber(c)
251    c.sign(k, getDigestAlgorithm(c))
252    ret_val.append(c)
253
254    prev = k
255    for c in cert_chain[1:]:
256        k = genFakeKey(c)
257        c.set_pubkey(k)
258        removePeskyExtensions(c)
259        randomizeSerialNumber(c)
260        c.sign(prev, getDigestAlgorithm(c))
261        prev = k
262        ret_val.append(c)
263
264    ret_val.reverse()
265    return k,ret_val
Note: See TracBrowser for help on using the repository browser.