def keypair(): request_data = json.loads(request.data.decode()) potential_pkey_size = request_data['pkey_size'] if not potential_pkey_size.isdigit() or len(potential_pkey_size) > 4: return INVALID_PRIVATE_KEY_SIZE_ERROR_MSG, 400 pkey_size = int(request_data['pkey_size']) encryption_method = str(request_data['encryption_method']) pkey_file_name = str(request_data['pkey_file']) passphrase = str(request_data['passphrase']) if path.isfile(PRIVATE_KEY_DIR + pkey_file_name): return 'Private key file ' + pkey_file_name + ' already exists.', 409 elif pkey_size < MINIMUM_PRIVATE_KEY_SIZE_IN_BITS or MAXIMUM_PRIVATE_KEY_SIZE_IN_BITS < pkey_size: return INVALID_PRIVATE_KEY_SIZE_ERROR_MSG, 400 else: private_key = crypto.PKey() private_key.generate_key(crypto.TYPE_RSA, pkey_size) with open(PRIVATE_KEY_DIR + pkey_file_name, "w") as private_key_file: if (encryption_method): print private_key_file.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, private_key, encryption_method, passphrase)) else: print private_key_file.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, private_key)) return 'Keypair successfully created.', 201
def generate(self, module): """Generate a keypair.""" if not self.check(module, perms_required=False) or self.force: self.privatekey = crypto.PKey() try: self.privatekey.generate_key(self.type, self.size) except (TypeError, ValueError) as exc: raise PrivateKeyError(exc) try: privatekey_file = os.open(self.path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, self.mode) if self.cipher and self.passphrase: os.write(privatekey_file, crypto.dump_privatekey(crypto.FILETYPE_PEM, self.privatekey, self.cipher, to_bytes(self.passphrase))) else: os.write(privatekey_file, crypto.dump_privatekey(crypto.FILETYPE_PEM, self.privatekey)) os.close(privatekey_file) self.changed = True except IOError as exc: self.remove() raise PrivateKeyError(exc) self.fingerprint = crypto_utils.get_fingerprint(self.path, self.passphrase) file_args = module.load_file_common_arguments(module.params) if module.set_fs_attributes_if_different(file_args, False): self.changed = True
def separar_arquivo(self, senha, caminho=False): """Separa o arquivo de certificado em dois: de chave e de certificado, e retorna a string. Se caminho for True grava na pasta temporaria e retorna o caminho dos arquivos, apos o uso devem ser excluidos com o metodo excluir.""" # Carrega o arquivo .pfx, erro pode ocorrer se a senha estiver errada ou formato invalido. pkcs12 = crypto.load_pkcs12(open(self.caminho_arquivo, "rb").read(), senha) if caminho: cert = crypto.dump_certificate(crypto.FILETYPE_PEM, pkcs12.get_certificate()) chave = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkcs12.get_privatekey()) # cria arquivos temporarios with tempfile.NamedTemporaryFile(delete=False) as arqcert: arqcert.write(cert) with tempfile.NamedTemporaryFile(delete=False) as arqchave: arqchave.write(chave) self.arquivos_temp.append(arqchave.name) self.arquivos_temp.append(arqcert.name) return arqchave.name, arqcert.name else: # Certificado cert = crypto.dump_certificate(crypto.FILETYPE_PEM, pkcs12.get_certificate()).decode('utf-8') cert = cert.replace('\n', '') cert = cert.replace('-----BEGIN CERTIFICATE-----', '') cert = cert.replace('-----END CERTIFICATE-----', '') # Chave, string decodificada da chave privada chave = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkcs12.get_privatekey()) return chave, cert
def create_certificates(configdir): """ Create certificates and private keys for WebCleaner. """ cakey = create_key_pair(TYPE_RSA, 1024) careq = create_cert_request(cakey, CN='Certificate Authority') # five years cacert = create_certificate(careq, (careq, cakey), 0, (0, 60*60*24*365*5)) # write files with appropriate umask oldmask = os.umask(0022) f = file(os.path.join(configdir, 'CA.pkey'), 'w') f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, cakey)) f.close() f = file(os.path.join(configdir, 'CA.cert'), 'w') f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cacert)) f.close() for (fname, cname) in [('client', '%s Client' % AppName), ('server', '%s Server' % AppName)]: pkey = create_key_pair(TYPE_RSA, 1024) req = create_cert_request(pkey, CN=cname) # five years cert = create_certificate(req, (cacert, cakey), 1, (0, 60*60*24*365*5)) f = file(os.path.join(configdir, '%s.pkey' % fname), 'w') f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)) f.close() f = file(os.path.join(configdir, '%s.cert' % fname), 'w') f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) f.close() # reset umask os.umask(oldmask)
def storePKIUserCertificate(self, user, hostname, certificate, obj, password=None): """Store a given PKI object into a file @param user [User] the user to which the certificate is associated @param hostname [Hostname] the hostname to which the certificate is associated @param certificate [Certificate] the Certificate instance associated with the file @param obj [X509/PKey] The object that will be dump to the file @param password [str] OPTIONNAL : an optionnal passphrase to use for encrypt the output (if available) """ path = (self.__new_cert_directory + str(user.id) + "/" + str(hostname.id) + "/") self.makePath(path) bytes_ = None if isinstance(obj, OpenSSL.crypto.X509): bytes_ = crypto.dump_certificate(crypto.FILETYPE_PEM, obj) path += str(certificate.id) + ".crt" if isinstance(obj, OpenSSL.crypto.X509Req): bytes_ = crypto.dump_certificate_request(crypto.FILETYPE_PEM, obj) path += str(certificate.id) + ".csr" elif isinstance(obj, OpenSSL.crypto.PKey): if isinstance(password, str): bytes_ = crypto.dump_privatekey(crypto.FILETYPE_PEM, obj, self.__cipher, password.encode()) else: bytes_ = crypto.dump_privatekey(crypto.FILETYPE_PEM, obj) path += str(certificate.id) + ".key" assert bytes_ is not None self.storeBytesToFile(bytes_, path)
def create_selfsigned(): #创建一个密钥对 k=crypto.PKey() k.generate_key(crypto.TYPE_RSA,1024) #证书 cert=crypto.X509() #cert.get_subject().C="China" cert.get_subject().ST="Hunan" cert.get_subject().L="Changsha" cert.get_subject().O="HNU" cert.get_subject().OU="HNU" cert.get_subject().CN="201208010127" cert.set_serial_number(8888) 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') #输出证书、密钥、公钥 open(CERT_FILE, "wb").write( crypto.dump_certificate(crypto.FILETYPE_PEM,cert)) open(PRIVATE_KEY_FILE, "wb").write( crypto.dump_privatekey(crypto.FILETYPE_PEM, k)) open(PUBLIC_KEY_FILE,"wb").write( crypto.dump_privatekey(crypto.FILETYPE_PEM, cert.get_pubkey())) print("hash value is:") print(cert.subject_name_hash())
def p12_assertions(self, cdir, cert, key, p12, cacert=None): ''' test basic p12 certificate bundle assumptions Args: cdir (s_certdir.CertDir): certdir object cert (crypto.X509): Cert to test key (crypto.PKey): Key for the certification p12 (crypto.PKCS12): PKCS12 object to test cacert (crypto.X509): Corresponding CA cert (optional) ''' self.nn(p12) # Pull out the CA cert and keypair data p12_cacert = None if cacert: p12_cacert = p12.get_ca_certificates() self.nn(p12_cacert) self.len(1, p12_cacert) p12_cacert = p12_cacert[0] self.eq(crypto.dump_certificate(crypto.FILETYPE_ASN1, cacert), crypto.dump_certificate(crypto.FILETYPE_ASN1, p12_cacert)) p12_cert = p12.get_certificate() p12_key = p12.get_privatekey() self.basic_assertions(cdir, p12_cert, p12_key, cacert=p12_cacert) # Make sure that the CA cert and keypair files are the same as the CA cert and keypair contained in the p12 file self.eq(crypto.dump_certificate(crypto.FILETYPE_ASN1, cert), crypto.dump_certificate(crypto.FILETYPE_ASN1, p12_cert)) self.eq(crypto.dump_privatekey(crypto.FILETYPE_ASN1, key), crypto.dump_privatekey(crypto.FILETYPE_ASN1, p12_key))
def make_certificate( ca_crt_path = 'ca.crt', ca_key_path = 'ca.key', server_crt_path = 'server.crt', server_key_path = 'server.key', vars=None): # make the certificat of CA # need passphrase ? ca_key = PKey() ca_key.generate_key(TYPE_RSA, 1024) dump_write(dump_privatekey(FILETYPE_PEM, ca_key), ca_key_path) # MAKE THE CA SELF-SIGNED CERTIFICATE cert = X509() sub = cert.get_subject() set_x509_ca(sub, vars=vars) #FORMAT : YYYYMMDDhhmmssZ after = '20200101000000Z' before = '20090101000000Z' cert.set_notAfter(after) cert.set_notBefore(before) cert.set_serial_number(1) cert.set_pubkey(ca_key) cert.set_issuer(cert.get_subject()) cert.sign(ca_key,"MD5") dump_write(dump_certificate(FILETYPE_PEM, cert), ca_crt_path) print "Generated CA certificate in %s" % ca_crt_path # MAKE THE SERVER CERTIFICATE s_key = PKey() s_key.generate_key(TYPE_RSA, 1024) dump_write(dump_privatekey(FILETYPE_PEM, s_key), server_key_path) s_cert = X509() s_sub = s_cert.get_subject() set_x509_serv(s_sub, vars=vars) #FORMAT : YYYYMMDDhhmmssZ after = '20200101000000Z' before = '20090101000000Z' s_cert.set_notAfter(after) s_cert.set_notBefore(before) s_cert.set_serial_number(2) s_cert.set_pubkey(s_key) s_cert.set_issuer(cert.get_subject()) s_cert.sign(ca_key,"MD5") dump_write(dump_certificate(FILETYPE_PEM, s_cert), server_crt_path) print "Generated Server certificate in %s" % server_crt_path for p in [ca_key_path, server_key_path]: os.chmod(p, 0600)
def main(): args = parse_args() ca_pem = args.ca.read() ca_key = crypto.load_privatekey(PEM, ca_pem, args.ca_pass) ca_cert = crypto.load_certificate(PEM, ca_pem) cert = crypto.load_certificate(PEM, args.cert.read()) new_cert, new_pkey = dupe(ca_cert, ca_key, cert) print crypto.dump_certificate(PEM, new_cert) print crypto.dump_privatekey(PEM, new_pkey)
def saveKey(self, path, password=None): (_, ext) = os.path.splitext(path) type = crypto.FILETYPE_PEM if ext == ".der" or ext == ".crt" or ext == ".cer": type = crypto.FILETYPE_ASN1 if password: write(path, crypto.dump_privatekey(type, self.pkey, self.parent.cipher, b(password))) else: write(path, crypto.dump_privatekey(type, self.pkey)) return self
def create_key(keyfile='', passphrase=None): key = crypto.PKey() key.generate_key(KEY_ALGO, KEY_SIZE) if passphrase: open(keyfile, "wt").write(crypto.dump_privatekey(crypto.FILETYPE_PEM, key, KEY_CIPHER, passphrase)) else: open(keyfile, "wt").write(crypto.dump_privatekey(crypto.FILETYPE_PEM, key)) return key
def _ASN1KeysEqual(key1, key2): try: key1_ASN1 = SSLCrypto.dump_privatekey(SSLCrypto.FILETYPE_ASN1, key1) key2_ASN1 = SSLCrypto.dump_privatekey(SSLCrypto.FILETYPE_ASN1, key2) # no need for constant time comparison here because both keys tested # are sent to us by the relay. doing it anyway in case i accidentally # use this function somewhere else in the future return crypto.constantStrEqual(key1_ASN1, key2_ASN1) except Exception as e: msg = "Failed to parse ASN1 key: {}.".format(e) logging.debug(msg) return False
def generate_ssl_keypair(cert_dir, fqdn, is_valid=True): if not os.path.exists(cert_dir): os.makedirs(cert_dir) cert_path = os.path.join(cert_dir, fqdn + '.crt') key_path = os.path.join(cert_dir, fqdn + '.key') pem_path = os.path.join(cert_dir, fqdn + '-fd.pem') if os.path.exists(cert_path): os.unlink(cert_path) if os.path.exists(key_path): os.unlink(key_path) if os.path.exists(pem_path): os.unlink(pem_path) # create a key pair key = crypto.PKey() key.generate_key(crypto.TYPE_RSA, 4096) # create a self-signed cert cert = crypto.X509() cert.get_subject().C = 'US' cert.get_subject().ST = 'California' cert.get_subject().L = 'Santa Cruz' cert.get_subject().O = 'Your Company Name' cert.get_subject().OU = 'IT' cert.get_subject().emailAddress = '*****@*****.**' cert.get_subject().CN = fqdn # Add X509v3 Extension ext1 = crypto.X509Extension('subjectKeyIdentifier', False, 'hash', subject=cert ) cert.add_extensions([ext1]) cert.set_serial_number(1000) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(10 * 365 * 24 * 60 * 60) cert.set_issuer(cert.get_subject()) cert.set_pubkey(key) cert.sign(key, 'sha1') with open(cert_path, 'wt') as fd: fd.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) with open(key_path, 'wt') as fd: fd.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, key)) with open(pem_path, 'wt') as pemfile: pemfile.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) pemfile.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, key)) return pem_path
def _generate_private_key(cls, bit_length=2048, passphrase=None): pk = crypto.PKey() pk.generate_key(crypto.TYPE_RSA, bit_length) if passphrase: return crypto.dump_privatekey( crypto.FILETYPE_PEM, pk, 'aes-256-cbc', passphrase ) else: return crypto.dump_privatekey( crypto.FILETYPE_PEM, pk )
def gen_certs(host='localhost', dir='.', days=None, save_all=False): print('Creating CA...') CA_key = make_key() CA_request = make_csr(CA_key, 'Generic Pipa Certificate Authority') days = days or 365 period = 60*60*24 * days CA_cert = sign_request(CA_request, CA_request, CA_key, period) time.sleep(1) if save_all: print('Writing CA key...') with open(join(dir, 'CA.key'), 'wb') as keyfile: key = crypto.dump_privatekey(crypto.FILETYPE_PEM, CA_key) keyfile.write(key) print('Writing CA cert...') with open(join(dir, 'CA.crt'), 'wb') as certfile: cert = crypto.dump_certificate(crypto.FILETYPE_PEM, CA_cert) certfile.write(cert) print('Generating server for %s...' % host) server_key = make_key() server_req = make_csr(server_key, host) server_cert = sign_request(server_req, CA_cert, CA_key, period) print('Writing Server key...') with open(join(dir, 'server.key'), 'wb') as keyfile: key = crypto.dump_privatekey(crypto.FILETYPE_PEM, server_key) keyfile.write(key) if save_all: print('Writing Server cert...') with open(join(dir, 'server.crt'), 'wb') as certfile: cert = crypto.dump_certificate(crypto.FILETYPE_PEM, server_cert) certfile.write(cert) print('Writing cert bundle...') with open(join(dir, 'bundle.pem'), 'wb') as bundle: cert = crypto.dump_certificate(crypto.FILETYPE_PEM, server_cert) bundle.write(cert) cert = crypto.dump_certificate(crypto.FILETYPE_PEM, CA_cert) bundle.write(cert) print('Done!')
def installCertificates(session): if not os_exists(CERT_FILE) \ or not os_exists(KEY_FILE): print "[Webinterface].installCertificates :: Generating SSL key pair and CACert" # create a key pair k = crypto.PKey() k.generate_key(crypto.TYPE_RSA, 1024) # create a self-signed cert cert = crypto.X509() cert.get_subject().C = "DE" cert.get_subject().ST = "Home" cert.get_subject().L = "Home" cert.get_subject().O = "Dreambox" cert.get_subject().OU = "STB" cert.get_subject().CN = socket_gethostname() cert.set_serial_number(random.randint(1000000,1000000000)) cert.set_notBefore("20120101000000Z"); cert.set_notAfter("20301231235900Z") cert.set_issuer(cert.get_subject()) cert.set_pubkey(k) print "[Webinterface].installCertificates :: Signing SSL key pair with new CACert" cert.sign(k, 'sha1') try: print "[Webinterface].installCertificates :: Installing newly generated certificate and key pair" saveFile(CERT_FILE, crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) saveFile(KEY_FILE, crypto.dump_privatekey(crypto.FILETYPE_PEM, k)) except IOError, e: #Disable https config.plugins.Webinterface.https.enabled.value = False config.plugins.Webinterface.https.enabled.save() #Inform the user session.open(MessageBox, "Couldn't install generated SSL-Certifactes for https access\nHttps access is disabled!", MessageBox.TYPE_ERROR)
def create_https_certificates(ssl_cert, ssl_key): """ Create self-signed HTTPS certificares and store in paths 'ssl_cert' and 'ssl_key' """ try: from OpenSSL import crypto #@UnresolvedImport from lib.certgen import createKeyPair, createCertRequest, createCertificate, TYPE_RSA, serial #@UnresolvedImport except: logger.log(u"pyopenssl module missing, please install for https access", logger.WARNING) return False # Create the CA Certificate cakey = createKeyPair(TYPE_RSA, 1024) careq = createCertRequest(cakey, CN='Certificate Authority') cacert = createCertificate(careq, (careq, cakey), serial, (0, 60*60*24*365*10)) # ten years cname = 'SickBeard' pkey = createKeyPair(TYPE_RSA, 1024) req = createCertRequest(pkey, CN=cname) cert = createCertificate(req, (cacert, cakey), serial, (0, 60*60*24*365*10)) # ten years # Save the key and certificate to disk try: open(ssl_key, 'w').write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)) open(ssl_cert, 'w').write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) except: logger.log(u"Error creating SSL key and certificate", logger.ERROR) return False return True
def make_ssl_devcert(base_path, host=None, cn=None): """Creates an SSL key for development. This should be used instead of the ``'adhoc'`` key which generates a new cert on each server start. It accepts a path for where it should store the key and cert and either a host or CN. If a host is given it will use the CN ``*.host/CN=host``. For more information see :func:`run_simple`. .. versionadded:: 0.9 :param base_path: the path to the certificate and key. The extension ``.crt`` is added for the certificate, ``.key`` is added for the key. :param host: the name of the host. This can be used as an alternative for the `cn`. :param cn: the `CN` to use. """ from OpenSSL import crypto if host is not None: cn = '*.%s/CN=%s' % (host, host) cert, pkey = generate_adhoc_ssl_pair(cn=cn) cert_file = base_path + '.crt' pkey_file = base_path + '.key' with open(cert_file, 'wb') as f: f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) with open(pkey_file, 'wb') as f: f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)) return cert_file, pkey_file
def create_https_certificates(ssl_cert, ssl_key): """ Create self-signed HTTPS certificates and store in paths 'ssl_cert' and 'ssl_key' """ try: from OpenSSL import crypto from sabnzbd.utils.certgen import createKeyPair, createCertRequest, createCertificate, \ TYPE_RSA, serial except: logging.warning(T('pyopenssl module missing, please install for https access')) return False # Create the CA Certificate cakey = createKeyPair(TYPE_RSA, 2048) careq = createCertRequest(cakey, digest='sha256', CN='Certificate Authority') cacert = createCertificate(careq, (careq, cakey), serial, (0, 60 * 60 * 24 * 365 * 10), digest='sha256') # ten years cname = 'SABnzbd' pkey = createKeyPair(TYPE_RSA, 2048) req = createCertRequest(pkey, digest='sha256', CN=cname) cert = createCertificate(req, (cacert, cakey), serial, (0, 60 * 60 * 24 * 365 * 10), digest='sha256') # ten years # Save the key and certificate to disk try: open(ssl_key, 'w').write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)) open(ssl_cert, 'w').write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) except: logging.error(T('Error creating SSL key and certificate')) logging.info("Traceback: ", exc_info=True) return False return True
def create_https_certificates(ssl_cert, ssl_key): """ Create a self-signed HTTPS certificate and store in it in 'ssl_cert' and 'ssl_key'. Method assumes pyOpenSSL is installed. This code is stolen from SickBeard (http://github.com/midgetspy/Sick-Beard). """ from OpenSSL import crypto from certgen import createKeyPair, createSelfSignedCertificate, TYPE_RSA serial = int(time.time()) domains = ['DNS:' + d.strip() for d in plexpy.CONFIG.HTTPS_DOMAIN.split(',') if d] ips = ['IP:' + d.strip() for d in plexpy.CONFIG.HTTPS_IP.split(',') if d] altNames = ','.join(domains + ips) # Create the self-signed PlexPy certificate logger.debug(u"Generating self-signed SSL certificate.") pkey = createKeyPair(TYPE_RSA, 2048) cert = createSelfSignedCertificate(("PlexPy", pkey), serial, (0, 60 * 60 * 24 * 365 * 10), altNames) # ten years # Save the key and certificate to disk try: with open(ssl_cert, "w") as fp: fp.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) with open(ssl_key, "w") as fp: fp.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)) except IOError as e: logger.error("Error creating SSL key and certificate: %s", e) return False return True
def create_https_certificates(ssl_cert, ssl_key): """ Create self-signed HTTPS certificares and store in paths 'ssl_cert' and 'ssl_key' """ try: from OpenSSL import crypto from certgen import createKeyPair, createCertRequest, createCertificate, TYPE_RSA, serial except ImportError: log.error("pyopenssl module missing, please install for https access\n try\n $ easy_install PyOpenSSL") return False # Create the CA Certificate cakey = createKeyPair(TYPE_RSA, 1024) careq = createCertRequest(cakey, CN='Certificate Authority') cacert = createCertificate(careq, (careq, cakey), serial, (0, 60 * 60 * 24 * 365 * 10)) # ten years cname = 'XDM' pkey = createKeyPair(TYPE_RSA, 1024) req = createCertRequest(pkey, CN=cname) cert = createCertificate(req, (cacert, cakey), serial, (0, 60 * 60 * 24 * 365 * 10)) # ten years # Save the key and certificate to disk try: open(ssl_key, 'w').write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)) open(ssl_cert, 'w').write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) except: log("Error creating SSL key and certificate") return False return True
def make_ssl_certificate(key_path, cert_path): """ Generate a self-signed certificate The generated key will be written out to key_path, with the corresponding certificate itself being written to cert_path. """ cert = crypto.X509() cert.set_serial_number(int(random() * sys.maxsize)) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(60 * 60 * 24 * 365) subject = cert.get_subject() subject.CN = '*' subject.O = 'Self-Signed Certificate for Err' issuer = cert.get_issuer() issuer.CN = 'Self-proclaimed Authority' issuer.O = 'Self-Signed' pkey = crypto.PKey() pkey.generate_key(crypto.TYPE_RSA, 4096) cert.set_pubkey(pkey) cert.sign(pkey, 'sha256' if PY3 else b'sha256') f = open(cert_path, 'w') f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode('utf-8')) f.close() f = open(key_path, 'w') f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey).decode('utf-8')) f.close()
def create_self_signed_cert(cert_dir="."): C_F = join(cert_dir, CERT_FILE) K_F = join(cert_dir, KEY_FILE) if not exists(C_F) or not exists(K_F): # create a key pair k = crypto.PKey() k.generate_key(crypto.TYPE_RSA, 1024) # create a self-signed cert cert = crypto.X509() cert.get_subject().C = raw_input("Country: ") cert.get_subject().ST = raw_input("State: ") cert.get_subject().L = raw_input("City: ") cert.get_subject().O = raw_input("Organization: ") cert.get_subject().OU = raw_input("Organizational Unit: ") cert.get_subject().CN = CN cert.set_serial_number(1000) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(315360000) cert.set_issuer(cert.get_subject()) cert.set_pubkey(k) cert.sign(k, 'sha1') open(C_F, "wt").write( crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) open(K_F, "wt").write( crypto.dump_privatekey(crypto.FILETYPE_PEM, k))
def create_self_signed_certificate(device_id, valid_days, cert_output_dir): cert_file = device_id + '-cert.pem' key_file = device_id + '-key.pem' # create a key pair key = crypto.PKey() key.generate_key(crypto.TYPE_RSA, 2048) # create a self-signed cert cert = crypto.X509() cert.get_subject().CN = device_id cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(valid_days * 24 * 60 * 60) cert.set_issuer(cert.get_subject()) cert.set_pubkey(key) cert.sign(key, 'sha256') cert_dump = crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode('utf-8') key_dump = crypto.dump_privatekey(crypto.FILETYPE_PEM, key).decode('utf-8') thumbprint = cert.digest('sha1').replace(b':', b'').decode('utf-8') if cert_output_dir is not None and exists(cert_output_dir): open(join(cert_output_dir, cert_file), "wt").write(cert_dump) open(join(cert_output_dir, key_file), "wt").write(key_dump) return { 'certificate': cert_dump, 'privateKey': key_dump, 'thumbprint': thumbprint }
def _generate_ssl_files(self): # Certificate and key files only for this session try: key_file = open(self.key_file_name, 'w') cert_file = open(self.cert_file_name, 'w') except: err_msg = 'Failed generated command port SSL files.\n' err_msg += 'For command functionality ensure permissions at %s' %\ tempfile.gettempdir() err_msg += ' or run the agent with administrative privileges.' logging.error(err_msg) self.ssl_files_generated = False return # Generate the key key = crypto.PKey() key.generate_key(crypto.TYPE_RSA, 1024) # Generate the certificate cert = crypto.X509() cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(self.cert_expire) cert.set_issuer(cert.get_subject()) cert.set_pubkey(key) cert.sign(key, 'sha1') # Write to files cert_file.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) key_file.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, key)) key_file.close() cert_file.close() self.ssl_files_generated = True
def generate_ssl_keys(): """ This method generates a new SSL key/cert. """ digest = "sha256" # Generate key pair pkey = crypto.PKey() pkey.generate_key(crypto.TYPE_RSA, 2048) # Generate cert request req = crypto.X509Req() subj = req.get_subject() setattr(subj, "CN", "Deluge Daemon") req.set_pubkey(pkey) req.sign(pkey, digest) # Generate certificate cert = crypto.X509() cert.set_serial_number(0) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(60 * 60 * 24 * 365 * 3) # Three Years cert.set_issuer(req.get_subject()) cert.set_subject(req.get_subject()) cert.set_pubkey(req.get_pubkey()) cert.sign(pkey, digest) # Write out files ssl_dir = deluge.configmanager.get_config_dir("ssl") open(os.path.join(ssl_dir, "daemon.pkey"), "w").write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)) open(os.path.join(ssl_dir, "daemon.cert"), "w").write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) # Make the files only readable by this user for f in ("daemon.pkey", "daemon.cert"): os.chmod(os.path.join(ssl_dir, f), stat.S_IREAD | stat.S_IWRITE)
def installCertificates(session): if not os.path.exists(CERT_FILE) or not os.path.exists(KEY_FILE): print "[OpenWebif] Generate SSL key pair and CACert" # create a key pair key = crypto.PKey() key.generate_key(crypto.TYPE_RSA, 1024) # create a self-signed cert cert = crypto.X509() cert.get_subject().C = "DE" cert.get_subject().ST = "Home" cert.get_subject().L = "Home" cert.get_subject().O = "OpenWebif" cert.get_subject().OU = "HTTPS-Server" cert.get_subject().CN = gethostname() cert.set_serial_number(random.randint(1000000,1000000000)) cert.set_notBefore("20120101000000Z"); cert.set_notAfter("20301231235900Z") cert.set_issuer(cert.get_subject()) cert.set_pubkey(key) cert.sign(key, 'sha1') try: print "[OpenWebif] Install newly generated certificate and key pair" open(CERT_FILE, "wt").write( crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) open(KEY_FILE, "wt").write( crypto.dump_privatekey(crypto.FILETYPE_PEM, key)) except IOError, e: #Disable https config.OpenWebif.https_enabled.value = False config.OpenWebif.https_enabled.save() #Inform the user session.open(MessageBox, "Cannot install generated SSL-Certifactes for https access\nHttps access is disabled!", MessageBox.TYPE_ERROR)
def generate(self): if not self.host: self.host = socket.gethostname() print "SSL Host used for Certificate Generation: "+self.host key = crypto.PKey() key.generate_key(crypto.TYPE_RSA, 2048) cert = crypto.X509() cert.get_subject().C = "IN" cert.get_subject().ST = "TN" cert.get_subject().L = "dodo" cert.get_subject().O = "dodo" cert.get_subject().OU = "dodo" cert.get_subject().CN = self.host cert.set_serial_number(1111) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(10 * 365 * 24 * 60 * 60) cert.set_issuer(cert.get_subject()) cert.set_pubkey(key) cert.sign(key, "sha1") with open(self.cert_path, "w") as f: f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) with open(self.key_path, "w") as f: f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, key))
def create_self_signed_cert(cert_dir): """ If datacard.crt and datacard.key don't exist in cert_dir, create a new self-signed cert and keypair and write them into that directory. """ if not exists(join(cert_dir, CERT_FILE)) \ or not exists(join(cert_dir, KEY_FILE)): # create a key pair k = crypto.PKey() k.generate_key(crypto.TYPE_RSA, 1024) # CREATE A SELF-SIGNED CERT cert = crypto.X509() cert.get_subject().C = "FR" cert.get_subject().ST = "Paris" cert.get_subject().L = "Paris" cert.get_subject().O = "Resilient Logger" cert.get_subject().OU = "Resilient Logger" cert.get_subject().CN = gethostname() cert.set_serial_number(1000) 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') open( join(cert_dir, CERT_FILE), "wt").write( crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) open( join(cert_dir, KEY_FILE), "wt").write( crypto.dump_privatekey(crypto.FILETYPE_PEM, k))
def create_key(key_file): """Create SSL key in specified key file.""" key = crypto.PKey() key.generate_key(crypto.TYPE_RSA, 4096) with open(os.path.join(key_file), 'wt') as file: file.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, key)) return key
def dump_privkey(path, pkey): with open(path, "w+") as f: pem = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey) f.write(pem)
def generate_keypair(crypt_type=crypto.TYPE_RSA, bits=2048): pkey = crypto.PKey() pkey.generate_key(crypt_type, bits) pubkey = crypto.dump_publickey(crypto.FILETYPE_PEM, pkey) privkey = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey) return pubkey, privkey
def write_key(path, key): with open(path, 'wb') as f: f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, key)) print('Created ' + path)
def certidude_request_certificate(url, key_path, request_path, certificate_path, authority_path, common_name, org_unit, email_address=None, given_name=None, surname=None, autosign=False, wait=False, key_usage=None, extended_key_usage=None, ip_address=None, dns=None): """ Exchange CSR for certificate using Certidude HTTP API server """ # Set up URL-s request_params = set() if autosign: request_params.add("autosign=yes") if wait: request_params.add("wait=forever") if not url.endswith("/"): url = url + "/" authority_url = url + "certificate" request_url = url + "request" if request_params: request_url = request_url + "?" + "&".join(request_params) if os.path.exists(authority_path): click.echo("Found CA certificate in: %s" % authority_path) else: if authority_url: click.echo("Attempting to fetch CA certificate from %s" % authority_url) try: with urllib.request.urlopen(authority_url) as fh: buf = fh.read() try: cert = crypto.load_certificate(crypto.FILETYPE_PEM, buf) except crypto.Error: raise ValueError("Failed to parse PEM: %s" % buf) with open(authority_path + ".part", "wb") as oh: oh.write(buf) click.echo("Writing CA certificate to: %s" % authority_path) os.rename(authority_path + ".part", authority_path) except urllib.error.HTTPError as e: click.echo( "Failed to fetch CA certificate, server responded with: %d %s" % (e.code, e.reason), err=True) return 1 else: raise FileNotFoundError( "CA certificate not found and no URL specified") try: certificate = Certificate(open(certificate_path)) click.echo("Found certificate: %s" % certificate_path) except FileNotFoundError: try: request = Request(open(request_path)) click.echo("Found signing request: %s" % request_path) except FileNotFoundError: # Construct private key click.echo("Generating 4096-bit RSA key...") key = crypto.PKey() key.generate_key(crypto.TYPE_RSA, 4096) # Dump private key os.umask(0o077) with open(key_path + ".part", "wb") as fh: fh.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, key)) # Construct CSR csr = crypto.X509Req() csr.set_version(2) # Corresponds to X.509v3 csr.set_pubkey(key) request = Request(csr) # Set subject attributes request.common_name = common_name if given_name: request.given_name = given_name if surname: request.surname = surname if org_unit: request.organizational_unit = org_unit # Collect subject alternative names subject_alt_name = set() if email_address: subject_alt_name.add("email:" + email_address) if ip_address: subject_alt_name.add("IP:" + ip_address) if dns: subject_alt_name.add("DNS:" + dns) # Set extensions extensions = [] if key_usage: extensions.append(("keyUsage", key_usage, True)) if extended_key_usage: extensions.append( ("extendedKeyUsage", extended_key_usage, True)) if subject_alt_name: extensions.append( ("subjectAltName", ", ".join(subject_alt_name), True)) request.set_extensions(extensions) # Dump CSR os.umask(0o022) with open(request_path + ".part", "w") as fh: fh.write(request.dump()) click.echo("Writing private key to: %s" % key_path) os.rename(key_path + ".part", key_path) click.echo("Writing certificate signing request to: %s" % request_path) os.rename(request_path + ".part", request_path) with open(request_path, "rb") as fh: buf = fh.read() submission = urllib.request.Request(request_url, buf) submission.add_header("User-Agent", "Certidude") submission.add_header("Content-Type", "application/pkcs10") click.echo("Submitting to %s, waiting for response..." % request_url) try: response = urllib.request.urlopen(submission) buf = response.read() if response.code == 202: click.echo( "No waiting was requested and server responded with 202 Accepted, run this command again once the certificate is signed" ) return 1 assert buf, "Server responded with no body, status code %d" % response.code cert = crypto.load_certificate(crypto.FILETYPE_PEM, buf) except crypto.Error: raise ValueError("Failed to parse PEM: %s" % buf) except urllib.error.HTTPError as e: if e.code == 409: click.echo( "Different signing request with same CN is already present on server, server refuses to overwrite", err=True) return 2 else: click.echo( "Failed to fetch certificate, server responded with: %d %s" % (e.code, e.reason), err=True) return 3 else: if response.code == 202: click.echo( "Server stored the request for processing (202 Accepted), but waiting was not requested, hence quitting for now", err=True) return 254 os.umask(0o022) with open(certificate_path + ".part", "wb") as gh: gh.write(buf) click.echo("Writing certificate to: %s" % certificate_path) os.rename(certificate_path + ".part", certificate_path)
f = open(priv_key_file, 'r') priv_key_pem = f.read() f.close() priv_key = crypto.load_privatekey(crypto.FILETYPE_PEM, priv_key_pem) sig = crypto.sign(priv_key, thing_name, 'sha256') sig = base64.b64encode(sig) # ### Create a Provisioning Request with own private key and CSR # If you want to create the private on your own you can send a CSR together with the provisioning request and let AWS IoT issue the certificate. if use_own_priv_key: print("=> creating own private key...") cont() device_priv_key = crypto.PKey() device_priv_key.generate_key(crypto.TYPE_RSA, 2048) print(crypto.dump_privatekey(crypto.FILETYPE_PEM, device_priv_key)) file_k = open(key_file, "w") file_k.write( crypto.dump_privatekey(crypto.FILETYPE_PEM, device_priv_key)) file_k.close() csr = crypto.X509Req() subj = csr.get_subject() setattr(subj, "CN", thing_name) csr.set_pubkey(device_priv_key) csr.sign(device_priv_key, 'sha256') print(crypto.dump_certificate_request(crypto.FILETYPE_PEM, csr)) file_cs = open(csr_file, "w") file_cs.write(crypto.dump_certificate_request(crypto.FILETYPE_PEM,
def generate_ssl_cert(target_file=None, overwrite=False, random=False, return_content=False, serial_number=None): # Note: Do NOT import "OpenSSL" at the root scope # (Our test Lambdas are importing this file but don't have the module installed) from OpenSSL import crypto def all_exist(*files): return all([os.path.exists(f) for f in files]) def store_cert_key_files(base_filename): key_file_name = '%s.key' % base_filename cert_file_name = '%s.crt' % base_filename # extract key and cert from target_file and store into separate files content = load_file(target_file) key_start = '-----BEGIN PRIVATE KEY-----' key_end = '-----END PRIVATE KEY-----' cert_start = '-----BEGIN CERTIFICATE-----' cert_end = '-----END CERTIFICATE-----' key_content = content[content.index(key_start): content.index(key_end) + len(key_end)] cert_content = content[content.index(cert_start): content.rindex(cert_end) + len(cert_end)] save_file(key_file_name, key_content) save_file(cert_file_name, cert_content) return cert_file_name, key_file_name if target_file and not overwrite and os.path.exists(target_file): key_file_name = '' cert_file_name = '' try: cert_file_name, key_file_name = store_cert_key_files(target_file) except Exception as e: # fall back to temporary files if we cannot store/overwrite the files above LOG.info('Error storing key/cert SSL files (falling back to random tmp file names): %s' % e) target_file_tmp = new_tmp_file() cert_file_name, key_file_name = store_cert_key_files(target_file_tmp) if all_exist(cert_file_name, key_file_name): return target_file, cert_file_name, key_file_name if random and target_file: if '.' in target_file: target_file = target_file.replace('.', '.%s.' % short_uid(), 1) else: target_file = '%s.%s' % (target_file, short_uid()) # create a key pair k = crypto.PKey() k.generate_key(crypto.TYPE_RSA, 2048) # create a self-signed cert cert = crypto.X509() subj = cert.get_subject() subj.C = 'AU' subj.ST = 'Some-State' subj.L = 'Some-Locality' subj.O = 'LocalStack Org' # noqa subj.OU = 'Testing' subj.CN = 'localhost' # Note: new requirements for recent OSX versions: https://support.apple.com/en-us/HT210176 # More details: https://www.iol.unh.edu/blog/2019/10/10/macos-catalina-and-chrome-trust serial_number = serial_number or 1001 cert.set_version(2) cert.set_serial_number(serial_number) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(2 * 365 * 24 * 60 * 60) cert.set_issuer(cert.get_subject()) cert.set_pubkey(k) alt_names = b'DNS:localhost,DNS:test.localhost.atlassian.io,DNS:localhost.localstack.cloud,IP:127.0.0.1' cert.add_extensions([ crypto.X509Extension(b'subjectAltName', False, alt_names), crypto.X509Extension(b'basicConstraints', True, b'CA:false'), crypto.X509Extension(b'keyUsage', True, b'nonRepudiation,digitalSignature,keyEncipherment'), crypto.X509Extension(b'extendedKeyUsage', True, b'serverAuth') ]) cert.sign(k, 'SHA256') cert_file = StringIO() key_file = StringIO() cert_file.write(to_str(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))) key_file.write(to_str(crypto.dump_privatekey(crypto.FILETYPE_PEM, k))) cert_file_content = cert_file.getvalue().strip() key_file_content = key_file.getvalue().strip() file_content = '%s\n%s' % (key_file_content, cert_file_content) if target_file: key_file_name = '%s.key' % target_file cert_file_name = '%s.crt' % target_file # check existence to avoid permission denied issues: # https://github.com/localstack/localstack/issues/1607 if not all_exist(target_file, key_file_name, cert_file_name): for i in range(2): try: save_file(target_file, file_content) save_file(key_file_name, key_file_content) save_file(cert_file_name, cert_file_content) break except Exception as e: if i > 0: raise LOG.info('Unable to store certificate file under %s, using tmp file instead: %s' % (target_file, e)) # Fix for https://github.com/localstack/localstack/issues/1743 target_file = '%s.pem' % new_tmp_file() key_file_name = '%s.key' % target_file cert_file_name = '%s.crt' % target_file TMP_FILES.append(target_file) TMP_FILES.append(key_file_name) TMP_FILES.append(cert_file_name) if not return_content: return target_file, cert_file_name, key_file_name return file_content
async def cert_extend(self, cert): """Extend certificate with some useful attributes.""" if cert.get('signedby'): # We query for signedby again to make sure it's keys do not have the "cert_" prefix and it has gone through # the cert_extend method cert['signedby'] = await self.middleware.call( 'datastore.query', 'system.certificateauthority', [('id', '=', cert['signedby']['id'])], { 'prefix': 'cert_', 'extend': 'certificate.cert_extend', 'get': True } ) # convert san to list cert['san'] = (cert.pop('san', '') or '').split() if cert['serial'] is not None: cert['serial'] = int(cert['serial']) if cert['type'] in ( CA_TYPE_EXISTING, CA_TYPE_INTERNAL, CA_TYPE_INTERMEDIATE ): root_path = CERT_CA_ROOT_PATH else: root_path = CERT_ROOT_PATH cert['root_path'] = root_path cert['certificate_path'] = os.path.join( root_path, '{0}.crt'.format(cert['name']) ) cert['privatekey_path'] = os.path.join( root_path, '{0}.key'.format(cert['name']) ) cert['csr_path'] = os.path.join( root_path, '{0}.csr'.format(cert['name']) ) def cert_issuer(cert): issuer = None if cert['type'] in (CA_TYPE_EXISTING, CERT_TYPE_EXISTING): issuer = "external" elif cert['type'] == CA_TYPE_INTERNAL: issuer = "self-signed" elif cert['type'] in (CERT_TYPE_INTERNAL, CA_TYPE_INTERMEDIATE): issuer = cert['signedby'] elif cert['type'] == CERT_TYPE_CSR: issuer = "external - signature pending" return issuer cert['issuer'] = cert_issuer(cert) cert['chain_list'] = [] if cert['chain']: certs = RE_CERTIFICATE.findall(cert['certificate']) else: certs = [cert['certificate']] signing_CA = cert['issuer'] # Recursively get all internal/intermediate certificates # FIXME: NONE HAS BEEN ADDED IN THE FOLLOWING CHECK FOR CSR'S WHICH HAVE BEEN SIGNED BY A CA while signing_CA not in ["external", "self-signed", "external - signature pending", None]: certs.append(signing_CA['certificate']) signing_CA['issuer'] = cert_issuer(signing_CA) signing_CA = signing_CA['issuer'] cert_obj = None try: for c in certs: # XXX Why load certificate if we are going to dump it right after? # Maybe just to verify its integrity? # Logic copied from freenasUI cert_obj = crypto.load_certificate(crypto.FILETYPE_PEM, c) cert['chain_list'].append( crypto.dump_certificate(crypto.FILETYPE_PEM, cert_obj).decode() ) except Exception: self.logger.debug('Failed to load certificate {0}'.format(cert['name']), exc_info=True) try: if cert['privatekey']: key_obj = crypto.load_privatekey(crypto.FILETYPE_PEM, cert['privatekey']) cert['privatekey'] = crypto.dump_privatekey(crypto.FILETYPE_PEM, key_obj).decode() except Exception: self.logger.debug('Failed to load privatekey {0}'.format(cert['name']), exc_info=True) try: if cert['CSR']: csr_obj = crypto.load_certificate_request(crypto.FILETYPE_PEM, cert['CSR']) cert['CSR'] = crypto.dump_certificate_request(crypto.FILETYPE_PEM, csr_obj).decode() except Exception: self.logger.debug('Failed to load csr {0}'.format(cert['name']), exc_info=True) cert['internal'] = 'NO' if cert['type'] in (CA_TYPE_EXISTING, CERT_TYPE_EXISTING) else 'YES' obj = None # date not applicable for CSR cert['from'] = None cert['until'] = None if cert['type'] == CERT_TYPE_CSR: obj = csr_obj elif cert_obj: obj = crypto.load_certificate(crypto.FILETYPE_PEM, cert['certificate']) notBefore = obj.get_notBefore() t1 = dateutil.parser.parse(notBefore) t2 = t1.astimezone(dateutil.tz.tzutc()) cert['from'] = t2.ctime() notAfter = obj.get_notAfter() t1 = dateutil.parser.parse(notAfter) t2 = t1.astimezone(dateutil.tz.tzutc()) cert['until'] = t2.ctime() if obj: cert['DN'] = '/' + '/'.join([ '%s=%s' % (c[0].decode(), c[1].decode()) for c in obj.get_subject().get_components() ]) return cert
if newcryptolib: password = bytes(password, encoding='utf-8') try: p12 = c.load_pkcs12(open(infile, 'rb').read(), password) except: g.msgbox('Error: invalid pack or password. Exiting.') exit(6) try: cert = c.dump_certificate(c.FILETYPE_PEM, p12.get_certificate()) certfile = open('client.crt', 'wb') certfile.write(cert) certfile.close() key = c.dump_privatekey(c.FILETYPE_PEM, p12.get_privatekey()) rsakey = RSA.importKey(key) keyfile = open('client.key', 'wb') keyfile.write(rsakey.exportKey()) keyfile.close() os.chmod('client.key', 400) cacert = c.dump_certificate(c.FILETYPE_PEM, p12.get_ca_certificates()[0]) cacertfile = open('whoisxmlapi.ca', 'wb') cacertfile.write(cacert) cacertfile.close() except: g.msgbox( 'Error: could not overwrite one of the files.\nEnsure that the following files do not exist or can be overwritten:\n whoisxmlapi.ca\n client.crt\n client.key\n' ) exit(1)
def generate_ssl_cert(target_file=None, overwrite=False, random=False, return_content=False, serial_number=None): # Note: Do NOT import "OpenSSL" at the root scope # (Our test Lambdas are importing this file but don't have the module installed) from OpenSSL import crypto if target_file and not overwrite and os.path.exists(target_file): key_file_name = '%s.key' % target_file cert_file_name = '%s.crt' % target_file return target_file, cert_file_name, key_file_name if random and target_file: if '.' in target_file: target_file = target_file.replace('.', '.%s.' % short_uid(), 1) else: target_file = '%s.%s' % (target_file, short_uid()) # create a key pair k = crypto.PKey() k.generate_key(crypto.TYPE_RSA, 1024) # create a self-signed cert cert = crypto.X509() subj = cert.get_subject() subj.C = 'AU' subj.ST = 'Some-State' subj.L = 'Some-Locality' subj.O = 'LocalStack Org' # noqa subj.OU = 'Testing' subj.CN = 'localhost' serial_number = serial_number or 1001 cert.set_serial_number(serial_number) 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') cert_file = StringIO() key_file = StringIO() cert_file.write(to_str(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))) key_file.write(to_str(crypto.dump_privatekey(crypto.FILETYPE_PEM, k))) cert_file_content = cert_file.getvalue().strip() key_file_content = key_file.getvalue().strip() file_content = '%s\n%s' % (key_file_content, cert_file_content) if target_file: key_file_name = '%s.key' % target_file cert_file_name = '%s.crt' % target_file # check existence to avoid permission denied issues: # https://github.com/localstack/localstack/issues/1607 if not os.path.exists(target_file): save_file(target_file, file_content) save_file(key_file_name, key_file_content) save_file(cert_file_name, cert_file_content) TMP_FILES.append(target_file) TMP_FILES.append(key_file_name) TMP_FILES.append(cert_file_name) if not return_content: return target_file, cert_file_name, key_file_name return file_content
""" cert = crypto.X509() cert.set_serial_number(serial) cert.gmtime_adj_notBefore(notBefore) cert.gmtime_adj_notAfter(notAfter) cert.set_issuer(issuerCert.get_subject()) cert.set_subject(req.get_subject()) cert.set_pubkey(req.get_pubkey()) cert.sign(issuerKey, digest) return cert if not exists(C_F) or not exists(K_F): k = createKeyPair(crypto.TYPE_RSA, 2048) req = createCertRequest(k, C=konf['countryName_default'], ST=konf['stateOrProvinceName_default'], L=konf['localityName'], O=konf['0.organizationName_default'], OU=konf['organizationalUnitName'], CN=CN) cert = createCertificate(req, (req, k), 0, (0, 60 * 60 * 24 * 365 * 5)) open(C_F, "wt").write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) open(K_F, "wt").write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k)) print "> Wrote certificate to %s and key to %s" % (C_F, K_F) else: print "> Not able to create a certificate. %s.crt or %s.key exists" % (CN, CN)
def check(self, module, perms_required=True): """Ensure the resource is in its desired state.""" state_and_perms = super(Pkcs, self).check(module, perms_required) def _check_pkey_passphrase(): if self.privatekey_passphrase: try: crypto_utils.load_privatekey(self.privatekey_path, self.privatekey_passphrase) except crypto.Error: return False except crypto_utils.OpenSSLBadPassphraseError: return False return True if not state_and_perms: return state_and_perms if os.path.exists(self.path) and module.params['action'] == 'export': dummy = self.generate(module) self.src = self.path try: pkcs12_privatekey, pkcs12_certificate, pkcs12_other_certificates, pkcs12_friendly_name = self.parse( ) except crypto.Error: return False if (pkcs12_privatekey is not None) and (self.privatekey_path is not None): expected_pkey = crypto.dump_privatekey( crypto.FILETYPE_PEM, self.pkcs12.get_privatekey()) if pkcs12_privatekey != expected_pkey: return False elif bool(pkcs12_privatekey) != bool(self.privatekey_path): return False if (pkcs12_certificate is not None) and (self.certificate_path is not None): expected_cert = crypto.dump_certificate( crypto.FILETYPE_PEM, self.pkcs12.get_certificate()) if pkcs12_certificate != expected_cert: return False elif bool(pkcs12_certificate) != bool(self.certificate_path): return False if (pkcs12_other_certificates is not None) and (self.other_certificates is not None): expected_other_certs = [ crypto.dump_certificate(crypto.FILETYPE_PEM, other_cert) for other_cert in self.pkcs12.get_ca_certificates() ] if set(pkcs12_other_certificates) != set(expected_other_certs): return False elif bool(pkcs12_other_certificates) != bool( self.other_certificates): return False if pkcs12_privatekey: # This check is required because pyOpenSSL will not return a friendly name # if the private key is not set in the file if ((self.pkcs12.get_friendlyname() is not None) and (pkcs12_friendly_name is not None)): if self.pkcs12.get_friendlyname() != pkcs12_friendly_name: return False elif bool(self.pkcs12.get_friendlyname()) != bool( pkcs12_friendly_name): return False else: return False return _check_pkey_passphrase()
def gen_signed_cert(domain, ca_crt, ca_key, ca_pass, certs_folder): """ This function takes a domain name as a parameter and then creates a certificate and key with the domain name(replacing dots by underscores), finally signing the certificate using specified CA and returns the path of key and cert files. If you are yet to generate a CA then check the top comments """ key_path = os.path.join(certs_folder, re.sub('[^-0-9a-zA-Z_]', '_', domain) + ".key") cert_path = os.path.join(certs_folder, re.sub('[^-0-9a-zA-Z_]', '_', domain) + ".crt") # The first conditions checks if file exists, and does nothing if true # If file doenst exist lock is obtained for writing (Other processes in race must wait) # After obtaining lock another check to handle race conditions gracefully if os.path.exists(key_path) and os.path.exists(cert_path): pass else: with FileLock(cert_path, timeout=2): # Check happens if the certificate and key pair already exists for a domain if os.path.exists(key_path) and os.path.exists(cert_path): pass else: # Serial Generation - Serial number must be unique for each certificate, # so serial is generated based on domain name md5_hash = hashlib.md5() md5_hash.update(domain) serial = int(md5_hash.hexdigest(), 36) # The CA stuff is loaded from the same folder as this script ca_cert = crypto.load_certificate(crypto.FILETYPE_PEM, open(ca_crt).read()) # The last parameter is the password for your CA key file ca_key = crypto.load_privatekey(crypto.FILETYPE_PEM, open(ca_key).read(), ca_pass) key = crypto.PKey() key.generate_key(crypto.TYPE_RSA, 2048) cert = crypto.X509() cert.get_subject().C = "IN" cert.get_subject().ST = "AP" cert.get_subject().L = "127.0.0.1" cert.get_subject().O = "OWTF" cert.get_subject().OU = "Inbound-Proxy" cert.get_subject().CN = domain cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(365 * 24 * 60 * 60) cert.set_serial_number(serial) cert.set_issuer(ca_cert.get_subject()) cert.set_pubkey(key) cert.sign(ca_key, "sha1") # The key and cert files are dumped and their paths are returned domain_key = open(key_path, "w") domain_key.write( crypto.dump_privatekey(crypto.FILETYPE_PEM, key)) domain_cert = open(cert_path, "w") domain_cert.write( crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) # print(("[*] Generated signed certificate for %s" % (domain))) return key_path, cert_path
def action_process(self): filecontent = base64.b64decode(self.file_content) try: p12 = crypto.load_pkcs12(filecontent, self.password) except: raise UserError('Error al abrir la firma, posiblmente ha ingresado\ mal la clave de la firma o el archivo no es compatible.') cert = p12.get_certificate() privky = p12.get_privatekey() cacert = p12.get_ca_certificates() issuer = cert.get_issuer() subject = cert.get_subject() self.write({ 'emision_date': datetime.strptime(cert.get_notBefore().decode("utf-8"), '%Y%m%d%H%M%SZ'), 'expire_date': datetime.strptime(cert.get_notAfter().decode("utf-8"), '%Y%m%d%H%M%SZ'), 'subject_c': subject.C, 'subject_title': subject.title, 'subject_common_name': subject.CN, 'subject_serial_number': subject.serialNumber, 'subject_email_address': subject.emailAddress, 'issuer_country': issuer.C, 'issuer_organization': issuer.O, 'issuer_common_name': issuer.CN, 'issuer_serial_number': issuer.serialNumber, 'issuer_email_address': issuer.emailAddress, 'cert_serial_number': cert.get_serial_number(), 'cert_signature_algor': cert.get_signature_algorithm(), 'cert_version': cert.get_version(), 'cert_hash': cert.subject_name_hash(), 'private_key_bits': privky.bits(), 'private_key_check': privky.check(), 'private_key_type': privky.type(), 'priv_key': crypto.dump_privatekey(type_, p12.get_privatekey()), 'cert': crypto.dump_certificate(type_, p12.get_certificate()), 'password': False, }) self.set_state()
def request_cert(domain): domain = domain.lower() print("Generating user key") user_key = josepy.JWKRSA( key=rsa.generate_private_key( public_exponent=65537, key_size=KEY_SIZE, backend=default_backend() ) ) save_key(user_key, domain) print("Connecting to Let's Encrypt on {}".format(DIRECTORY_URL)) acme = client.Client(DIRECTORY_URL, user_key) print("Registering") regr = acme.register() print("Agreeing to ToS") acme.agree_to_tos(regr) print("Requesting challenges") authzr = acme.request_challenges( identifier=messages.Identifier(typ=messages.IDENTIFIER_FQDN, value=domain) ) print("Looking for DNS challenge") challenge = get_dns_challenge(authzr) print("You need to set up the challenge response.") print("DNS (TXT) record: _acme-challenge.{}".format(domain)) print("Content: {}".format(challenge.chall.validation(user_key))) response = challenge.chall.response(user_key) while not response.simple_verify(challenge.chall, domain, user_key.public_key()): input("It doesn't look like it's set up yet; press return when it is.") print("Authorizing -- here goes...") auth_response = acme.answer_challenge(challenge, challenge.chall.response(user_key)) print("Response was {}".format(auth_response.body.status.name)) print("Waiting for authorization to become valid") while True: print("Polling") authzr, authzr_response = acme.poll(authzr) challenge = get_dns_challenge(authzr) if challenge.status.name == "valid": break print("DNS challenge is currently {}".format(challenge.status.name)) time.sleep(10) print("Auth valid") print("Generating CSR") certificate_key = crypto.PKey() certificate_key.generate_key(crypto.TYPE_RSA, 2048) csr = crypto.X509Req() csr.get_subject().CN = domain csr.set_pubkey(certificate_key) csr.sign(certificate_key, "sha256") print("Requesting certificate") certificate_response = acme.request_issuance(josepy.util.ComparableX509(csr), [authzr]) print("Got it!") print("Fetching chain") chain = acme.fetch_chain(certificate_response) print("Done!") print("Here are the details:") print("Private key:") print(crypto.dump_privatekey(FILETYPE_PEM, certificate_key)) print("Combined cert:") print(crypto.dump_certificate(FILETYPE_PEM, certificate_response.body.wrapped)) for cert in chain: print(crypto.dump_certificate(FILETYPE_PEM, cert.wrapped))
def export_privatekey(key, passphrase=None, format='PEM'): crypto_format = _get_crypto_format(format) private_key = crypto.dump_privatekey(crypto_format, key) return private_key
def create_self_signed_cert(config, messages): """ OpenSSL wrapper to create selfsigned CA. """ # for now hardcoded place for landing CACert file on servers config['CONFIG_SSL_CACERT'] = '/etc/pki/tls/certs/packstack_cacert.crt' # if (config['CONFIG_AMQP_ENABLE_SSL'] != 'y' and # config["CONFIG_HORIZON_SSL"] != 'y'): if config['CONFIG_AMQP_ENABLE_SSL'] != 'y': return config['CONFIG_SSL_CERT_DIR'] = os.path.expanduser( config['CONFIG_SSL_CERT_DIR']) if not os.path.isdir(config['CONFIG_SSL_CERT_DIR']): os.mkdir(config['CONFIG_SSL_CERT_DIR']) certs = os.path.join(config['CONFIG_SSL_CERT_DIR'], 'certs') if not os.path.isdir(certs): os.mkdir(certs) keys = os.path.join(config['CONFIG_SSL_CERT_DIR'], 'keys') if not os.path.isdir(keys): os.mkdir(keys) if config['CONFIG_SSL_CACERT_SELFSIGN'] != 'y': return CERT_FILE = config['CONFIG_SSL_CACERT_FILE'] = ( '%s/certs/selfcert.crt' % config['CONFIG_SSL_CERT_DIR']) KEY_FILE = config['CONFIG_SSL_CACERT_KEY_FILE'] = ( '%s/keys/selfcert.crt' % config['CONFIG_SSL_CERT_DIR']) if not os.path.exists(CERT_FILE) or not os.path.exists(KEY_FILE): # create a key pair k = crypto.PKey() k.generate_key(crypto.TYPE_RSA, 4096) # create a self-signed cert mail = config['CONFIG_SSL_CERT_SUBJECT_MAIL'] cert = crypto.X509() subject = cert.get_subject() subject.C = config['CONFIG_SSL_CERT_SUBJECT_C'] subject.ST = config['CONFIG_SSL_CERT_SUBJECT_ST'] subject.L = config['CONFIG_SSL_CERT_SUBJECT_L'] subject.O = config['CONFIG_SSL_CERT_SUBJECT_O'] subject.OU = config['CONFIG_SSL_CERT_SUBJECT_OU'] subject.CN = config['CONFIG_SSL_CERT_SUBJECT_CN'] subject.emailAddress = mail cert.set_serial_number(1000) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(10 * 365 * 24 * 60 * 60) cert.set_issuer(cert.get_subject()) cert.set_pubkey(k) # CA extensions cert.add_extensions([ crypto.X509Extension("basicConstraints".encode('ascii'), False, "CA:TRUE".encode('ascii')), crypto.X509Extension("keyUsage".encode('ascii'), False, "keyCertSign, cRLSign".encode('ascii')), crypto.X509Extension("subjectKeyIdentifier".encode('ascii'), False, "hash".encode('ascii'), subject=cert), ]) cert.add_extensions([ crypto.X509Extension("authorityKeyIdentifier".encode('ascii'), False, "keyid:always".encode('ascii'), issuer=cert) ]) cert.sign(k, 'sha1') open((CERT_FILE), "wt").write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) open((KEY_FILE), "wt").write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k)) messages.append( "%sNOTE%s : A selfsigned CA certificate was generated to be used " "for ssl, you should still change it do subordinate CA cert. In " "any case please save the contents of %s." % (utils.COLORS['red'], utils.COLORS['nocolor'], config['CONFIG_SSL_CERT_DIR']))
def get_certificate_from_publish_settings(publish_settings_path, path_to_write_certificate, subscription_id=None): ''' Writes a certificate file to the specified location. This can then be used to instantiate ServiceManagementService. Returns the subscription ID. publish_settings_path: Path to subscription file downloaded from http://go.microsoft.com/fwlink/?LinkID=301775 path_to_write_certificate: Path to write the certificate file. subscription_id: (optional) Provide a subscription id here if you wish to use a specific subscription under the publish settings file. ''' import base64 try: from xml.etree import cElementTree as ET except ImportError: from xml.etree import ElementTree as ET try: import OpenSSL.crypto as crypto except: raise Exception( "pyopenssl is required to use get_certificate_from_publish_settings" ) _validate_not_none('publish_settings_path', publish_settings_path) _validate_not_none('path_to_write_certificate', path_to_write_certificate) # parse the publishsettings file and find the ManagementCertificate Entry tree = ET.parse(publish_settings_path) subscriptions = tree.getroot().findall("./PublishProfile/Subscription") # Default to the first subscription in the file if they don't specify # or get the matching subscription or return none. if subscription_id: subscription = next( (s for s in subscriptions if s.get('Id').lower() == subscription_id.lower()), None) else: subscription = subscriptions[0] # validate that subscription was found if subscription is None: raise ValueError( "The provided subscription_id '{}' was not found in the publish settings file provided at '{}'" .format(subscription_id, publish_settings_path)) cert_string = _decode_base64_to_bytes( subscription.get('ManagementCertificate')) # Load the string in pkcs12 format. Don't provide a password as it isn't encrypted. cert = crypto.load_pkcs12(cert_string, b'') # Write the data out as a PEM format to a random location in temp for use under this run. with open(path_to_write_certificate, 'wb') as f: f.write( crypto.dump_certificate(crypto.FILETYPE_PEM, cert.get_certificate())) f.write( crypto.dump_privatekey(crypto.FILETYPE_PEM, cert.get_privatekey())) return subscription.get('Id')
def dump_keys(key): print( crypto.dump_publickey(crypto.FILETYPE_PEM, key).decode('utf-8') + "\n" + \ crypto.dump_privatekey(crypto.FILETYPE_PEM, key ).decode('utf-8') )
def write_privatekey(privatekey, path, passphrase=None): open(path, "w").write( crypto.dump_privatekey( crypto.FILETYPE_PEM, privatekey, passphrase=str(passphrase) if passphrase else None))
def generate_deviceCert(): # Prompt user for basic registration information fullName = client_fullName() email = raw_input( 'Enter your DoD e-mail address i.e., [email protected]: \n>E-mail: ' ) edipi = client_edipi() device_serial = raw_input( 'Enter your device serial number: \n>Device S/N: ') # Initial biometric verification fingerprint = biometric_verification() # Timer start = time.time() # Populate certificate fields if len(fullName.split(' ')) == 3: # middlename included firstName = fullName.split(' ')[0].upper() middleName = fullName.split(' ')[1].upper() lastName = fullName.split(' ')[2].upper() CN = lastName + '.' + firstName + '.' + middleName + '.' + str(edipi) else: # No middlename firstName = fullName.split(' ')[0].upper() lastName = fullName.split(' ')[1].upper() CN = lastName + '.' + firstName + '.' + str(edipi) print('\nSending user and device information') connection.sendall(CN + ',' + edipi + ',' + fingerprint + ',' + device_serial + ',' + email + '\n') server_reply = connection.recv(1024) print('Server Response: ' + server_reply) OU = 'USMC' O = 'U.S. Government' C = 'US' serial_number = int(generate_serialNumber(6)) notBefore = 0 notAfter = 10 * 365 * 24 * 60 * 60 privateKey = CN + '.key' pubCert = CN + '.crt' # Generate 2048-bit RSA private key print('Generating 2048-bit RSA private key\n') key = crypto.PKey() key.generate_key(crypto.TYPE_RSA, 2048) # Generate self-signed X.509 public certificate # Check certificate: openssl x509 -in selfsigned.crt -noout -text # Check private key: openssl rsa -in private.key -check print('Generating self-signed X.509 public certificate\n') x509 = crypto.X509() x509.get_subject().emailAddress = email x509.get_subject().OU = OU x509.get_subject().CN = CN x509.get_subject().O = O x509.get_subject().C = C x509.set_serial_number(serial_number) x509.gmtime_adj_notBefore(notBefore) x509.gmtime_adj_notAfter(notAfter) x509.set_issuer(x509.get_subject()) x509.set_pubkey(key) x509.sign(key, 'sha256') with open(pubCert, 'wt') as pubCert_file: pubCert_file.write( crypto.dump_certificate(crypto.FILETYPE_PEM, x509).decode('utf-8')) with open(privateKey, 'wt') as privateKey_file: privateKey_file.write( crypto.dump_privatekey(crypto.FILETYPE_PEM, key).decode('utf-8')) # Prepare self-signed public certificate for export print('Creating p12 containg self-signed public certificate\n') self_p12 = generate_p12(CN, pubCert) # Sending p12 containing self-signed public certificate print('Checking if server is ready for file transfer...') connection.sendall(self_p12 + '\n') server_reply = connection.recv(1024) print('Server Response: ' + server_reply) # Server is ready for the file transfer, send p12 thread = threading.Thread(target=os.system('python ./send_p7.py ' + self_p12)) thread.start() thread.join() # Confirm server receipt connection.sendall('OK\n') server_reply = connection.recv(1024) fileSize = int(server_reply.split(' ')[1]) fileName = server_reply.split(' ')[0] print('Server Response: ' + server_reply) # Server p7 initiation message connection.sendall('OK - Send\n') # Receive server challenge p7 decryptMsg = 'decrypted.txt' thread = threading.Thread(target=os.system('python ./receive_p7.py ' + fileName + ' ' + str(fileSize))) thread.start() thread.join() # Decrypt the p7 to extract the server's challenge password thread = threading.Thread( target=os.system('openssl smime -decrypt -inform pem -in ' + fileName + ' -inkey ' + privateKey + ' -out ' + decryptMsg)) thread.start() thread.join() print(fileName + ' successfully decrypted with ' + privateKey + '; server challenge stored as ' + decryptMsg + '\n') # Create a signed p7 containing the encrypted decrypted challenge signedp7 = 'signed.p7' thread = threading.Thread( target=os.system('openssl smime -sign -nodetach -in ' + decryptMsg + ' -out ' + signedp7 + ' -outform pem -inkey ' + privateKey + ' -signer ' + pubCert)) thread.start() thread.join() print(signedp7 + ' containing ' + decryptMsg + ' successfuly encrypted and signed with ' + privateKey + '\n') # Check if server ready for file transfer print('Checking if server is ready for file transfer...') connection.sendall(signedp7 + '\n') server_reply = connection.recv(1024) print('Server Response: ' + server_reply) # Send the signed p7 thread = threading.Thread(target=os.system('python ./send_p7.py ' + signedp7)) thread.start() thread.join() # Check if server successfuly received p7 server_reply = connection.recv(1024) print('Server Response: ' + server_reply) # Signal to receive p7 containing SCEP instructions connection.sendall('OK CA\n') server_reply = connection.recv(1024) fileSize = int(server_reply.split(' ')[1]) fileName = server_reply.split(' ')[0] print('Server Response: ' + server_reply) # Server p7 initiation message connection.sendall('OK - Send\n') # Receive the encrypted SCEP p7 from the server thread = threading.Thread(target=os.system('python ./receive_p7.py ' + fileName + ' ' + str(fileSize))) thread.start() thread.join() p7 = fileName decryptMsg = 'scep.txt' # Decrypt the p7 to extract the SCEP instructions thread = threading.Thread( target=os.system('openssl smime -decrypt -inform pem -in ' + p7 + ' -inkey ' + privateKey + ' -out ' + decryptMsg)) thread.start() thread.join() print(p7 + ' successfully decrypted with ' + privateKey + '; server challenge stored as ' + decryptMsg + '\n') # Open scep.txt and retrieve SCEP instructions with open('scep.txt', 'r') as scep_info: info = scep_info.read() scep_info.close() CA_ip = info.split()[0] CA_port = info.split()[1] CAcert_hash = info.split()[2] # Connect to SCEP Device CA, request Device CA public certificate, authenticate CA public certificate thread = threading.Thread(target=os.system('python ./connectCA.py ' + CA_ip + ' ' + CA_port + ' ' + CAcert_hash)) thread.start() thread.join() # Create CSR using a new private key privateKey = CN + '.device.key' csr = CN + '.csr' thread = threading.Thread(target=os.system('openssl genrsa -out ' + privateKey + ' 2048')) thread.start() thread.join() print('Done.\n') print('Generating CA Certificate Signing Request...\n') thread = threading.Thread( target=os.system('openssl req -new -key ' + privateKey + ' -out ' + csr + ' -subj "/C=US/OU=USMC/O=U.S.GOVERNMENT/CN=' + CN + '/emailAddress=' + email + '" -addext "keyUsage=digitalSignature"')) thread.start() thread.join() print('Done.\n') # Connect to SCEP CA, send CSR, receive CA signed device certificate thread = threading.Thread(target=os.system('python ./client_csr.py ' + CA_ip + ' ' + CA_port + ' ' + csr + ' ' + CN)) thread.start() thread.join() # Second server p7 initiation message connection.sendall('OK\n') server_reply = connection.recv(1024) fileSize = int(server_reply.split(' ')[1]) fileName = server_reply.split(' ')[0] print('Server Response: ' + server_reply) connection.sendall('OK - Send\n') # Receive server challenge p7 thread = threading.Thread(target=os.system('python ./receive_p7.py ' + fileName + ' ' + str(fileSize))) thread.start() thread.join() decryptMsg = 'decrypted2.txt' # Decrypt the p7 to extract the server's challenge password privateKey = CN + '.device.key' thread = threading.Thread( target=os.system('openssl smime -decrypt -inform pem -in ' + fileName + ' -inkey ' + privateKey + ' -out ' + decryptMsg)) thread.start() thread.join() print(fileName + ' successfully decrypted with ' + privateKey + '; server challenge stored as ' + decryptMsg + '\n') # Create a signed p7 containing the encrypted decrypted challenge signedp7 = 'signed2.p7' pubCert = CN + '.device.crt' thread = threading.Thread( target=os.system('openssl smime -sign -nodetach -in ' + decryptMsg + ' -out ' + signedp7 + ' -outform pem -inkey ' + privateKey + ' -signer ' + pubCert)) thread.start() thread.join() print(signedp7 + ' containing ' + decryptMsg + ' successfuly encrypted and signed with ' + privateKey + '\n') # Check if server ready for file transfer print('Checking if server is ready for file transfer...') connection.sendall(signedp7 + '\n') server_reply = connection.recv(1024) print('Server Response: ' + server_reply) # Send the signed p7 thread = threading.Thread(target=os.system('python ./send_p7.py ' + signedp7)) thread.start() thread.join() # Check if server successfuly received p7 server_reply = connection.recv(1024) print('Server Response: ' + server_reply) end = time.time() elapsedTime = end - start # Final biometric verification fingerprint = raw_input( 'Authenticate your identity to complete the process: \n>Fingerprint: ') print('\nProcessing.....') connection.sendall(fingerprint + '\n') server_reply = connection.recv(1024) print('Server Response: ' + server_reply) print('+++++ ORION Device Enrollment Complete - Total Elapsed Time: ' + str(elapsedTime) + ' Seconds +++++\n') print('+++++ Device serial: ' + device_serial + ' is now credentialed to user EDIPI: ' + edipi + ' +++++\n') choice = raw_input( 'Press [Enter] to continue to expedited credentialing\n') while True: if choice == '': break choice = raw_input( 'Press Enter to continue to expedited credentialing\n') # Generate new PIV Auth, Signature, and Encryption Certificate generate_credentials(privateKey, CN, email)
# Create the CA Certificate cakey = createKeyPair(TYPE_RSA, 1024) careq = createCertRequest(cakey, CN='Certificate Authority') cacert = createCertificate(careq, (careq, cakey), serial, (0, 60 * 60 * 24 * 365 * 10)) # ten years cname = 'SickRage' pkey = createKeyPair(TYPE_RSA, 1024) req = createCertRequest(pkey, CN=cname) cert = createCertificate(req, (cacert, cakey), serial, (0, 60 * 60 * 24 * 365 * 10)) # ten years # Save the key and certificate to disk try: open(ssl_key, 'w').write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)) open(ssl_cert, 'w').write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) except: logger.log(u"Error creating SSL key and certificate", logger.ERROR) return False return True if __name__ == '__main__': import doctest doctest.testmod()
def check_rdp_socket(s, username, password, domain, hashes=None): try: from OpenSSL import SSL, crypto except: return "pyOpenSSL is not installed, can't continue" if hashes is not None: lmhash, nthash = hashes.split(':') lmhash = a2b_hex(lmhash) nthash = a2b_hex(nthash) else: lmhash = '' nthash = '' tpkt = TPKT() tpdu = TPDU() rdp_neg = RDP_NEG_REQ() rdp_neg['Type'] = TYPE_RDP_NEG_REQ rdp_neg['requestedProtocols'] = PROTOCOL_HYBRID | PROTOCOL_SSL tpdu['VariablePart'] = str(rdp_neg) tpdu['Code'] = TDPU_CONNECTION_REQUEST tpkt['TPDU'] = str(tpdu) s.setblocking(1) s.sendall(str(tpkt)) pkt = s.recv(8192) try: tpkt.fromString(pkt) tpdu.fromString(tpkt['TPDU']) cr_tpdu = CR_TPDU(tpdu['VariablePart']) if cr_tpdu['Type'] == TYPE_RDP_NEG_FAILURE: rdp_failure = RDP_NEG_FAILURE(tpdu['VariablePart']) rdp_failure.dump() return "Server doesn't support PROTOCOL_HYBRID, hence we can't use CredSSP to check credentials" else: rdp_neg.fromString(tpdu['VariablePart']) except struct_error: return False # Since we were accepted to talk PROTOCOL_HYBRID, below is its implementation # 1. The CredSSP client and CredSSP server first complete the TLS handshake, # as specified in [RFC2246]. After the handshake is complete, all subsequent # CredSSP Protocol messages are encrypted by the TLS channel. # The CredSSP Protocol does not extend the TLS wire protocol. As part of the TLS # handshake, the CredSSP server does not request the client's X.509 certificate # (thus far, the client is anonymous). Also, the CredSSP Protocol does not require # the client to have a commonly trusted certification authority root with the # CredSSP server. Thus, the CredSSP server MAY use, for example, # a self-signed X.509 certificate. # Switching to TLS now ctx = SSL.Context(SSL.TLSv1_METHOD) ctx.set_cipher_list('RC4') tls = SSL.Connection(ctx, s) tls.set_connect_state() tls.setblocking(1) tls.do_handshake() # If you want to use Python internal ssl, uncomment this and comment # the previous lines #tls = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_TLSv1, ciphers='RC4') # 2. Over the encrypted TLS channel, the SPNEGO handshake between the client # and server completes mutual authentication and establishes an encryption key # that is used by the SPNEGO confidentiality services, as specified in [RFC4178]. # All SPNEGO tokens as well as the underlying encryption algorithms are opaque to # the calling application (the CredSSP client and CredSSP server). # The wire protocol for SPNEGO is specified in [MS-SPNG]. # The SPNEGO tokens exchanged between the client and the server are encapsulated # in the negoTokens field of the TSRequest structure. Both the client and the # server use this structure as many times as necessary to complete the SPNEGO # exchange.<9> # # Note During this phase of the protocol, the OPTIONAL authInfo field is omitted # from the TSRequest structure by the client and server; the OPTIONAL pubKeyAuth # field is omitted by the client unless the client is sending the last SPNEGO token. # If the client is sending the last SPNEGO token, the TSRequest structure MUST have # both the negoToken and the pubKeyAuth fields filled in. # NTLMSSP stuff auth = ntlm.getNTLMSSPType1('', '', True, use_ntlmv2=True) ts_request = TSRequest() ts_request['NegoData'] = str(auth) tls.send(ts_request.getData()) buff = tls.recv(4096) try: ts_request.fromString(buff) except struct_error: return False # 3. The client encrypts the public key it received from the server (contained # in the X.509 certificate) in the TLS handshake from step 1, by using the # confidentiality support of SPNEGO. The public key that is encrypted is the # ASN.1-encoded SubjectPublicKey sub-field of SubjectPublicKeyInfo from the X.509 # certificate, as specified in [RFC3280] section 4.1. The encrypted key is # encapsulated in the pubKeyAuth field of the TSRequest structure and is sent over # the TLS channel to the server. # # Note During this phase of the protocol, the OPTIONAL authInfo field is omitted # from the TSRequest structure; the client MUST send its last SPNEGO token to the # server in the negoTokens field (see step 2) along with the encrypted public key # in the pubKeyAuth field. # Last SPNEGO token calculation #ntlmChallenge = ntlm.NTLMAuthChallenge(ts_request['NegoData']) type3, exportedSessionKey = ntlm.getNTLMSSPType3(auth, ts_request['NegoData'], username, password, domain, lmhash, nthash, use_ntlmv2=True) # Get server public key server_cert = tls.get_peer_certificate() pkey = server_cert.get_pubkey() dump = crypto.dump_privatekey(crypto.FILETYPE_ASN1, pkey) # Fix up due to PyOpenSSL lack for exporting public keys dump = dump[7:] dump = '\x30' + asn1encode(dump) cipher = SPNEGOCipher(type3['flags'], exportedSessionKey) signature, cripted_key = cipher.encrypt(dump) ts_request['NegoData'] = str(type3) ts_request['pubKeyAuth'] = str(signature) + cripted_key try: # Sending the Type 3 NTLM blob tls.send(ts_request.getData()) # The other end is waiting for the pubKeyAuth field, but looks like it's # not needed to check whether authentication worked. # If auth is unsuccessful, it throws an exception with the previous send(). # If auth is successful, the server waits for the pubKeyAuth and doesn't answer # anything. So, I'm sending garbage so the server returns an error. # Luckily, it's a different error so we can determine whether or not auth worked ;) buff = tls.recv(1024) except SSL.Error: # Likely communication error return False except Exception, e: return str(type(e)) + ': ' + str(e)
def write_privatekey(privatekey, path): open(path, "w").write(crypto.dump_privatekey(crypto.FILETYPE_PEM, privatekey))
"[*] Encrypted Socat - Developed by Rajeev KARUVATH - CSEC 742 Computer System Security" ) print("[*] Generating TLS certificate") rsa_key = crypto.PKey() rsa_key.generate_key(crypto.TYPE_RSA, 4096) pem_cert = crypto.X509() pem_cert.get_subject().C = "US" pem_cert.get_subject().ST = "New York" pem_cert.get_subject().L = "Rochester" pem_cert.get_subject().O = "Rochester Institute of Technology" pem_cert.get_subject().OU = "Department of Computing Security" pem_cert.get_subject().CN = "Rajeev KARUVATH" pem_cert.get_subject().emailAddress = "*****@*****.**" pem_cert.gmtime_adj_notBefore(0) pem_cert.gmtime_adj_notAfter(2 * 365 * 24 * 60 * 60) pem_cert.set_issuer(pem_cert.get_subject()) pem_cert.set_pubkey(rsa_key) pem_cert.sign(rsa_key, 'sha512') with open('socat.pem', "wt") as file: file.write( crypto.dump_certificate(crypto.FILETYPE_PEM, pem_cert).decode("utf-8")) file.write( crypto.dump_privatekey(crypto.FILETYPE_PEM, rsa_key).decode("utf-8")) print("[*] TLS Certificate Generated") socat_command = f"socat OPENSSL-LISTEN:{parsed_args.listen},cert=socat.pem,verify=0,fork {parsed_args.socat_args}" print(socat_command) os.system(socat_command) print("[*] Closing socat") os.remove("socat.pem") print("[*] Deleted TLS certificate")
def export_privatekey(buf): key = crypto.load_privatekey(crypto.FILETYPE_PEM, buf) return crypto.dump_privatekey(crypto.FILETYPE_PEM, key)
def __init__(self): self.pk = PKey() self.pk.generate_key(TYPE_RSA, 1024) self.private_key = self.strip_pri( dump_privatekey(FILETYPE_PEM, self.pk)) self.public_key = self.strip_pub(dump_publickey(FILETYPE_PEM, self.pk))
def create_public_key_pair(keyFile): k = crypto.PKey() k.generate_key(crypto.TYPE_RSA, KEY_SIZE) keyToByte = crypto.dump_privatekey(crypto.FILETYPE_PEM, k) write_to_file(keyToByte, keyFile) return k
def create_certificate(self, cert_info, request=False, valid_from=0, valid_to=315360000, sn=1, key_length=1024, hash_alg="sha256", write_to_file=False, cert_dir="", cipher_passphrase=None): """ Can create certificate requests, to be signed later by another certificate with the method create_cert_signed_certificate. If request is True. Can also create self signed root certificates if request is False. This is default behaviour. :param cert_info: Contains information about the certificate. Is a dictionary that must contain the keys: cn = Common name. This part must match the host being authenticated country_code = Two letter description of the country. state = State city = City organization = Organization, can be a company name. organization_unit = A unit at the organization, can be a department. Example: cert_info_ca = { "cn": "company.com", "country_code": "se", "state": "AC", "city": "Dorotea", "organization": "Company", "organization_unit": "Sales" } :param request: True if this is a request for certificate, that should be signed. False if this is a self signed certificate, root certificate. :param valid_from: When the certificate starts to be valid. Amount of seconds from when the certificate is generated. :param valid_to: How long the certificate will be valid from when it is generated. The value is in seconds. Default is 315360000 seconds, a.k.a 10 years. :param sn: Serial number for the certificate. Default is 1. :param key_length: Length of the key to be generated. Defaults to 1024. :param hash_alg: Hash algorithm to use for the key. Default is sha256. :param write_to_file: True if you want to write the certificate to a file. The method will then return a tuple with path to certificate file and path to key file. False if you want to get the result as strings. The method will then return a tuple with the certificate string and the key as string. WILL OVERWRITE ALL EXISTING FILES WITHOUT ASKING! :param cert_dir: Where to save the files if write_to_file is true. :param cipher_passphrase A dictionary with cipher and passphrase. Example: {"cipher": "blowfish", "passphrase": "qwerty"} :return: string representation of certificate, string representation of private key if write_to_file parameter is False otherwise path to certificate file, path to private key file """ cn = cert_info["cn"] c_f = None k_f = None if write_to_file: cert_file = "%s.crt" % cn key_file = "%s.key" % cn try: remove(cert_file) except: pass try: remove(key_file) except: pass c_f = join(cert_dir, cert_file) k_f = join(cert_dir, key_file) # create a key pair k = crypto.PKey() k.generate_key(crypto.TYPE_RSA, key_length) # create a self-signed cert cert = crypto.X509() if request: cert = crypto.X509Req() if (len(cert_info["country_code"]) != 2): raise WrongInput("Country code must be two letters!") cert.get_subject().C = cert_info["country_code"] cert.get_subject().ST = cert_info["state"] cert.get_subject().L = cert_info["city"] cert.get_subject().O = cert_info["organization"] cert.get_subject().OU = cert_info["organization_unit"] cert.get_subject().CN = cn if not request: cert.set_serial_number(sn) cert.gmtime_adj_notBefore(valid_from) #Valid before present time cert.gmtime_adj_notAfter(valid_to) #3 650 days cert.set_issuer(cert.get_subject()) cert.set_pubkey(k) cert.sign(k, hash_alg) filesCreated = False try: if request: tmp_cert = crypto.dump_certificate_request( crypto.FILETYPE_PEM, cert) else: tmp_cert = crypto.dump_certificate(crypto.FILETYPE_PEM, cert) tmp_key = None if cipher_passphrase is not None: tmp_key = crypto.dump_privatekey( crypto.FILETYPE_PEM, k, cipher_passphrase["cipher"], cipher_passphrase["passphrase"]) else: tmp_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, k) if write_to_file: fc = open(c_f, "wt") fk = open(k_f, "wt") if request: fc.write(tmp_cert) else: fc.write(tmp_cert) fk.write(tmp_key) filesCreated = True try: fc.close() except: pass try: fk.close() except: pass return c_f, k_f return tmp_cert, tmp_key except Exception as ex: raise CertificateError("Certificate cannot be generated.", ex)
def as_pem(self): return crypto.dump_privatekey(crypto.FILETYPE_PEM, self.key)
ca_cert.set_issuer(ca_subj) ca_cert.set_pubkey(ca_key) ca_cert.gmtime_adj_notBefore(0) ca_cert.gmtime_adj_notAfter(10 * 365 * 24 * 60 * 60) ca_cert.sign(ca_key, 'sha256') # Save certificate with open("certs_file/ca.crt", "wt") as f: f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, ca_cert)) # Save private key with open("certs_file/ca.key", "wt") as f: f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, ca_key)) ############### # Client Cert # ############### client_key = crypto.PKey() client_key.generate_key(crypto.TYPE_RSA, 2048) client_cert = crypto.X509() client_cert.set_version(2) client_cert.set_serial_number(random.randint(50000000, 100000000)) client_subj = client_cert.get_subject() client_subj.commonName = "Client"