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

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

.

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