Exemplo n.º 1
0
def gen_cert(outfile):
    k = crypto.PKey()
    k.generate_key(crypto.TYPE_RSA, 2048)

    c = crypto.X509()

    c.get_subject().C = "US"
    c.get_subject().ST = "Minnesota"
    c.get_subject().L = "Minnetonka"
    c.get_subject().O = "my company"
    c.get_subject().OU = "my organization"
    c.get_subject().CN = gethostname()
    c.set_serial_number(1000)
    c.gmtime_adj_notBefore(0)
    c.gmtime_adj_notAfter(10*365*24*60*60)
    c.set_issuer(c.get_subject())

    c.set_pubkey(k)
    c.sign(k, 'sha1')

    with open(outfile, 'w') as f:
        f.write(crypto.dump_certificate(1, c).decode('utf-8'))
        f.write(crypto.dump_privatekey(1, k).decode('utf-8'))

    cert_hash = sha256()
    cert_hash.update(crypto.dump_certificate(1, c))
    return cert_hash.hexdigest()
Exemplo n.º 2
0
 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
Exemplo n.º 3
0
def main():
  parser = argparse.ArgumentParser(description=__doc__)
  parser.add_argument('host')
  args = parser.parse_args()

  x509cert = client.get_host_certificate(args.host)
  print crypto.dump_certificate(crypto.FILETYPE_PEM, x509cert)
Exemplo n.º 4
0
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)
Exemplo n.º 5
0
 def cert(self, val):
     if self.cert_path:
         with open(self.cert_path, 'w') as cert_fh:
             cert_fh.write(crypto.dump_certificate(crypto.FILETYPE_PEM,
                                                   val))
     else:
         self._cert_val = crypto.dump_certificate(crypto.FILETYPE_PEM, val)
Exemplo n.º 6
0
    def _generate_ca(self):
        # Generate key
        self.key = PKey()
        self.key.generate_key(TYPE_RSA, 2048)

        # Generate certificate
        self.cert = X509()
        self.cert.set_version(3)
        self.cert.set_serial_number(1)
        self.cert.get_subject().CN = 'Namecoin .bit proxy'
        self.cert.gmtime_adj_notBefore(0)
        self.cert.gmtime_adj_notAfter(315360000)
        self.cert.set_issuer(self.cert.get_subject())
        self.cert.set_pubkey(self.key)
        self.cert.add_extensions([
            X509Extension("basicConstraints", True, "CA:TRUE, pathlen:0"),
            X509Extension("keyUsage", True, "keyCertSign, cRLSign"),
            X509Extension("subjectKeyIdentifier", False, "hash", subject=self.cert),
            ])
        self.cert.sign(self.key, "sha256")

        with open(self.ca_file, 'wb+') as f:
            f.write(dump_privatekey(self.filetype, self.key))
            f.write(dump_certificate(self.filetype, self.cert))

        # export for Windows
        with open("ca.crt", 'wb+') as f:
            f.write(dump_certificate(self.filetype, self.cert))
Exemplo n.º 7
0
	def make_cert(self, pem_data):
		old_cert = crypto.load_certificate(crypto.FILETYPE_PEM, pem_data)
		common_name = old_cert.get_subject().CN	
		if os.path.isfile(os.path.join(self._files_dir, common_name+'.pem')):
			certfile = os.path.join(self._files_dir, common_name+'.pem')
			keyfile = os.path.join(self._files_dir, common_name+'.key')
			return certfile, keyfile
		pkey = crypto.PKey()
		pkey.generate_key(crypto.TYPE_RSA, 2048)
		new_cert = crypto.X509()
		new_cert.gmtime_adj_notBefore(0)
		new_cert.gmtime_adj_notAfter(10*365*24*60*60)
		#set same subject of old cert
		new_cert.set_subject(old_cert.get_subject())
		#look for and set SNA of old cert
		for i in range(old_cert.get_extension_count()):
			ext = old_cert.get_extension(i)
			if ext.get_short_name() == 'subjectAltName':
				new_cert.add_extensions([ext])
		new_cert.set_issuer(self.issuer)
		self._count_lock.acquire()
		new_cert.set_serial_number(self._count)
		self._count += 1
		self._count_lock.release()		
		new_cert.set_pubkey(pkey)
		new_cert.sign(self.root_key, 'sha1')
		certfile = os.path.join( self._files_dir, common_name+'.pem',)
		keyfile = os.path.join( self._files_dir, common_name+'.key')		
		#write key and cert
		with open(certfile, "wt") as cf: cf.write(crypto.dump_certificate(crypto.FILETYPE_PEM, new_cert))
		with open(keyfile, "wt") as kf: kf.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
		#append root to cert chain
		with open(certfile, 'at') as ccf: ccf.write(crypto.dump_certificate(crypto.FILETYPE_PEM, self.root_cert)) 		
		return certfile, keyfile
Exemplo n.º 8
0
    def _gen_ca(self,again=False):
        # Generate key
        #如果证书存在而且不是强制生成,直接返回证书信息
        if os.path.exists(self.ca_file_path) and os.path.exists(self.cert_file_path) and not again:
            self._read_ca(self.ca_file_path) #读取证书信息
            return
        self.key = PKey()
        self.key.generate_key(TYPE_RSA, 2048)
        # Generate certificate
        self.cert = X509()
        self.cert.set_version(2)
        self.cert.set_serial_number(1)
        self.cert.get_subject().CN = 'baseproxy'
        self.cert.gmtime_adj_notBefore(0)
        self.cert.gmtime_adj_notAfter(315360000)
        self.cert.set_issuer(self.cert.get_subject())
        self.cert.set_pubkey(self.key)
        self.cert.add_extensions([
            X509Extension(b"basicConstraints", True, b"CA:TRUE, pathlen:0"),
            X509Extension(b"keyUsage", True, b"keyCertSign, cRLSign"),
            X509Extension(b"subjectKeyIdentifier", False, b"hash", subject=self.cert),
        ])
        self.cert.sign(self.key, "sha256")
        with open(self.ca_file_path, 'wb+') as f:
            f.write(dump_privatekey(FILETYPE_PEM, self.key))
            f.write(dump_certificate(FILETYPE_PEM, self.cert))

        with open(self.cert_file_path, 'wb+') as f:
            f.write(dump_certificate(FILETYPE_PEM, self.cert))
Exemplo n.º 9
0
    def update(self, param):
        """
        This method is called during the initialization process.
        :param param: parameters from the token init
        :type param: dict
        :return: None
        """
        TokenClass.update(self, param)

        request = getParam(param, "request", optional)
        spkac = getParam(param, "spkac", optional)
        certificate = getParam(param, "certificate", optional)
        generate = getParam(param, "genkey", optional)
        if request or generate:
            # If we do not upload a user certificate, then we need a CA do
            # sign the uploaded request or generated certificate.
            ca = getParam(param, "ca", required)
            self.add_tokeninfo("CA", ca)
            cacon = get_caconnector_object(ca)
        if request:
            # During the initialization process, we need to create the
            # certificate
            x509object = cacon.sign_request(request,
                                            options={"spkac": spkac})
            certificate = crypto.dump_certificate(crypto.FILETYPE_PEM,
                                                  x509object)
        elif generate:
            # Create the certificate on behalf of another user.
            # Now we need to create the key pair,
            # the request
            # and the certificate
            # We need the user for whom the certificate should be created
            user = get_user_from_param(param, optionalOrRequired=required)

            keysize = getParam(param, "keysize", optional, 2048)
            key = crypto.PKey()
            key.generate_key(crypto.TYPE_RSA, keysize)
            req = crypto.X509Req()
            req.get_subject().CN = user.login
            # Add email to subject
            if user.info.get("email"):
                req.get_subject().emailAddress = user.info.get("email")
            req.get_subject().organizationalUnitName = user.realm
            # TODO: Add Country, Organization, Email
            # req.get_subject().countryName = 'xxx'
            # req.get_subject().stateOrProvinceName = 'xxx'
            # req.get_subject().localityName = 'xxx'
            # req.get_subject().organizationName = 'xxx'
            req.set_pubkey(key)
            req.sign(key, "sha256")
            x509object = cacon.sign_request(crypto.dump_certificate_request(
                crypto.FILETYPE_PEM, req))
            certificate = crypto.dump_certificate(crypto.FILETYPE_PEM,
                                                  x509object)
            # Save the private key to the encrypted key field of the token
            s = crypto.dump_privatekey(crypto.FILETYPE_PEM, key)
            self.add_tokeninfo("privatekey", s, value_type="password")

        if certificate:
            self.add_tokeninfo("certificate", certificate)
Exemplo n.º 10
0
    def composing(self, composition, context):
        'Will copy local MSP info over at this point for each peer node'

        directory = getDirectory(context)

        for peerService in self.getPeerList(composition):
            localMspConfigPath = self.getLocalMspConfigPath(composition, peerService)
            self._createLocalMspConfigDirs(localMspConfigPath)
            # Loop through directory and place Peer Organization Certs into cacerts folder
            for peerOrg in [org for orgName,org in directory.organizations.items() if Network.Peer in org.networks]:
                with open("{0}/cacerts/{1}.pem".format(localMspConfigPath, peerOrg.name), "w") as f:
                    f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, peerOrg.getSelfSignedCert()))

            # Loop through directory and place Peer Organization Certs into admincerts folder
            #TODO: revisit this, ASO recommended for now
            for peerOrg in [org for orgName,org in directory.organizations.items() if Network.Peer in org.networks]:
                with open("{0}/admincerts/{1}.pem".format(localMspConfigPath, peerOrg.name), "w") as f:
                    f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, peerOrg.getSelfSignedCert()))

            # Find the peer signer Tuple for this peer and add to signcerts folder
            for pnt, cert in [(peerNodeTuple,cert) for peerNodeTuple,cert in directory.ordererAdminTuples.items() if peerService in peerNodeTuple.user and "signer" in peerNodeTuple.user.lower()]:
                # Put the PEM file in the signcerts folder
                with open("{0}/signcerts/{1}.pem".format(localMspConfigPath, pnt.user), "w") as f:
                    f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
                # Put the associated private key into the keystore folder
                user = directory.getUser(pnt.user, shouldCreate=False)
                with open("{0}/keystore/{1}.pem".format(localMspConfigPath, pnt.user), "w") as f:
                    f.write(user.ecdsaSigningKey.to_pem())
Exemplo n.º 11
0
    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))
Exemplo n.º 12
0
def createSignature(hash, signingCertificatePkcs12, signingCertificatePassword):
    # see also in AM: src/crypto-lib/signature.cpp / Signature::create()

    s = SMIME.SMIME()

    # M2Crypto has no support for PKCS#12, so we have to use pyopenssl here
    # to load the .p12. Since the internal structures are incompatible, we
    # have to export from pyopenssl and import to M2Crypto via PEM BIOs.
    pkcs12 = load_pkcs12(signingCertificatePkcs12, signingCertificatePassword)
    signKey = BIO.MemoryBuffer(dump_privatekey(FILETYPE_PEM, pkcs12.get_privatekey()))
    signCert = BIO.MemoryBuffer(dump_certificate(FILETYPE_PEM, pkcs12.get_certificate()))
    caCerts = X509.X509_Stack()
    if pkcs12.get_ca_certificates():
        for cert in pkcs12.get_ca_certificates():
            bio = BIO.MemoryBuffer(dump_certificate(FILETYPE_PEM, cert))
            caCerts.push(X509.load_cert_bio(bio, X509.FORMAT_PEM))

    bioHash = BIO.MemoryBuffer(hash)

    s.load_key_bio(signKey, signCert)
    s.set_x509_stack(caCerts)
    signature = s.sign(bioHash, SMIME.PKCS7_DETACHED + SMIME.PKCS7_BINARY)
    bioSignature = BIO.MemoryBuffer()
    signature.write(bioSignature)

    data = bioSignature.read_all()
    return data
Exemplo n.º 13
0
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 savePEM(self, path, chain=True, root=False):
     text = crypto.dump_certificate(crypto.FILETYPE_PEM, self.x509)
     if chain:
         parent = self.parent
         while parent if root else parent.parent:
             text += crypto.dump_certificate(crypto.FILETYPE_PEM, parent.cacert.x509)
             parent = parent.parent
     write(path, text)
     return self
Exemplo n.º 15
0
def parse(pkt, vrb, cert_loc, revoke):
	# set some globals
	global ssl_location
	global verbose
	global revocation
	verbose = vrb
	revocation = revoke
	ssl_location = cert_loc

	cert = ssl.get_server_certificate((pkt[IP].src, 443))
	x509 = crypto.load_certificate(crypto.FILETYPE_PEM, cert)
	# if we're not dumping to console, validate it immediately
	if not verbose:
		return validate(x509)

	print "[!] Getting SSL certificate..."
	print "[+] SSL certificate from {0}:{1} -> {2}:{3}".format(pkt[IP].src, pkt[TCP].sport, pkt[IP].dst, pkt[TCP].dport)


	# issuer info
	issuer = x509.get_issuer().get_components()
	print "[!] Issuer"
	for k, v in dict(issuer).iteritems():
		print "[+]\t{0}:\t{1}".format(k,v)
	print "[+]\tHash:\t",hashlib.md5(x509.get_issuer().der()).hexdigest()

	# subject info
	subject = x509.get_subject().get_components()
	print "[!] Subject"
	for k, v in dict(subject).iteritems():
		print"[+]\t{0}:\t{1}".format(k,v)
	print "[+]\tHash:\t",hashlib.md5(x509.get_subject().der()).hexdigest()
	
	# public key info
	print "[!] Public Key"
	print "[+]\tBits:\t", x509.get_pubkey().bits()
	print "[+]\tType:\t", x509.get_pubkey().type()

	# misc
	print "[+] Version:\t",x509.get_version()
	print "[+] Serial:\t",x509.get_serial_number()
	before = datetime.datetime.strptime(x509.get_notBefore(), "%Y%m%d%H%M%SZ")
	after  = datetime.datetime.strptime(x509.get_notAfter(), "%Y%m%d%H%M%SZ")
	print "[+] Valid:\t{0} - {1}".format(before.strftime('%B %d, %Y'), after.strftime('%B %d, %Y'))
	print "[+] Algorithm:\t",x509.get_signature_algorithm()

	# extensions
	print "[!] x509v3 Extensions:"
	for i in range(1,x509.get_extension_count()):
		ext = x509.get_extension(i)
		print "[+] Extension: ", ext.get_short_name()
		print "\t",str(ext).replace('\n', ', ')

	print "[!] Certificate Dump:"
	print crypto.dump_certificate(crypto.FILETYPE_PEM, x509)
	
	return validate(x509)
Exemplo n.º 16
0
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)
Exemplo n.º 17
0
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
Exemplo n.º 18
0
    def test_getCertsFromCell(self):
        lc = test_cert_der
        link_cert = CertsCellPayloadItem(LINK_CERT_TYPE, len(lc), lc)
        ic = test_cert_der
        id_cert = CertsCellPayloadItem(ID_CERT_TYPE, len(ic), ic)

        cell = CertsCell.make(0, [link_cert, id_cert])

        res1 = crypto.load_certificate(crypto.FILETYPE_ASN1, lc)
        res2 = crypto.load_certificate(crypto.FILETYPE_ASN1, ic)

        l, i = connectionbuildtask._getCertsFromCell(cell)

        self.assertEqual(crypto.dump_certificate(crypto.FILETYPE_ASN1, l), lc)
        self.assertEqual(crypto.dump_certificate(crypto.FILETYPE_ASN1, i), ic)
Exemplo n.º 19
0
Arquivo: certs.py Projeto: Ivoz/pipa
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!')
Exemplo n.º 20
0
    def issue_certificate_request(self, order_id, order_meta, plugin_meta,
                                  barbican_meta_dto):
        if barbican_meta_dto.generated_csr is not None:
            encoded_csr = barbican_meta_dto.generated_csr
        else:
            try:
                encoded_csr = base64.b64decode(order_meta['request_data'])
            except KeyError:
                return cert_manager.ResultDTO(
                    cert_manager.CertificateStatus.CLIENT_DATA_ISSUE_SEEN,
                    status_message=u._("No request_data specified"))
        csr = crypto.load_certificate_request(crypto.FILETYPE_PEM, encoded_csr)

        ca_id = barbican_meta_dto.plugin_ca_id
        if ca_id:
            ca = self.cas.get(ca_id)
            if ca is None:
                raise cert_manager.CertificateGeneralException(
                    "Invalid ca_id passed into snake oil plugin:" + ca_id)
        else:
            ca = self.ca

        cert_mgr = CertManager(ca)
        cert = cert_mgr.make_certificate(csr)
        cert_enc = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)

        return cert_manager.ResultDTO(
            cert_manager.CertificateStatus.CERTIFICATE_GENERATED,
            certificate=base64.b64encode(cert_enc),
            intermediates=base64.b64encode(ca.pkcs7))
Exemplo n.º 21
0
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 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))
Exemplo n.º 23
0
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)
Exemplo n.º 24
0
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
Exemplo n.º 25
0
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
Exemplo n.º 26
0
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
Exemplo n.º 27
0
def createInvokeProposalForBDD(context, ccSpec, chainID, signersCert, Mspid, type):
    import binascii

    "Returns a deployment proposal of chaincode type"
    lc_chaincode_invocation_spec = chaincode_pb2.ChaincodeInvocationSpec(chaincode_spec = ccSpec)

    # Create
    ccHdrExt = proposal_pb2.ChaincodeHeaderExtension(chaincode_id=ccSpec.chaincode_id)

    ccProposalPayload = proposal_pb2.ChaincodeProposalPayload(input=lc_chaincode_invocation_spec.SerializeToString())

    bootstrapHelper = ContextHelper.GetHelper(context=context).getBootrapHelper(chainId=chainID)

    serializedIdentity = identities_pb2.SerializedIdentity(Mspid=Mspid, IdBytes=crypto.dump_certificate(crypto.FILETYPE_PEM, signersCert))

    nonce = bootstrap_util.BootstrapHelper.getNonce()

    sigHdr = bootstrapHelper.makeSignatureHeader(serializedIdentity.SerializeToString(), nonce)
    
    # Calculate the transaction ID
    tx_id = binascii.hexlify(bootstrap_util.computeCryptoHash(nonce + serializedIdentity.SerializeToString()))

    chainHdr = bootstrapHelper.makeChainHeader(type=common_dot_common_pb2.HeaderType.Value(type),
                                               txID=tx_id, extension=ccHdrExt.SerializeToString())

    header = common_dot_common_pb2.Header(channel_header=chainHdr.SerializeToString(), signature_header=sigHdr.SerializeToString())

    # make proposal
    proposal = proposal_pb2.Proposal(header=header.SerializeToString(), payload=ccProposalPayload.SerializeToString())


    return proposal
Exemplo n.º 28
0
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
Exemplo n.º 29
0
    def create_keypair(self):
        LOG.debug('Generating Snakeoil CA')
        key = crypto.PKey()
        key.generate_key(crypto.TYPE_RSA, self.key_size)

        cert = crypto.X509()
        cert.set_version(self.x509_version)
        cert.set_serial_number(self.serial)
        subject = cert.get_subject()
        set_subject_X509Name(subject, self.subject_dn)
        cert.set_subject(subject)
        cert.gmtime_adj_notBefore(0)
        cert.gmtime_adj_notAfter(self.expiry_days)
        cert.set_issuer(set_subject_X509Name(
            cert.get_issuer(), self.signing_dn))
        cert.set_pubkey(key)
        cert.add_extensions([
            crypto.X509Extension(b"basicConstraints", True,
                                 b"CA:TRUE, pathlen:5"),
        ])
        if not self.signing_key:
            self.signing_key = key  # self-signed

        cert.sign(self.signing_key, 'sha256')

        LOG.debug('Snakeoil CA cert/key generated')

        chain = ""
        if self.parent_chain_path:
            with open(self.parent_chain_path) as fh:
                chain = fh.read()
        chain += crypto.dump_certificate(crypto.FILETYPE_PEM, cert)

        pkcs7 = self._generate_pkcs7(chain)
        return cert, key, chain, pkcs7
Exemplo n.º 30
0
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()
Exemplo n.º 31
0
def writeout_cert(filename, item, type=crypto.FILETYPE_PEM):
    with open(filename, "w") as f:
        f.write(crypto.dump_certificate(type, item))
Exemplo n.º 32
0
    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
Exemplo n.º 33
0
    def __ca_sign_csr(self, data, schema_name):
        verrors = ValidationErrors()

        ca_data = self.middleware.call_sync('certificateauthority.query',
                                            ([('id', '=', data['ca_id'])]))
        csr_cert_data = self.middleware.call_sync(
            'certificate.query', [('id', '=', data['csr_cert_id'])])

        if not ca_data:
            verrors.add(
                f'{schema_name}.ca_id',
                f'No Certificate Authority found for id {data["ca_id"]}')
        else:
            ca_data = ca_data[0]
            if not ca_data.get('privatekey'):
                verrors.add(
                    f'{schema_name}.ca_id',
                    'Please use a CA which has a private key assigned')

        if not csr_cert_data:
            verrors.add(f'{schema_name}.csr_cert_id',
                        f'No Certificate found for id {data["csr_cert_id"]}')
        else:
            csr_cert_data = csr_cert_data[0]
            if not csr_cert_data.get('CSR'):
                verrors.add(f'{schema_name}.csr_cert_id',
                            'No CSR has been filed by this certificate')
            else:
                try:
                    csr = crypto.load_certificate_request(
                        crypto.FILETYPE_PEM, csr_cert_data['CSR'])
                except crypto.Error:
                    verrors.add(f'{schema_name}.csr_cert_id', 'CSR not valid')

        if verrors:
            raise verrors

        cert_info = crypto.load_certificate(crypto.FILETYPE_PEM,
                                            ca_data['certificate'])
        PKey = load_private_key(ca_data['privatekey'])

        serial = self.middleware.call_sync(
            'certificateauthority.get_serial_for_certificate', ca_data['id'])

        cert = crypto.X509()
        cert.set_serial_number(serial)
        cert.gmtime_adj_notBefore(0)
        cert.gmtime_adj_notAfter(86400 * 365 * 10)
        cert.set_issuer(cert_info.get_subject())
        cert.set_subject(csr.get_subject())
        cert.set_pubkey(csr.get_pubkey())
        cert.sign(PKey, ca_data['digest_algorithm'])

        new_cert = crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode()

        new_csr = {
            'type': CERT_TYPE_INTERNAL,
            'name': data['name'],
            'certificate': new_cert,
            'privatekey': csr_cert_data['privatekey'],
            'create_type': 'CERTIFICATE_CREATE',
            'signedby': ca_data[
                'id']  # Is this the right step ? If a CA signs a CSR, should it be the signedby
        }  # entity for that certificate

        new_csr_dict = self.middleware.call_sync('certificate.create', new_csr)

        return new_csr_dict
Exemplo n.º 34
0
 def _sign_file(cert, password, request):
     min = 1
     max = 99999
     signature_id = 'Signature%05d' % random.randint(min, max)
     signed_properties_id = signature_id + '-SignedProperties%05d' \
                                           % random.randint(min, max)
     key_info_id = 'KeyInfo%05d' % random.randint(min, max)
     reference_id = 'Reference%05d' % random.randint(min, max)
     object_id = 'Object%05d' % random.randint(min, max)
     etsi = 'http://uri.etsi.org/01903/v1.3.2#'
     sig_policy_identifier = 'http://www.facturae.es/' \
                             'politica_de_firma_formato_facturae/' \
                             'politica_de_firma_formato_facturae_v3_1' \
                             '.pdf'
     sig_policy_hash_value = 'Ohixl6upD6av8N7pEvDABhEL6hM='
     root = etree.fromstring(request)
     sign = xmlsig.template.create(
         c14n_method=xmlsig.constants.TransformInclC14N,
         sign_method=xmlsig.constants.TransformRsaSha1,
         name=signature_id,
         ns="ds")
     key_info = xmlsig.template.ensure_key_info(sign, name=key_info_id)
     x509_data = xmlsig.template.add_x509_data(key_info)
     xmlsig.template.x509_data_add_certificate(x509_data)
     xmlsig.template.add_key_value(key_info)
     certificate = crypto.load_pkcs12(base64.b64decode(cert), password)
     xmlsig.template.add_reference(
         sign,
         xmlsig.constants.TransformSha1,
         uri='#' + signed_properties_id,
         uri_type='http://uri.etsi.org/01903#SignedProperties')
     xmlsig.template.add_reference(sign,
                                   xmlsig.constants.TransformSha1,
                                   uri='#' + key_info_id)
     ref = xmlsig.template.add_reference(sign,
                                         xmlsig.constants.TransformSha1,
                                         name=reference_id,
                                         uri="")
     xmlsig.template.add_transform(ref,
                                   xmlsig.constants.TransformEnveloped)
     object_node = etree.SubElement(
         sign,
         etree.QName(xmlsig.constants.DSigNs, 'Object'),
         nsmap={'etsi': etsi},
         attrib={xmlsig.constants.ID_ATTR: object_id})
     qualifying_properties = etree.SubElement(
         object_node,
         etree.QName(etsi, 'QualifyingProperties'),
         attrib={'Target': '#' + signature_id})
     signed_properties = etree.SubElement(
         qualifying_properties,
         etree.QName(etsi, 'SignedProperties'),
         attrib={xmlsig.constants.ID_ATTR: signed_properties_id})
     signed_signature_properties = etree.SubElement(
         signed_properties,
         etree.QName(etsi, 'SignedSignatureProperties'))
     now = datetime.now().replace(microsecond=0, tzinfo=pytz.utc)
     etree.SubElement(signed_signature_properties,
                      etree.QName(
                          etsi, 'SigningTime')).text = now.isoformat()
     signing_certificate = etree.SubElement(
         signed_signature_properties,
         etree.QName(etsi, 'SigningCertificate'))
     signing_certificate_cert = etree.SubElement(
         signing_certificate, etree.QName(etsi, 'Cert'))
     cert_digest = etree.SubElement(signing_certificate_cert,
                                    etree.QName(etsi, 'CertDigest'))
     etree.SubElement(
         cert_digest,
         etree.QName(xmlsig.constants.DSigNs, 'DigestMethod'),
         attrib={'Algorithm': 'http://www.w3.org/2000/09/xmldsig#sha1'})
     hash_cert = hashlib.sha1(
         crypto.dump_certificate(crypto.FILETYPE_ASN1,
                                 certificate.get_certificate()))
     etree.SubElement(
         cert_digest, etree.QName(
             xmlsig.constants.DSigNs,
             'DigestValue')).text = base64.b64encode(hash_cert.digest())
     issuer_serial = etree.SubElement(signing_certificate_cert,
                                      etree.QName(etsi, 'IssuerSerial'))
     etree.SubElement(
         issuer_serial,
         etree.QName(xmlsig.constants.DSigNs, 'X509IssuerName')
     ).text = xmlsig.utils.get_rdns_name(
         certificate.get_certificate().to_cryptography().issuer.rdns)
     etree.SubElement(
         issuer_serial,
         etree.QName(
             xmlsig.constants.DSigNs, 'X509SerialNumber')).text = str(
                 certificate.get_certificate().get_serial_number())
     signature_policy_identifier = etree.SubElement(
         signed_signature_properties,
         etree.QName(etsi, 'SignaturePolicyIdentifier'))
     signature_policy_id = etree.SubElement(
         signature_policy_identifier,
         etree.QName(etsi, 'SignaturePolicyId'))
     sig_policy_id = etree.SubElement(signature_policy_id,
                                      etree.QName(etsi, 'SigPolicyId'))
     etree.SubElement(sig_policy_id, etree.QName(
         etsi, 'Identifier')).text = sig_policy_identifier
     etree.SubElement(sig_policy_id, etree.QName(
         etsi, 'Description')).text = "Política de Firma FacturaE v3.1"
     sig_policy_hash = etree.SubElement(
         signature_policy_id, etree.QName(etsi, 'SigPolicyHash'))
     etree.SubElement(
         sig_policy_hash,
         etree.QName(xmlsig.constants.DSigNs, 'DigestMethod'),
         attrib={'Algorithm': 'http://www.w3.org/2000/09/xmldsig#sha1'})
     hash_value = sig_policy_hash_value
     etree.SubElement(
         sig_policy_hash,
         etree.QName(xmlsig.constants.DSigNs,
                     'DigestValue')).text = hash_value
     signer_role = etree.SubElement(signed_signature_properties,
                                    etree.QName(etsi, 'SignerRole'))
     claimed_roles = etree.SubElement(signer_role,
                                      etree.QName(etsi, 'ClaimedRoles'))
     etree.SubElement(claimed_roles,
                      etree.QName(etsi,
                                  'ClaimedRole')).text = 'supplier'
     signed_data_object_properties = etree.SubElement(
         signed_properties,
         etree.QName(etsi, 'SignedDataObjectProperties'))
     data_object_format = etree.SubElement(
         signed_data_object_properties,
         etree.QName(etsi, 'DataObjectFormat'),
         attrib={'ObjectReference': '#' + reference_id})
     etree.SubElement(data_object_format,
                      etree.QName(etsi, 'Description')).text = 'Factura'
     etree.SubElement(data_object_format,
                      etree.QName(etsi, 'MimeType')).text = 'text/xml'
     ctx = xmlsig.SignatureContext()
     key = crypto.load_pkcs12(base64.b64decode(cert), password)
     ctx.x509 = key.get_certificate().to_cryptography()
     ctx.public_key = ctx.x509.public_key()
     ctx.private_key = key.get_privatekey().to_cryptography_key()
     root.append(sign)
     ctx.sign(sign)
     return etree.tostring(root, xml_declaration=True, encoding='UTF-8')
Exemplo n.º 35
0
 def dump(self, format=crypto.FILETYPE_ASN1):
     return crypto.dump_certificate(format, self.original)
Exemplo n.º 36
0
if __name__ == "__main__":
    try:
        config_ca, config_cert = certerator_config()
    
        # Firstly, sort out the CA file
        if os.path.isfile(config_ca['cert_filename']) and os.path.isfile(config_ca['cert_key']):
            sys.stdout.write("Reusing "+config_ca['cert_filename']+" as the CA\n")
            ca_cert = crypto.load_certificate(crypto.FILETYPE_PEM, file(config_ca['cert_filename']).read())
            ca_key = crypto.load_privatekey(crypto.FILETYPE_PEM, file(config_ca['cert_key']).read())
            sys.stdout.write(" SHA1 CA Fingerprint: "+ca_cert.digest('sha1')+"\n")
        else:
            sys.stdout.write("Generating new CA...")
            sys.stdout.flush()
            ca_cert, ca_key = generate_ca(config_ca)
            sys.stdout.write("..done\n")
            open(config_ca['cert_filename'], "w").write(crypto.dump_certificate(crypto.FILETYPE_PEM, ca_cert))
            open(config_ca['cert_der'], "wb").write(crypto.dump_certificate(crypto.FILETYPE_ASN1, ca_cert))
            open(config_ca['cert_key'], "w").write(crypto.dump_privatekey(crypto.FILETYPE_PEM, ca_key))
            open(config_ca['cert_p12'], "wb").write(make_ca_p12(ca_cert,ca_key))
            sys.stdout.write(" Written PEM CA certificate to "+config_ca['cert_filename']+"\n")
            sys.stdout.write(" Written DER CA certificate to "+config_ca['cert_der']+"\n")
            sys.stdout.write(" Written CA private key to "+config_ca['cert_key']+"\n")
            sys.stdout.write(" Written CA PKCS12 (private key and certificate) to "+config_ca['cert_p12']+"\n")
            sys.stdout.write(" SHA1 CA Fingerprint: "+ca_cert.digest('sha1')+"\n")
            
        # Now sort out the signing certificate
        if os.path.isfile(config_cert['cert_filename']) and os.path.isfile(config_cert['cert_key']):
            sys.stdout.write("Reusing "+config_cert['cert_filename']+" as the code signing certificate\n")
            cert_cert = crypto.load_certificate(crypto.FILETYPE_PEM, file(config_cert['cert_filename']).read())
            cert_key = crypto.load_privatekey(crypto.FILETYPE_PEM, file(config_cert['cert_key']).read())
            sys.stdout.write(" SHA1 Cert Fingerprint: "+cert_cert.digest('sha1')+"\n")
Exemplo n.º 37
0
def write_certificate_chain(chain, path):
    with open(path, "w") as f:
        for certificate in chain:
            f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, certificate))
        f.close()
Exemplo n.º 38
0
def write_certificate(certificate, path):
    open(path, "w").write(
        crypto.dump_certificate(crypto.FILETYPE_PEM, certificate)
    )
Exemplo n.º 39
0
 def _test_openssl(self):
     '''
     Run a test with openssl to detect any MITM proxies
     '''
     if not self.cert_verify:
         logger.info('cert_verify set to False, skipping SSL check...')
         return False
     success = True
     hostname = urlparse(self.base_url).netloc.split(':')
     sock = socket.socket()
     sock.setblocking(1)
     if self.proxies:
         connect_str = 'CONNECT {0}:443 HTTP/1.0\r\n'.format(hostname[0])
         if self.proxy_auth:
             connect_str += 'Proxy-Authorization: {0}\r\n'.format(
                 self.proxy_auth)
         connect_str += '\r\n'
         proxy = urlparse(self.proxies['https']).netloc.split(':')
         try:
             sock.connect((proxy[0], int(proxy[1])))
         except Exception as e:
             logger.debug(e)
             logger.error(
                 'Failed to connect to proxy %s. Connection refused.',
                 self.proxies['https'])
             return False
         sock.send(connect_str.encode('utf-8'))
         res = sock.recv(4096)
         if u'200 connection established' not in res.decode(
                 'utf-8').lower():
             logger.error('Failed to connect to %s.', self.base_url)
             logger.error('HTTP message:\n%s', res)
             return False
     else:
         try:
             sock.connect((hostname[0], 443))
         except socket.gaierror as e:
             logger.error(
                 'Error: Failed to connect to %s. Invalid hostname.',
                 self.base_url)
             logger.error(e)
             return False
     ctx = SSL.Context(SSL.TLSv1_METHOD)
     if type(self.cert_verify) is not bool:
         if os.path.isfile(self.cert_verify):
             ctx.load_verify_locations(self.cert_verify, None)
         else:
             logger.error('Error: Invalid cert path: %s', self.cert_verify)
             return False
     ctx.set_verify(SSL.VERIFY_PEER, self._verify_check)
     ssl_conn = SSL.Connection(ctx, sock)
     ssl_conn.set_connect_state()
     try:
         # output from verify generated here
         ssl_conn.do_handshake()
         # print cert chain
         certs = self.cert_chain[1]
         # put them in the right order
         certs.reverse()
         logger.debug('---\nCertificate chain')
         for depth, c in enumerate(certs):
             logger.debug(
                 self._generate_cert_str(c.get_subject(),
                                         u'{0} s :/'.format(depth)))
             logger.debug(self._generate_cert_str(c.get_issuer(),
                                                  u'  i :/'))
         # print server cert
         server_cert = ssl_conn.get_peer_certificate()
         logger.debug('---\nServer certificate')
         logger.debug(
             crypto.dump_certificate(crypto.FILETYPE_PEM, server_cert))
         logger.debug(
             self._generate_cert_str(server_cert.get_subject(),
                                     u'subject=/'))
         logger.debug(
             self._generate_cert_str(server_cert.get_issuer(), u'issuer=/'))
         logger.debug('---')
     except SSL.Error as e:
         logger.debug('SSL error: %s', e)
         success = False
         logger.error('Certificate chain test failed!')
     ssl_conn.shutdown()
     ssl_conn.close()
     if self.cert_chain[0]:
         logger.error('Certificate chain test failed!  Self '
                      'signed certificate detected in chain')
     return success and not self.cert_chain[0]
Exemplo n.º 40
0
if tornado.options.options.generate_certs:
    from OpenSSL import crypto
    ca_pk = crypto.PKey()
    ca_pk.generate_key(crypto.TYPE_RSA, 2048)
    ca_cert = crypto.X509()
    ca_cert.get_subject().CN = 'butterfly ca'
    ca_cert.set_serial_number(100)
    ca_cert.gmtime_adj_notBefore(0)  # From now
    ca_cert.gmtime_adj_notAfter(315360000)  # to 10y
    ca_cert.set_issuer(ca_cert.get_subject())  # Self signed
    ca_cert.set_pubkey(ca_pk)
    ca_cert.sign(ca_pk, 'sha1')

    with open(ca, "wb") as cf:
        cf.write(crypto.dump_certificate(crypto.FILETYPE_PEM, ca_cert))
    with open(ca_key, "wb") as cf:
        cf.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, ca_pk))

    server_pk = crypto.PKey()
    server_pk.generate_key(crypto.TYPE_RSA, 2048)
    server_cert = crypto.X509()
    server_cert.get_subject().CN = tornado.options.options.host
    server_cert.set_serial_number(200)
    server_cert.gmtime_adj_notBefore(0)  # From now
    server_cert.gmtime_adj_notAfter(315360000)  # to 10y
    server_cert.set_issuer(ca_cert.get_subject())  # Signed by ca
    server_cert.set_pubkey(server_pk)
    server_cert.sign(ca_pk, 'sha1')

    with open(cert, "wb") as cf:
    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()
Exemplo n.º 42
0
    def get_server_verify_key_v1_direct(self, server_name, key_ids):
        """Finds a verification key for the server with one of the key ids.
        Args:
            server_name (str): The name of the server to fetch a key for.
            keys_ids (list of str): The key_ids to check for.
        """

        # Try to fetch the key from the remote server.

        (response, tls_certificate) = yield fetch_server_key(
            server_name, self.hs.tls_server_context_factory)

        # Check the response.

        x509_certificate_bytes = crypto.dump_certificate(
            crypto.FILETYPE_ASN1, tls_certificate)

        if ("signatures" not in response
                or server_name not in response["signatures"]):
            raise KeyLookupError("Key response not signed by remote server")

        if "tls_certificate" not in response:
            raise KeyLookupError("Key response missing TLS certificate")

        tls_certificate_b64 = response["tls_certificate"]

        if encode_base64(x509_certificate_bytes) != tls_certificate_b64:
            raise KeyLookupError("TLS certificate doesn't match")

        # Cache the result in the datastore.

        time_now_ms = self.clock.time_msec()

        verify_keys = {}
        for key_id, key_base64 in response["verify_keys"].items():
            if is_signing_algorithm_supported(key_id):
                key_bytes = decode_base64(key_base64)
                verify_key = decode_verify_key_bytes(key_id, key_bytes)
                verify_key.time_added = time_now_ms
                verify_keys[key_id] = verify_key

        for key_id in response["signatures"][server_name]:
            if key_id not in response["verify_keys"]:
                raise KeyLookupError(
                    "Key response must include verification keys for all"
                    " signatures")
            if key_id in verify_keys:
                verify_signed_json(response, server_name, verify_keys[key_id])

        yield self.store.store_server_certificate(
            server_name,
            server_name,
            time_now_ms,
            tls_certificate,
        )

        yield self.store_keys(
            server_name=server_name,
            from_server=server_name,
            verify_keys=verify_keys,
        )

        defer.returnValue(verify_keys)
Exemplo n.º 43
0
def is_cert_valid(expected, observed):
    c1 = crypto.load_certificate(crypto.FILETYPE_PEM, expected)
    c2 = crypto.load_certificate(crypto.FILETYPE_PEM, observed)
    return (crypto.dump_certificate(crypto.FILETYPE_PEM,
                                    c1) == crypto.dump_certificate(
                                        crypto.FILETYPE_PEM, c2))
Exemplo n.º 44
0
def create_self_signed_cert(
        organisation: str = 'Ceph',
        common_name: str = 'mgr',
        dname: Optional[Dict[str, str]] = None) -> Tuple[str, str]:
    """Returns self-signed PEM certificates valid for 10 years.
    
    The optional dname parameter provides complete control of the cert/key
    creation by supporting all valid RDNs via a dictionary. However, if dname
    is not provided the default O and CN settings will be applied.

    :param organisation: String representing the Organisation(O) RDN (default='Ceph')
    :param common_name: String representing the Common Name(CN) RDN (default='mgr')
    :param dname: Optional dictionary containing RDNs to use for crt/key generation 

    :return: ssl crt and key in utf-8 format

    :raises ValueError: if the dname parameter received contains invalid RDNs

    """

    from OpenSSL import crypto
    from uuid import uuid4

    # RDN = Relative Distinguished Name
    valid_RDN_list = ['C', 'ST', 'L', 'O', 'OU', 'CN', 'emailAddress']

    # create a key pair
    pkey = crypto.PKey()
    pkey.generate_key(crypto.TYPE_RSA, 2048)

    # Create a "subject" object
    req = crypto.X509Req()
    subj = req.get_subject()

    if dname:
        # dname received, so check it contains valid RDNs
        if not all(field in valid_RDN_list for field in dname):
            raise ValueError(
                "Invalid DNAME received. Valid DNAME fields are {}".format(
                    ', '.join(valid_RDN_list)))
    else:
        dname = {"O": organisation, "CN": common_name}

    # populate the subject with the dname settings
    for k, v in dname.items():
        setattr(subj, k, v)

    # create a self-signed cert
    cert = crypto.X509()
    cert.set_subject(req.get_subject())
    cert.set_serial_number(int(uuid4()))
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(10 * 365 * 24 * 60 * 60)  # 10 years
    cert.set_issuer(cert.get_subject())
    cert.set_pubkey(pkey)
    cert.sign(pkey, 'sha512')

    cert = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)
    pkey = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)

    return cert.decode('utf-8'), pkey.decode('utf-8')
Exemplo n.º 45
0
def getCertificado(clp12):
    cert = crypto.dump_certificate(crypto.FILETYPE_PEM,
                                   clp12.get_certificate())
    return cert
Exemplo n.º 46
0
    def __init__(self, name, roles, pub_net, priv_net, client, ca, ip):
        self.name = name
        self.roles = roles
        self.flavor = client._flavor
        self.sshkey = client._sshkey
        self.region = client._region
        self.pub_net = pub_net
        self.priv_net = priv_net
        self.ip = ip

        self.image = get_coreos_images(client)[0]

        self.userdata = UserData()
        self.userdata.configure_clinux_core()
        self.userdata.gen_etc_hosts(client, priv_net)

        if any([r in self.roles for r in ['master', 'node']]):
            self.userdata.gen_kube_data()

            # Dump X.509 CA cert
            ca_crt_pem = dump_certificate(FILETYPE_PEM, ca.cert)

            # we generate a single RSA key per host due to User Data size limit of 65535 bytes (base64-encoded)
            key = ca.create_key()
            key_pem = dump_privatekey(FILETYPE_PEM, key)

            # TLS client certificates
            kubelet_client_crt = ca.create_client_cert(
                key, 'system:nodes',
                'system:node:host-' + ip.replace('.', '-'))
            kubelet_client_crt_pem = dump_certificate(FILETYPE_PEM,
                                                      kubelet_client_crt)
            proxy_client_crt = ca.create_client_cert(key, 'Kubernetes',
                                                     'system:kube-proxy')
            proxy_client_crt_pem = dump_certificate(FILETYPE_PEM,
                                                    proxy_client_crt)

            # TLS server certificates
            kubelet_server_crt = ca.create_server_cert(
                key, 'Kubernetes', 'host-' + ip.replace('.', '-'))
            kubelet_server_crt_pem = dump_certificate(FILETYPE_PEM,
                                                      kubelet_server_crt)

            self.userdata.add_files([
                {
                    'filesystem': 'root',
                    'path': '/etc/kubernetes/tls/host.key',
                    'mode': 416,  # 0640
                    'contents': {
                        'source': 'data:,' + quote(key_pem)
                    }
                },
                {
                    'filesystem': 'root',
                    'path': '/etc/kubernetes/tls/ca.pem',
                    'mode': 420,  # 0644
                    'contents': {
                        'source': 'data:,' + quote(ca_crt_pem)
                    }
                },
                {
                    'filesystem': 'root',
                    'path': '/etc/kubernetes/tls/client/kubelet.crt',
                    'mode': 420,  # 0644
                    'contents': {
                        'source': 'data:,' + quote(kubelet_client_crt_pem)
                    }
                },
                {
                    'filesystem': 'root',
                    'path': '/etc/kubernetes/tls/server/kubelet.crt',
                    'mode': 420,  # 0644
                    'contents': {
                        'source': 'data:,' + quote(kubelet_server_crt_pem)
                    }
                },
                {
                    'filesystem': 'root',
                    'path': '/etc/kubernetes/tls/client/proxy.crt',
                    'mode': 420,  # 0644
                    'contents': {
                        'source': 'data:,' + quote(proxy_client_crt_pem)
                    }
                }
            ])

        if 'master' in self.roles:
            self.userdata.gen_kubemaster_data()

            # Dump X.509 CA key
            ca_key_pem = dump_privatekey(FILETYPE_PEM, ca.key)

            # TLS server pair for kube API server
            apiserver_san = [
                'DNS:kubernetes.default.svc.cluster.local',
                'DNS:kubernetes.default.svc', 'DNS:kubernetes.default',
                'DNS:kubernetes', 'IP:10.0.0.1', 'DNS:localhost',
                'IP:127.0.0.1', 'DNS:' + 'host-' + ip.replace('.', '-'),
                'IP:' + ip
            ]
            apiserver_crt = ca.create_server_cert(key, 'Kubernetes',
                                                  'apiserver', apiserver_san)
            apiserver_crt_pem = dump_certificate(FILETYPE_PEM, apiserver_crt)

            # TLS server pair for etcd member
            etcd_san = [
                'DNS:localhost', 'IP:127.0.0.1',
                'DNS:' + 'host-' + ip.replace('.', '-'), 'IP:' + ip
            ]
            etcd_member_crt = ca.create_server_cert(key, 'etcd', 'member',
                                                    etcd_san)
            etcd_member_crt_pem = dump_certificate(FILETYPE_PEM,
                                                   etcd_member_crt)

            # TLS client certificates
            cm_crt = ca.create_client_cert(key, 'Kubernetes',
                                           'system:kube-controller-manager')
            cm_crt_pem = dump_certificate(FILETYPE_PEM, cm_crt)
            scheduler_crt = ca.create_client_cert(key, 'Kubernetes',
                                                  'system:kube-scheduler')
            scheduler_crt_pem = dump_certificate(FILETYPE_PEM, scheduler_crt)
            apiserver_client_crt = ca.create_client_cert(
                key, 'system:masters',
                'apiserver:host-' + ip.replace('.', '-'))
            apiserver_client_crt_pem = dump_certificate(
                FILETYPE_PEM, apiserver_client_crt)
            etcd_client_crt = ca.create_client_cert(key, 'etcd', 'root')
            etcd_client_crt_pem = dump_certificate(FILETYPE_PEM,
                                                   etcd_client_crt)

            self.userdata.add_files([
                {
                    'filesystem': 'root',
                    'path': '/etc/kubernetes/tls/ca.key',
                    'mode': 416,  # 0640
                    'contents': {
                        'source': 'data:,' + quote(ca_key_pem)
                    }
                },
                {
                    'filesystem': 'root',
                    'path': '/etc/kubernetes/tls/server/apiserver.crt',
                    'mode': 420,  # 0644
                    'contents': {
                        'source': 'data:,' + quote(apiserver_crt_pem)
                    }
                },
                {
                    'filesystem': 'root',
                    'path': '/etc/kubernetes/tls/server/etcd.crt',
                    'mode': 420,  # 0644
                    'contents': {
                        'source': 'data:,' + quote(etcd_member_crt_pem)
                    }
                },
                {
                    'filesystem': 'root',
                    'path':
                    '/etc/kubernetes/tls/client/controller-manager.crt',
                    'mode': 420,  # 0644
                    'contents': {
                        'source': 'data:,' + quote(cm_crt_pem)
                    }
                },
                {
                    'filesystem': 'root',
                    'path': '/etc/kubernetes/tls/client/scheduler.crt',
                    'mode': 420,  # 0644
                    'contents': {
                        'source': 'data:,' + quote(scheduler_crt_pem)
                    }
                },
                {
                    'filesystem': 'root',
                    'path': '/etc/kubernetes/tls/client/apiserver.crt',
                    'mode': 420,  # 0644
                    'contents': {
                        'source': 'data:,' + quote(apiserver_client_crt_pem)
                    }
                },
                {
                    'filesystem': 'root',
                    'path': '/etc/kubernetes/tls/client/etcd.crt',
                    'mode': 420,  # 0644
                    'contents': {
                        'source': 'data:,' + quote(etcd_client_crt_pem)
                    }
                }
            ])

        if 'node' in self.roles:
            self.userdata.gen_kubenode_data()
Exemplo n.º 47
0
def _dump_cert(cert, filetype=FILETYPE_PEM):
    """Dumps obj cert object to string."""
    return crypto.dump_certificate(filetype, cert)
Exemplo n.º 48
0
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])

    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
        if all_exist(key_file_name, cert_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)
    cert.add_extensions([
        crypto.X509Extension(b'subjectAltName', False,
                             b'DNS:localhost,IP:127.0.0.1'),
        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
Exemplo n.º 49
0
    if not os.path.exists(ca) and not os.path.exists(ca_key):
        print('Root certificate not found, generating it')
        ca_pk = crypto.PKey()
        ca_pk.generate_key(crypto.TYPE_RSA, 2048)
        ca_cert = crypto.X509()
        ca_cert.get_subject().CN = 'Butterfly CA on %s' % socket.gethostname()
        fill_fields(ca_cert.get_subject())
        ca_cert.set_serial_number(uuid.uuid4().int)
        ca_cert.gmtime_adj_notBefore(0)  # From now
        ca_cert.gmtime_adj_notAfter(315360000)  # to 10y
        ca_cert.set_issuer(ca_cert.get_subject())  # Self signed
        ca_cert.set_pubkey(ca_pk)
        ca_cert.sign(ca_pk, 'sha512')

        write(ca, crypto.dump_certificate(crypto.FILETYPE_PEM, ca_cert))
        write(ca_key, crypto.dump_privatekey(crypto.FILETYPE_PEM, ca_pk))
        os.chmod(ca_key, stat.S_IRUSR | stat.S_IWUSR)  # 0o600 perms
    else:
        print('Root certificate found, using it')
        ca_cert = crypto.load_certificate(crypto.FILETYPE_PEM, read(ca))
        ca_pk = crypto.load_privatekey(crypto.FILETYPE_PEM, read(ca_key))

    server_pk = crypto.PKey()
    server_pk.generate_key(crypto.TYPE_RSA, 2048)
    server_cert = crypto.X509()
    server_cert.get_subject().CN = host
    alt = 'subjectAltName'
    value = 'DNS:%s' % host
    server_cert.add_extensions([
        crypto.X509Extension(alt.encode('utf-8'), False, value.encode('utf-8'))
Exemplo n.º 50
0
def generate_self_signed_certificate(subject: Dict) -> Tuple:
    """
    Create and return a self-signed certificate using the provided subject information.

    Args:
        subject     Dictionary holding the certificate subject key/value pair

    Returns:
        device_key, device_cert, ca_cert   Tuple as strings
    """
    ca_key, ca_cert = get_cephqe_ca()

    # Generate the private key
    keyout = crypto.PKey()
    keyout.generate_key(crypto.TYPE_RSA, 2048)

    # Create CSR
    cert = crypto.X509()
    cert.get_subject().C = subject.get("country", "IN")
    cert.get_subject().ST = subject.get("state", "Karnataka")
    cert.get_subject().L = subject.get("locality", "Bangalore")
    cert.get_subject().O = subject.get("company", "Red Hat Inc")
    cert.get_subject().OU = subject.get("department", "Storage")
    cert.get_subject().CN = subject["common_name"]
    cert.set_serial_number(random.randint(200, 50000))
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(365 * 24 * 60 * 60)

    san_list = [
        f"DNS:*.{subject['common_name']}",
        f"DNS:{subject['common_name']}",
        f"IP:{subject['ip_address']}",
    ]
    sans = ", ".join(san_list)
    extensions = [
        crypto.X509Extension(
            b"keyUsage", False,
            b"Digital Signature, Non Repudiation, Key Encipherment"),
        crypto.X509Extension(b"basicConstraints", False, b"CA:FALSE"),
        crypto.X509Extension(b"extendedKeyUsage", False,
                             b"serverAuth, clientAuth"),
        crypto.X509Extension(b"subjectAltName", False, sans.encode()),
    ]
    cert.add_extensions(extensions)

    cert.set_issuer(cert.get_subject())
    cert.set_pubkey(keyout)
    cert.sign(keyout, "sha256")

    # Sign CSR
    if ca_cert and ca_key:
        signed_cert = crypto.X509()
        signed_cert.set_serial_number(random.randint(10, 10000))
        signed_cert.gmtime_adj_notBefore(0)
        signed_cert.gmtime_adj_notAfter(365 * 24 * 60 * 60)
        signed_cert.set_subject(cert.get_subject())
        signed_cert.add_extensions(extensions)
        signed_cert.set_issuer(ca_cert.get_subject())
        signed_cert.set_pubkey(cert.get_pubkey())
        signed_cert.sign(ca_key, "sha256")

        return (
            crypto.dump_privatekey(crypto.FILETYPE_PEM,
                                   keyout).decode("utf-8"),
            crypto.dump_certificate(crypto.FILETYPE_PEM,
                                    signed_cert).decode("utf-8"),
            crypto.dump_certificate(crypto.FILETYPE_PEM,
                                    ca_cert).decode("utf-8"),
        )

    return (
        crypto.dump_privatekey(crypto.FILETYPE_PEM, keyout).decode("utf-8"),
        crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode("utf-8"),
        "",
    )
Exemplo n.º 51
0
    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:
                passphrase = cipher_passphrase["passphrase"]
                if isinstance(cipher_passphrase["passphrase"],
                              six.string_types):
                    passphrase = passphrase.encode('utf-8')
                tmp_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, k,
                                                 cipher_passphrase["cipher"],
                                                 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.decode('utf-8'))
                else:
                    fc.write(tmp_cert.decode('utf-8'))
                fk.write(tmp_key.decode('utf-8'))
                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)
Exemplo n.º 52
0
    def verify(self, signing_cert_str, cert_str):
        """
        Verifies if a certificate is valid and signed by a given certificate.

        :param signing_cert_str: This certificate will be used to verify the
                                  signature. Must be a string representation
                                 of the certificate. If you only have a file
                                 use the method read_str_from_file to
                                 get a string representation.
        :param cert_str:         This certificate will be verified if it is
                                  correct. Must be a string representation
                                 of the certificate. If you only have a file
                                 use the method read_str_from_file to
                                 get a string representation.
        :return:                 Valid, Message
                                 Valid = True if the certificate is valid,
                                 otherwise false.
                                 Message = Why the validation failed.
        """
        try:
            ca_cert = crypto.load_certificate(crypto.FILETYPE_PEM,
                                              signing_cert_str)
            cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_str)

            if self.certificate_not_valid_yet(ca_cert):
                return False, "CA certificate is not valid yet."

            if ca_cert.has_expired() == 1:
                return False, "CA certificate is expired."

            if cert.has_expired() == 1:
                return False, "The signed certificate is expired."

            if self.certificate_not_valid_yet(cert):
                return False, "The signed certificate is not valid yet."

            if ca_cert.get_subject().CN == cert.get_subject().CN:
                return False, (
                    "CN may not be equal for CA certificate and the "
                    "signed certificate.")

            cert_algorithm = cert.get_signature_algorithm()
            if six.PY3:
                cert_algorithm = cert_algorithm.decode('ascii')

            cert_asn1 = crypto.dump_certificate(crypto.FILETYPE_ASN1, cert)

            der_seq = asn1.DerSequence()
            der_seq.decode(cert_asn1)

            cert_certificate = der_seq[0]
            #cert_signature_algorithm=der_seq[1]
            cert_signature = der_seq[2]

            cert_signature_decoded = asn1.DerObject()
            cert_signature_decoded.decode(cert_signature)

            signature_payload = cert_signature_decoded.payload

            sig_pay0 = signature_payload[0]
            if ((isinstance(sig_pay0, int) and sig_pay0 != 0)
                    or (isinstance(sig_pay0, str) and sig_pay0 != '\x00')):
                return (False,
                        "The certificate should not contain any unused bits.")

            signature = signature_payload[1:]

            try:
                crypto.verify(ca_cert, signature, cert_certificate,
                              cert_algorithm)
                return True, "Signed certificate is valid and correctly signed by CA certificate."
            except crypto.Error as e:
                return False, "Certificate is incorrectly signed."
        except Exception as e:
            return False, "Certificate is not valid for an unknown reason. %s" % str(
                e)
Exemplo n.º 53
0
def export_certificate(buf):
    cert = crypto.load_certificate(crypto.FILETYPE_PEM, buf)
    return crypto.dump_certificate(crypto.FILETYPE_PEM, cert)
Exemplo n.º 54
0
    def create_cert_signed_certificate(self,
                                       sign_cert_str,
                                       sign_key_str,
                                       request_cert_str,
                                       hash_alg="sha256",
                                       valid_from=0,
                                       valid_to=315360000,
                                       sn=1,
                                       passphrase=None):
        """
        Will sign a certificate request with a give certificate.
        :param sign_cert_str:     This certificate will be used to sign with.
                                  Must be a string representation of
                                  the certificate. If you only have a file
                                  use the method read_str_from_file to
                                  get a string representation.
        :param sign_key_str:        This is the key for the ca_cert_str
                                  represented as a string.
                                  If you only have a file use the method
                                  read_str_from_file to get a string
                                  representation.
        :param request_cert_str:  This is the prepared certificate to be
                                  signed. Must be a string representation of
                                  the requested certificate. If you only have
                                  a file use the method read_str_from_file
                                  to get a string representation.
        :param hash_alg:          Hash algorithm to use for the key. Default
                                  is sha256.
        :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 passphrase:        Password for the private key in sign_key_str.
        :return:                  String representation of the signed
                                  certificate.
        """
        ca_cert = crypto.load_certificate(crypto.FILETYPE_PEM, sign_cert_str)
        ca_key = None
        if passphrase is not None:
            ca_key = crypto.load_privatekey(crypto.FILETYPE_PEM, sign_key_str,
                                            passphrase)
        else:
            ca_key = crypto.load_privatekey(crypto.FILETYPE_PEM, sign_key_str)
        req_cert = crypto.load_certificate_request(crypto.FILETYPE_PEM,
                                                   request_cert_str)

        cert = crypto.X509()
        cert.set_subject(req_cert.get_subject())
        cert.set_serial_number(sn)
        cert.gmtime_adj_notBefore(valid_from)
        cert.gmtime_adj_notAfter(valid_to)
        cert.set_issuer(ca_cert.get_subject())
        cert.set_pubkey(req_cert.get_pubkey())
        cert.sign(ca_key, hash_alg)

        cert_dump = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)
        if isinstance(cert_dump, six.string_types):
            return cert_dump
        return cert_dump.decode('utf-8')
Exemplo n.º 55
0
def _convert_certificate_der_to_pem(der):
    cert = crypto.load_certificate(crypto.FILETYPE_ASN1, der)
    pem = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)
    return pem
Exemplo n.º 56
0
def _convert_certificate_pem_to_der(pem):
    cert = crypto.load_certificate(crypto.FILETYPE_PEM, pem)
    der = crypto.dump_certificate(crypto.FILETYPE_ASN1, cert)
    return der
Exemplo n.º 57
0
def get_certificate_data():
    _, cert, _ = _load_certificate_and_key()
    return dump_certificate(FILETYPE_PEM, cert)
Exemplo n.º 58
0
    def do_rootCA(self, params):
        tlscfg = cfg
        ca_cfg = cfg.get("tls_ca_config")
        if ca_cfg:
            tlscfg = OpenSIPSCLIConfig()
            tlscfg.parse(ca_cfg)

        cn = tlscfg.read_param(
            "tls_ca_common_name",
            "input the hostname of the website the certificate is for",
            "www.opensips.com")
        ca_dir = tlscfg.read_param("tls_ca_dir", "ca director",
                                   "/etc/opensips/tls/rootCA/")
        cert_file = tlscfg.read_param("tls_ca_cert_file", "cert_file",
                                      "cacert.pem")
        key_file = tlscfg.read_param("tls_ca_key_file", "key_file",
                                     "private/cakey.pem")
        c_f = join(ca_dir, cert_file)
        k_f = join(ca_dir, key_file)
        create_cert = False
        if not exists(c_f) or not exists(k_f):
            create_cert = True
        else:
            if tlscfg.read_param(
                    "tls_ca_overwrite",
                    "rootCA already exists, do you want to overwrite it?",
                    "yes", True):
                create_cert = True
        if create_cert:
            # create a key pair
            key = crypto.PKey()
            key_size = int(
                tlscfg.read_param("tls_ca_key_size", "key_size", 4096))
            key.generate_key(crypto.TYPE_RSA, key_size)

            # create a self-signed cert
            cert = crypto.X509()

            cert.get_subject().C = tlscfg.read_param("tls_ca_country",
                                                     "country")
            cert.get_subject().ST = tlscfg.read_param("tls_ca_state", "state",
                                                      "Ilfov")
            cert.get_subject().L = tlscfg.read_param("tls_ca_city", "city",
                                                     "Bucharest")
            cert.get_subject().O = tlscfg.read_param("tls_ca_organisation",
                                                     "organization",
                                                     "opensips")
            cert.get_subject().OU = tlscfg.read_param(
                "tls_ca_organisational_unit", "organisational unit", "project")
            cert.get_subject().CN = cn
            cert.set_serial_number(1)
            cert.gmtime_adj_notBefore(0)
            notafter = int(
                tlscfg.read_param("tls_ca_notafter", "duration", 315360000))
            cert.gmtime_adj_notAfter(notafter)
            cert.set_issuer(cert.get_subject())
            cert.set_pubkey(key)
            md = tlscfg.read_param("tls_ca_md", "md", "sha1")
            cert.sign(key, md)

            if not exists(dirname(c_f)):
                makedirs(dirname(c_f))
            try:
                open(c_f, "wt").write(
                    crypto.dump_certificate(crypto.FILETYPE_PEM,
                                            cert).decode('utf-8'))
            except Exception as e:
                logger.error(e)

            if not exists(dirname(k_f)):
                makedirs(dirname(k_f))
            try:
                open(k_f, "wt").write(
                    crypto.dump_privatekey(crypto.FILETYPE_PEM,
                                           key).decode('utf-8'))
            except Exception as e:
                logger.error(e)
            logger.info("CA certificate created in " + c_f)
            logger.info("CA private key created in " + k_f)
Exemplo n.º 59
0
    def export_cert_artifacts_to_dir(self, id_str, dir_path):
        """
        API to generate certificate, private key files along with any root and chain certificates
        for certificate identified by id_str

        Args:
            id_str (str): A user defined unique id string to identify the certificate
            dir_path (str): Valid directory path where the certificates are to be exported.

        Raises:
            edgectl.errors.EdgeValueError - Any input found to be invalid
            edgectl.errors.EdgeFileAccessError
        """
        if EdgeUtils.check_if_directory_exists(dir_path) is False:
            msg = 'Invalid export directory {0}'.format(dir_path)
            logging.error(msg)
            raise edgectl.errors.EdgeValueError(msg)

        if id_str not in list(self._cert_chain.keys()):
            msg = 'Certificate not in chain. ID: {0}'.format(id_str)
            raise edgectl.errors.EdgeValueError(msg)

        cert_dict = self._cert_chain[id_str]
        prefix = id_str
        try:
            path = os.path.realpath(dir_path)
            path = os.path.join(path, prefix)
            logging.debug('Deleting dir: %s', path)
            EdgeUtils.delete_dir(path)
            logging.debug('Creating dir: %s', path)
            EdgeUtils.mkdir_if_needed(path)
            priv_dir = os.path.join(path, 'private')
            logging.debug('Creating dir: %s', priv_dir)
            EdgeUtils.mkdir_if_needed(priv_dir)
            os.chmod(priv_dir, 0o700)
            cert_dir = os.path.join(path, 'cert')
            logging.debug('Creating dir: %s', cert_dir)
            EdgeUtils.mkdir_if_needed(cert_dir)

            # export the private key
            priv_key_file_name = prefix + '.key.pem'
            priv_key_file = os.path.join(priv_dir, priv_key_file_name)
            if 'key_file' in cert_dict:
                key_file_path = cert_dict['key_file']
                logging.debug('Copying Private Key File %s To %s', key_file_path, priv_key_file)
                copy2(key_file_path, priv_key_file)
            else:
                key_obj = cert_dict['key_pair']
                key_passphrase = cert_dict['passphrase']
                passphrase = None
                if key_passphrase and key_passphrase != '':
                    passphrase = key_passphrase.encode('utf-8')
                logging.debug('Exporting Private Key File: %s', priv_key_file)
                with open(priv_key_file, 'w') as ip_file:
                    cipher = None
                    if passphrase:
                        cipher = 'aes256'
                    ip_file.write(crypto.dump_privatekey(crypto.FILETYPE_PEM,
                                                         key_obj,
                                                         cipher=cipher,
                                                         passphrase=passphrase).decode('utf-8'))

            # export the cert
            cert_obj = cert_dict['cert']
            cert_file_name = prefix + '.cert.pem'
            cert_file = os.path.join(cert_dir, cert_file_name)
            current_cert_file_path = cert_file
            logging.debug('Exporting Certificate File: %s', cert_file)
            with open(cert_file, 'w') as ip_file:
                ip_file.write(crypto.dump_certificate(crypto.FILETYPE_PEM,
                                                      cert_obj).decode('utf-8'))

            # export any chain certs
            if 'ca_chain' in list(cert_dict.keys()):
                src_chain_cert_file = cert_dict['ca_chain']
                cert_file_name = prefix + '-chain.cert.pem'
                cert_file = os.path.join(cert_dir, cert_file_name)
                logging.debug('Copying CA Chain Certificate File %s To %s',
                              src_chain_cert_file, cert_file)
                copy2(src_chain_cert_file, cert_file)

            # check if this is the root cert in the chain, i.e. issuer is itself
            if cert_dict['issuer_id'] == id_str:
                cert_file_name = prefix + '-root.cert.pem'
                cert_file = os.path.join(cert_dir, cert_file_name)
                # export the ca cert's root ca (parent)
                if 'ca_root' in list(cert_dict.keys()):
                    src_root_cert_file = cert_dict['ca_root']
                else:
                    src_root_cert_file = current_cert_file_path
                logging.debug('Copying CA Root Certificate File %s To %s',
                              src_root_cert_file, cert_file)
                copy2(src_root_cert_file, cert_file)
        except IOError as ex:
            msg = 'IO Error when exporting certs for ID: {0}.\n' \
                  ' Error seen when copying/exporting file {1}.' \
                  ' Errno: {2} Error: {3}'.format(id_str, ex.filename, str(ex.errno), ex.strerror)
            logging.error(msg)
            raise edgectl.errors.EdgeFileAccessError(msg, path)
Exemplo n.º 60
0
    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 parse_json(data):
    """