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

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

.

File size: 9.8 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        try:
101            serverSock = socket.socket()
102            serverSock.connect((host,port))
103            if timeout:
104                serverSock.settimeout(timeout)
105        except Exception as e:
106            if verbose:
107                sys.stderr.write("Unable to connect to %s:%s\n" % (host,port))
108            return None
109           
110        try:
111            if handshake_callback:
112                if not handshake_callback(serverSock):
113                    return None
114        except Exception as e:
115            traceback.print_exc(file=sys.stderr)
116            return None
117           
118        try:
119            conn = startSSLTLS(serverSock, mode='client', protocol=p, cipher_list=cl, timeout=timeout)
120            break
121        except ValueError as e:
122            if verbose:
123                sys.stderr.write("%s protocol not supported by your openssl library, trying others...\n" % pname)
124        except SSL.Error as e:
125            if verbose:
126                sys.stderr.write("Exception during %s handshake with server." % pname)
127                sys.stderr.write("\nThis could happen because the server requires "
128                                 "certain SSL/TLS versions or a client certificiate."
129                                 "  Have no fear, we'll keep trying...\n")
130        except Exception as e:
131            sys.stderr.write("Unknown exception during %s handshake with server: \n" % pname)
132            traceback.print_exc(file=sys.stderr)
133
134    return conn
135
136
137def fetchCertificateChain(connection):
138    chain = connection.get_peer_cert_chain()
139    if chain:
140        return chain
141    return None
142
143
144def normalizeCertificateName(cert_name):
145    n = cert_name.get_components()
146    n.sort()
147    return tuple(n)
148
149
150def normalizeCertificateChain(chain):
151    # Organize certificates by subject and issuer for quick lookups
152    subject_table = {}
153    issuer_table = {}
154    for c in chain:
155        subject_table[normalizeCertificateName(c.get_subject())] = c
156        issuer_table[normalizeCertificateName(c.get_issuer())] = c
157
158    # Now find root or highest-level intermediary
159    root = None
160    for c in chain:
161        i = normalizeCertificateName(c.get_issuer())
162        s = normalizeCertificateName(c.get_subject())
163        if (i == s) or (i not in subject_table):
164            if root != None:
165                sys.stderr.write("WARN: Multiple root certificates found or broken certificate chain detected.")
166            else:
167                # Go with the first identified "root", since that's more likely to link up with the server cert
168                root = c
169
170    # Finally, build the chain from the top-down in the correct order
171    new_chain = []
172    nxt = root
173    while nxt != None:
174        new_chain = [nxt] + new_chain
175        s = normalizeCertificateName(nxt.get_subject())
176        nxt = issuer_table.get(s)
177   
178    return new_chain
179   
180
181def genFakeKey(certificate):
182    fake_key = OpenSSL.crypto.PKey()
183    old_pubkey = certificate.get_pubkey()
184    fake_key.generate_key(old_pubkey.type(), old_pubkey.bits())
185
186    return fake_key
187
188
189def getDigestAlgorithm(certificate):
190    # XXX: ugly hack because openssl API for this is limited
191    algo = certificate.get_signature_algorithm()
192    if b'With' in algo:
193        return algo.split(b'With', 1)[0].decode('utf-8')
194    return None
195
196
197def deleteExtension(certificate, index):
198    '''
199    A dirty hack until this is implemented in pyOpenSSL. See:
200    https://github.com/pyca/pyopenssl/issues/152
201    '''
202    ffi = cffi.FFI()
203    ffi.cdef('''void* X509_delete_ext(void* x, int loc);''')
204
205    # Try to load libssl using several recent names because package
206    # maintainers have the blinders on and don't have a universal
207    # symlink to the most recent version.
208    libssl = None
209    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'):
210        try:
211            libssl = ffi.dlopen(libname)
212            break
213        except OSError as e:
214            pass
215   
216    ext = libssl.X509_delete_ext(certificate._x509, index)
217    #XXX: memory leak.  supposed to free ext here
218
219
220def removePeskyExtensions(certificate):
221    #for index in range(0,certificate.get_extension_count()):
222    #    e = certificate.get_extension(index)
223    #    print("extension %d: %s\n" % (index, e.get_short_name()), e)
224
225    index = 0
226    while index < certificate.get_extension_count():
227        e = certificate.get_extension(index)
228        if e.get_short_name() in (b'subjectKeyIdentifier', b'authorityKeyIdentifier'):
229            deleteExtension(certificate, index)
230            #XXX: would be nice if each of these extensions were re-added with appropriate values
231            index -= 1
232        index += 1
233   
234    #for index in range(0,certificate.get_extension_count()):
235    #    e = certificate.get_extension(index)
236    #    print("extension %d: %s\n" % (index, e.get_short_name()), e)
237
238
239def randomizeSerialNumber(certificate):
240    certificate.set_serial_number(random.randint(0,2**64))
241   
242def genFakeCertificateChain(cert_chain):
243    ret_val = []
244    cert_chain.reverse() # start with highest level authority
245
246    c = cert_chain[0]
247    i = normalizeCertificateName(c.get_issuer())
248    s = normalizeCertificateName(c.get_subject())
249    if s != i:
250        # XXX: consider retrieving root locally and including a forged version instead
251        c.set_issuer(c.get_subject())
252    k = genFakeKey(c)
253    c.set_pubkey(k)
254    removePeskyExtensions(c)
255    randomizeSerialNumber(c)
256    c.sign(k, getDigestAlgorithm(c))
257    ret_val.append(c)
258
259    prev = k
260    for c in cert_chain[1:]:
261        k = genFakeKey(c)
262        c.set_pubkey(k)
263        removePeskyExtensions(c)
264        randomizeSerialNumber(c)
265        c.sign(prev, getDigestAlgorithm(c))
266        prev = k
267        ret_val.append(c)
268
269    ret_val.reverse()
270    return k,ret_val
Note: See TracBrowser for help on using the repository browser.