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

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

fixed handshake algorithm for when openssl wants you to poll poll poll...

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