def _generateChild(self, cert, serial, validity): key = crypto.PKey() key.generate_key(self.keyalg, self.keysize) req = crypto.X509Req() setSubject(cert.dn, req.get_subject()) req.set_pubkey(key) req.sign(key, self.sigalg) x509 = crypto.X509() x509.set_version(0x02) x509.set_serial_number(serial or random.getrandbits(64)) if validity is None or validity > 0: x509.gmtime_adj_notBefore(0) x509.gmtime_adj_notAfter(60 * 60 * 24 * (validity or self.validity)) else: x509.gmtime_adj_notBefore(60 * 60 * 24 * validity) x509.gmtime_adj_notAfter(0) x509.set_issuer(self.cacert.x509.get_subject()) x509.set_subject(req.get_subject()) x509.set_pubkey(req.get_pubkey()) extensions = [ crypto.X509Extension(b('subjectKeyIdentifier'), False, b('hash'), subject=x509), crypto.X509Extension(b('authorityKeyIdentifier'), False, b('keyid:always,issuer:always'), issuer=self.cacert.x509), crypto.X509Extension( b('keyUsage'), False, b('nonRepudiation, digitalSignature, keyEncipherment')) ] subAltName = cert.getAlternativeName() if subAltName: extensions.append( crypto.X509Extension(b('subjectAltName'), False, b(subAltName))) if self.cacert.getAlternativeName(): extensions.append( crypto.X509Extension(b('issuerAltName'), False, b("issuer:copy"), issuer=self.cacert.x509)) x509.add_extensions(extensions) x509.sign(self.cacert.pkey, self.sigalg) return cert.init(key, x509)
def __init__(self, *args, **kargs): CertificateFactory.__init__(self, *args, **kargs) if not self.parent: self.keyalg = crypto.TYPE_RSA if self.keyalg == "rsa" else crypto.TYPE_DSA self.cipher = "DES-EDE3-CBC" # Cipher used to encode the private key if not self.cacert.exists(): # Generate the CA certificate key = crypto.PKey() key.generate_key(self.keyalg, self.keysize) req = crypto.X509Req() setSubject(self.cacert.dn, req.get_subject()) req.set_pubkey(key) req.sign(key, self.sigalg) x509 = crypto.X509() x509.set_version(0x02) x509.set_serial_number(random.getrandbits(64)) x509.gmtime_adj_notBefore(0) x509.gmtime_adj_notAfter(60 * 60 * 24 * self.validity) x509.set_subject(req.get_subject()) x509.set_pubkey(req.get_pubkey()) extensions = [ crypto.X509Extension(b('basicConstraints'), False, b('CA:true')), crypto.X509Extension(b('subjectKeyIdentifier'), False, b('hash'), subject=x509), ] subjectAltName = self.cacert.getAlternativeName() if subjectAltName: extensions.append(crypto.X509Extension(b('subjectAltName'), False, b(subjectAltName))) if self.parent: extensions.append(crypto.X509Extension(b('authorityKeyIdentifier'), False, b('keyid:always,issuer:always'), issuer=self.parent.cacert.x509)) if self.parent.cacert.getAlternativeName(): extensions.append(crypto.X509Extension(b('issuerAltName'), False, b("issuer:copy"), issuer=self.parent.cacert.x509)) x509.add_extensions(extensions) if self.parent: x509.set_issuer(self.parent.cacert.x509.get_subject()) x509.sign(self.parent.cacert.pkey, self.sigalg) else: x509.set_issuer(req.get_subject()) x509.sign(key, self.sigalg) self.cacert.init(key, x509)
def saveKey(self, path, password=None): if not opensslSupport: raise RuntimeError("No openssl support, add openssl to your PATH to export private keys") # # Write password to safe temporary file # passpath = None if password: (f, passpath) = tempfile.mkstemp() os.write(f, b(password)) os.close(f) try: pem = self.parent.run("openssl", "pkcs12", "-nocerts", "-nodes", "-in " + self.generatePKCS12(), passin="file:" + self.parent.passpath, passout=("file:" + passpath) if passpath else None) (_, ext) = os.path.splitext(path) outform = "DER" if ext == ".der" or ext == ".crt" or ext == ".cer" else "PEM" self.parent.run("openssl", "pkcs8", "-nocrypt -topk8", outform=outform, out=path, stdin=pem) finally: if passpath: os.remove(passpath) return self
def savePKCS12(self, path, password=None, chain=True, root=False, addkey=None): if addkey is None: addkey = self != self.parent.cacert chainfile = None if chain: # Save the certificate chain to PKCS12 certs = "" parent = self.parent while parent if root else parent.parent: certs += d(read(parent.cacert.pem)) parent = parent.parent if len(certs) > 0: (f, chainfile) = tempfile.mkstemp() os.write(f, b(certs)) os.close(f) key = "-inkey={0}".format(self.key) if addkey else "-nokeys" try: self.openSSL("pkcs12", out=path, inkey=self.key, certfile=chainfile, password=password or "password") finally: if chainfile: os.remove(chainfile) return self
def generateKEY(self): if not os.path.exists(self.key): write( self.key, crypto.dump_privatekey(crypto.FILETYPE_PEM, self.pkey, self.parent.cipher, b(self.parent.password)))
def savePKCS12(self, path, password=None, chain=True, root=False, addkey=None): if addkey is None: addkey = self != self.parent.cacert p12 = crypto.PKCS12() p12.set_certificate(self.x509) p12.set_friendlyname(b(self.alias)) if addkey: p12.set_privatekey(self.pkey) if chain: certs = [] parent = self.parent while parent if root else parent.parent: certs.append(parent.cacert.x509) parent = parent.parent p12.set_ca_certificates(certs) write(path, p12.export(b(password or "password"))) return self
def saveKey(self, path, password=None): (_, ext) = os.path.splitext(path) type = crypto.FILETYPE_PEM if ext == ".der" or ext == ".crt" or ext == ".cer": type = crypto.FILETYPE_ASN1 if password: write(path, crypto.dump_privatekey(type, self.pkey, self.parent.cipher, b(password))) else: write(path, crypto.dump_privatekey(type, self.pkey)) return self
def _generateChild(self, cert, serial, validity): key = crypto.PKey() key.generate_key(self.keyalg, self.keysize) req = crypto.X509Req() setSubject(cert.dn, req.get_subject()) req.set_pubkey(key) req.sign(key, self.sigalg) x509 = crypto.X509() x509.set_version(0x02) x509.set_serial_number(serial or random.getrandbits(64)) if validity is None or validity > 0: x509.gmtime_adj_notBefore(0) x509.gmtime_adj_notAfter(60 * 60 * 24 * (validity or self.validity)) else: x509.gmtime_adj_notBefore(60 * 60 * 24 * validity) x509.gmtime_adj_notAfter(0) x509.set_issuer(self.cacert.x509.get_subject()) x509.set_subject(req.get_subject()) x509.set_pubkey(req.get_pubkey()) extensions = [ crypto.X509Extension(b('subjectKeyIdentifier'), False, b('hash'), subject=x509), crypto.X509Extension(b('authorityKeyIdentifier'), False, b('keyid:always,issuer:always'), issuer=self.cacert.x509), crypto.X509Extension(b('keyUsage'), False, b('nonRepudiation, digitalSignature, keyEncipherment')) ] subAltName = cert.getAlternativeName() if subAltName: extensions.append(crypto.X509Extension(b('subjectAltName'), False, b(subAltName))) if self.cacert.getAlternativeName(): extensions.append(crypto.X509Extension(b('issuerAltName'), False, b("issuer:copy"), issuer=self.cacert.x509)) x509.add_extensions(extensions) x509.sign(self.cacert.pkey, self.sigalg) return cert.init(key, x509)
def load(self): cert = crypto.load_certificate(crypto.FILETYPE_PEM, read(self.pem)) key = crypto.load_privatekey(crypto.FILETYPE_PEM, read(self.key), b(self.parent.password)) subject = cert.get_subject() self.dn = DistinguishedName(subject.commonName, subject.organizationalUnitName, subject.organizationName, subject.localityName, subject.stateOrProvinceName, subject.countryName, subject.emailAddress) return self.init(key, cert)
def saveKey(self, path, password=None): (_, ext) = os.path.splitext(path) type = crypto.FILETYPE_PEM if ext == ".der" or ext == ".crt" or ext == ".cer": type = crypto.FILETYPE_ASN1 if password: write( path, crypto.dump_privatekey(type, self.pkey, self.parent.cipher, b(password))) else: write(path, crypto.dump_privatekey(type, self.pkey)) return self
def openSSL(self, cmd, *args, **kargs): command = "openssl {cmd}".format(cmd=cmd) # Consume cert argument cert = kargs.get("cert", None) if cert: del kargs["cert"] # Consume config/extfile arguments tmpfiles = [] for a in ["config", "extfile"]: data = kargs.get(a, None) if data: del kargs[a] (f, path) = tempfile.mkstemp() os.write(f, b(data)) os.close(f) command += " -{a} {path}".format(a=a, path=path) tmpfiles.append(path) # Consume password argument password = kargs.get("password", None) if password: del kargs["password"] # # Write password to safe temporary file # passpath = None if password: (f, passpath) = tempfile.mkstemp() os.write(f, b(password)) os.close(f) tmpfiles.append(passpath) # # Key creation and certificate request parameters # if cmd == "req": command += " -keyform PEM -keyout {cert.key} -newkey {this.keyalg}:{this.keyparams}" if "-x509" in args: command += " -out {cert.pem} -passout file:\"{this.passpath}\"" # CA self-signed certificate else: command += " -passout file:\"{this.passpath}\"" # # Signature parameters for "req -x509" (CA self-signed certificate) or # "x509 -req" (signing certificate request) # if (cmd == "req" and "-x509" in args) or (cmd == "x509" and "-req" in args): command += " -{this.sigalg}" # # Certificate request signature parameters # if cmd == "x509" and "-req" in args: command += " -CA {cacert.pem} -CAkey {cacert.key} -passin file:\"{this.passpath}\" -extensions ext " \ "-out {cert.pem}" # # Export certificate parameters # if cmd == "x509" and not "-req" in args: command += " -in {cert.pem}" elif cmd == self.keyalg or cmd == "pkcs8": command += " -in {cert.key} -passin file:\"{this.passpath}\"" if password: command += " -passout file:\"{passpath}\"" elif cmd == "pkcs12": command += " -in {cert.pem} -name {cert.alias} -export -passin file:\"{this.passpath}\"" command += " -passout file:\"{passpath}\"" command = command.format(cert=cert, cacert=self.cacert, this=self, passpath=passpath) try: return self.run(command, *args, **kargs) finally: for f in tmpfiles: # Remove temporary configuration files os.remove(f)
def __init__(self, *args, **kargs): CertificateFactory.__init__(self, *args, **kargs) if not self.parent: self.keyalg = crypto.TYPE_RSA if self.keyalg == "rsa" else crypto.TYPE_DSA self.cipher = "DES-EDE3-CBC" # Cipher used to encode the private key if not self.cacert.exists(): # Generate the CA certificate key = crypto.PKey() key.generate_key(self.keyalg, self.keysize) req = crypto.X509Req() setSubject(self.cacert.dn, req.get_subject()) req.set_pubkey(key) req.sign(key, self.sigalg) x509 = crypto.X509() x509.set_version(0x02) x509.set_serial_number(random.getrandbits(64)) x509.gmtime_adj_notBefore(0) x509.gmtime_adj_notAfter(60 * 60 * 24 * self.validity) x509.set_subject(req.get_subject()) x509.set_pubkey(req.get_pubkey()) extensions = [ crypto.X509Extension(b('basicConstraints'), False, b('CA:true')), crypto.X509Extension(b('subjectKeyIdentifier'), False, b('hash'), subject=x509), ] subjectAltName = self.cacert.getAlternativeName() if subjectAltName: extensions.append( crypto.X509Extension(b('subjectAltName'), False, b(subjectAltName))) if self.parent: extensions.append( crypto.X509Extension(b('authorityKeyIdentifier'), False, b('keyid:always,issuer:always'), issuer=self.parent.cacert.x509)) if self.parent.cacert.getAlternativeName(): extensions.append( crypto.X509Extension(b('issuerAltName'), False, b("issuer:copy"), issuer=self.parent.cacert.x509)) x509.add_extensions(extensions) if self.parent: x509.set_issuer(self.parent.cacert.x509.get_subject()) x509.sign(self.parent.cacert.pkey, self.sigalg) else: x509.set_issuer(req.get_subject()) x509.sign(key, self.sigalg) self.cacert.init(key, x509)
def generateKEY(self): if not os.path.exists(self.key): write(self.key, crypto.dump_privatekey(crypto.FILETYPE_PEM, self.pkey, self.parent.cipher, b(self.parent.password)))
def openSSL(self, cmd, *args, **kargs): command = "openssl {cmd}".format(cmd = cmd) # Consume cert argument cert = kargs.get("cert", None) if cert: del kargs["cert"] # Consume config/extfile arguments tmpfiles = [] for a in ["config", "extfile"]: data = kargs.get(a, None) if data: del kargs[a] (f, path) = tempfile.mkstemp() os.write(f, b(data)) os.close(f) command += " -{a} {path}".format(a=a, path=path) tmpfiles.append(path) # Consume password argument password = kargs.get("password", None) if password: del kargs["password"] # # Write password to safe temporary file # passpath = None if password: (f, passpath) = tempfile.mkstemp() os.write(f, b(password)) os.close(f) tmpfiles.append(passpath) # # Key creation and certificate request parameters # if cmd == "req": command += " -keyform PEM -keyout {cert.key} -newkey {this.keyalg}:{this.keysize}" if "-x509" in args: command += " -out {cert.pem} -passout file:\"{this.passpath}\"" # CA self-signed certificate else: command += " -passout file:\"{this.passpath}\"" # # Signature parameters for "req -x509" (CA self-signed certificate) or # "x509 -req" (signing certificate request) # if (cmd == "req" and "-x509" in args) or (cmd == "x509" and "-req" in args): command += " -{this.sigalg}" # # Certificate request signature parameters # if cmd == "x509" and "-req" in args: command += " -CA {cacert.pem} -CAkey {cacert.key} -passin file:\"{this.passpath}\" -extensions ext " \ "-out {cert.pem}" # # Export certificate parameters # if cmd == "x509" and not "-req" in args: command += " -in {cert.pem}" elif cmd == self.keyalg or cmd == "pkcs8": command += " -in {cert.key} -passin file:\"{this.passpath}\"" if password: command += " -passout file:\"{passpath}\"" elif cmd == "pkcs12": command += " -in {cert.pem} -name {cert.alias} -export -passin file:\"{this.passpath}\"" command += " -passout file:\"{passpath}\"" command = command.format(cert = cert, cacert = self.cacert, this = self, passpath=passpath) try: return self.run(command, *args, **kargs) finally: for f in tmpfiles: # Remove temporary configuration files os.remove(f)