- digest = "md5"
-
- data = None
- cert = None
- issuerKey = None
- issuerSubject = None
- parent = None
-
- separator="-----parent-----"
-
- ##
- # Create a certificate object.
- #
- # @param create If create==True, then also create a blank X509 certificate.
- # @param subject If subject!=None, then create a blank certificate and set
- # it's subject name.
- # @param string If string!=None, load the certficate from the string.
- # @param filename If filename!=None, load the certficiate from the file.
-
- def __init__(self, create=False, subject=None, string=None, filename=None):
- if create or subject:
- self.create()
- if subject:
- self.set_subject(subject)
- if string:
- self.load_from_string(string)
- if filename:
- self.load_from_file(filename)
-
- ##
- # Create a blank X509 certificate and store it in this object.
-
- def create(self):
- self.cert = crypto.X509()
- self.cert.set_serial_number(1)
- self.cert.gmtime_adj_notBefore(0)
- self.cert.gmtime_adj_notAfter(60*60*24*365*5) # five years
-
- ##
- # Given a pyOpenSSL X509 object, store that object inside of this
- # certificate object.
-
- def load_from_pyopenssl_x509(self, x509):
- self.cert = x509
-
- ##
- # Load the certificate from a string
-
- def load_from_string(self, string):
- # if it is a chain of multiple certs, then split off the first one and
- # load it
- parts = string.split(Certificate.separator, 1)
- self.cert = crypto.load_certificate(crypto.FILETYPE_PEM, parts[0])
-
- # if there are more certs, then create a parent and let the parent load
- # itself from the remainder of the string
- if len(parts) > 1:
- self.parent = self.__class__()
- self.parent.load_from_string(parts[1])
-
- ##
- # Load the certificate from a file
-
- def load_from_file(self, filename):
- file = open(filename)
- string = file.read()
- self.load_from_string(string)
-
- ##
- # Save the certificate to a string.
- #
- # @param save_parents If save_parents==True, then also save the parent certificates.
-
- def save_to_string(self, save_parents=False):
- string = crypto.dump_certificate(crypto.FILETYPE_PEM, self.cert)
- if save_parents and self.parent:
- string = string + Certificate.separator + self.parent.save_to_string(save_parents)
- return string
-
- ##
- # Save the certificate to a file.
- # @param save_parents If save_parents==True, then also save the parent certificates.
-
- def save_to_file(self, filename, save_parents=False):
- string = self.save_to_string(save_parents=save_parents)
- open(filename, 'w').write(string)
-
- ##
- # Sets the issuer private key and name
- # @param key Keypair object containing the private key of the issuer
- # @param subject String containing the name of the issuer
- # @param cert (optional) Certificate object containing the name of the issuer
-
- def set_issuer(self, key, subject=None, cert=None):
- self.issuerKey = key
- if subject:
- # it's a mistake to use subject and cert params at the same time
- assert(not cert)
- if isinstance(subject, dict) or isinstance(subject, str):
- req = crypto.X509Req()
- reqSubject = req.get_subject()
- if (isinstance(subject, dict)):
- for key in reqSubject.keys():
- setattr(reqSubject, key, name[key])
- else:
- setattr(reqSubject, "CN", subject)
- subject = reqSubject
- # subject is not valid once req is out of scope, so save req
- self.issuerReq = req
- if cert:
- # if a cert was supplied, then get the subject from the cert
- subject = cert.cert.get_issuer()
- assert(subject)
- self.issuerSubject = subject
-
- ##
- # Get the issuer name
-
- def get_issuer(self, which="CN"):
- x = self.cert.get_issuer()
- return getattr(x, which)
-
- ##
- # Set the subject name of the certificate
-
- def set_subject(self, name):
- req = crypto.X509Req()
- subj = req.get_subject()
- if (isinstance(name, dict)):
- for key in name.keys():
- setattr(subj, key, name[key])
- else:
- setattr(subj, "CN", name)
- self.cert.set_subject(subj)
- ##
- # Get the subject name of the certificate
-
- def get_subject(self, which="CN"):
- x = self.cert.get_subject()
- return getattr(x, which)
-
- ##
- # Get the public key of the certificate.
- #
- # @param key Keypair object containing the public key
-
- def set_pubkey(self, key):
- assert(isinstance(key, Keypair))
- self.cert.set_pubkey(key.get_openssl_pkey())
-
- ##
- # Get the public key of the certificate.
- # It is returned in the form of a Keypair object.
-
- def get_pubkey(self):
- m2x509 = X509.load_cert_string(self.save_to_string())
- pkey = Keypair()
- pkey.key = self.cert.get_pubkey()
- pkey.m2key = m2x509.get_pubkey()
- return pkey
-
- ##
- # Add an X509 extension to the certificate. Add_extension can only be called
- # once for a particular extension name, due to limitations in the underlying
- # library.
- #
- # @param name string containing name of extension
- # @param value string containing value of the extension
-
- def add_extension(self, name, critical, value):
- ext = crypto.X509Extension (name, critical, value)
- self.cert.add_extensions([ext])
-
- ##
- # Get an X509 extension from the certificate
-
- def get_extension(self, name):
- # pyOpenSSL does not have a way to get extensions
- m2x509 = X509.load_cert_string(self.save_to_string())
- value = m2x509.get_ext(name).get_value()
- return value
-
- ##
- # Set_data is a wrapper around add_extension. It stores the parameter str in
- # the X509 subject_alt_name extension. Set_data can only be called once, due
- # to limitations in the underlying library.
-
- def set_data(self, str):
- # pyOpenSSL only allows us to add extensions, so if we try to set the
- # same extension more than once, it will not work
- if self.data != None:
- raise "cannot set subjectAltName more than once"
- self.data = str
- self.add_extension("subjectAltName", 0, "URI:http://" + str)
-
- ##
- # Return the data string that was previously set with set_data
-
- def get_data(self):
- if self.data:
- return self.data
-
- try:
- uri = self.get_extension("subjectAltName")
- except LookupError:
- self.data = None
- return self.data
-
- if not uri.startswith("URI:http://"):
- raise "bad encoding in subjectAltName"
- self.data = uri[11:]
- return self.data
-
- ##
- # Sign the certificate using the issuer private key and issuer subject previous set with set_issuer().
-
- def sign(self):
- assert self.cert != None
- assert self.issuerSubject != None
- assert self.issuerKey != None
- self.cert.set_issuer(self.issuerSubject)
- self.cert.sign(self.issuerKey.get_openssl_pkey(), self.digest)
+ digest = "sha256"
+
+# x509 = None
+# issuerKey = None
+# issuerSubject = None
+# parent = None
+ isCA = None # will be a boolean once set
+
+ separator = "-----parent-----"
+
+ ##
+ # Create a certificate object.
+ #
+ # @param lifeDays life of cert in days - default is 1825==5 years
+ # @param create If create==True, then also create a blank X509 certificate.
+ # @param subject If subject!=None, then create a blank certificate and set
+ # it's subject name.
+ # @param string If string!=None, load the certficate from the string.
+ # @param filename If filename!=None, load the certficiate from the file.
+ # @param isCA If !=None, set whether this cert is for a CA
+
+ def __init__(self, lifeDays=1825, create=False, subject=None, string=None,
+ filename=None, isCA=None):
+ # these used to be defined in the class !
+ self.x509 = None
+ self.issuerKey = None
+ self.issuerSubject = None
+ self.parent = None
+
+ self.data = {}
+ if create or subject:
+ self.create(lifeDays)
+ if subject:
+ self.set_subject(subject)
+ if string:
+ self.load_from_string(string)
+ if filename:
+ self.load_from_file(filename)
+
+ # Set the CA bit if a value was supplied
+ if isCA is not None:
+ self.set_is_ca(isCA)
+
+ # Create a blank X509 certificate and store it in this object.
+
+ def create(self, lifeDays=1825):
+ self.x509 = OpenSSL.crypto.X509()
+ # FIXME: Use different serial #s
+ self.x509.set_serial_number(3)
+ self.x509.gmtime_adj_notBefore(0) # 0 means now
+ self.x509.gmtime_adj_notAfter(
+ lifeDays * 60 * 60 * 24) # five years is default
+ self.x509.set_version(2) # x509v3 so it can have extensions
+
+ ##
+ # Given a pyOpenSSL X509 object, store that object inside of this
+ # certificate object.
+
+ def load_from_pyopenssl_x509(self, x509):
+ self.x509 = x509
+
+ ##
+ # Load the certificate from a string
+
+ def load_from_string(self, string):
+ # if it is a chain of multiple certs, then split off the first one and
+ # load it (support for the ---parent--- tag as well as normal chained
+ # certs)
+
+ if string is None or string.strip() == "":
+ logger.warning("Empty string in load_from_string")
+ return
+
+ string = string.strip()
+
+ # If it's not in proper PEM format, wrap it
+ if string.count('-----BEGIN CERTIFICATE') == 0:
+ string = '-----BEGIN CERTIFICATE-----'\
+ '\n{}\n-----END CERTIFICATE-----'\
+ .format(string)
+
+ # If there is a PEM cert in there, but there is some other text first
+ # such as the text of the certificate, skip the text
+ beg = string.find('-----BEGIN CERTIFICATE')
+ if beg > 0:
+ # skipping over non cert beginning
+ string = string[beg:]
+
+ parts = []
+
+ if string.count('-----BEGIN CERTIFICATE-----') > 1 and \
+ string.count(Certificate.separator) == 0:
+ parts = string.split('-----END CERTIFICATE-----', 1)
+ parts[0] += '-----END CERTIFICATE-----'
+ else:
+ parts = string.split(Certificate.separator, 1)
+
+ self.x509 = OpenSSL.crypto.load_certificate(
+ OpenSSL.crypto.FILETYPE_PEM, parts[0])
+
+ if self.x509 is None:
+ logger.warning(
+ "Loaded from string but cert is None: {}".format(string))
+
+ # if there are more certs, then create a parent and let the parent load
+ # itself from the remainder of the string
+ if len(parts) > 1 and parts[1] != '':
+ self.parent = self.__class__()
+ self.parent.load_from_string(parts[1])
+
+ ##
+ # Load the certificate from a file
+
+ def load_from_file(self, filename):
+ file = open(filename)
+ string = file.read()
+ self.load_from_string(string)
+ self.filename = filename
+
+ ##
+ # Save the certificate to a string.
+ #
+ # @param save_parents If save_parents==True,
+ # then also save the parent certificates.
+
+ def save_to_string(self, save_parents=True):
+ if self.x509 is None:
+ logger.warning("None cert in certificate.save_to_string")
+ return ""
+ string = OpenSSL.crypto.dump_certificate(
+ OpenSSL.crypto.FILETYPE_PEM, self.x509)
+ if PY3 and isinstance(string, bytes):
+ string = string.decode()
+ if save_parents and self.parent:
+ string = string + self.parent.save_to_string(save_parents)
+ return string
+
+ ##
+ # Save the certificate to a file.
+ # @param save_parents If save_parents==True,
+ # then also save the parent certificates.
+
+ def save_to_file(self, filename, save_parents=True, filep=None):
+ string = self.save_to_string(save_parents=save_parents)
+ if filep:
+ f = filep
+ else:
+ f = open(filename, 'w')
+ if PY3 and isinstance(string, bytes):
+ string = string.decode()
+ f.write(string)
+ f.close()
+ self.filename = filename
+
+ ##
+ # Save the certificate to a random file in /tmp/
+ # @param save_parents If save_parents==True,
+ # then also save the parent certificates.
+ def save_to_random_tmp_file(self, save_parents=True):
+ fp, filename = mkstemp(suffix='cert', text=True)
+ fp = os.fdopen(fp, "w")
+ self.save_to_file(filename, save_parents=True, filep=fp)
+ return filename
+
+ ##
+ # Sets the issuer private key and name
+ # @param key Keypair object containing the private key of the issuer
+ # @param subject String containing the name of the issuer
+ # @param cert (optional)
+ # Certificate object containing the name of the issuer
+
+ def set_issuer(self, key, subject=None, cert=None):
+ self.issuerKey = key
+ if subject:
+ # it's a mistake to use subject and cert params at the same time
+ assert(not cert)
+ if isinstance(subject, dict) or isinstance(subject, str):
+ req = OpenSSL.crypto.X509Req()
+ reqSubject = req.get_subject()
+ if isinstance(subject, dict):
+ for key in reqSubject.keys():
+ setattr(reqSubject, key, subject[key])
+ else:
+ setattr(reqSubject, "CN", subject)
+ subject = reqSubject
+ # subject is not valid once req is out of scope, so save req
+ self.issuerReq = req
+ if cert:
+ # if a cert was supplied, then get the subject from the cert
+ subject = cert.x509.get_subject()
+ assert(subject)
+ self.issuerSubject = subject
+
+ ##
+ # Get the issuer name
+
+ def get_issuer(self, which="CN"):
+ x = self.x509.get_issuer()
+ return getattr(x, which)
+
+ ##
+ # Set the subject name of the certificate
+
+ def set_subject(self, name):
+ req = OpenSSL.crypto.X509Req()
+ subj = req.get_subject()
+ if isinstance(name, dict):
+ for key in name.keys():
+ setattr(subj, key, name[key])
+ else:
+ setattr(subj, "CN", name)
+ self.x509.set_subject(subj)
+
+ ##
+ # Get the subject name of the certificate
+
+ def get_subject(self, which="CN"):
+ x = self.x509.get_subject()
+ return getattr(x, which)
+
+ ##
+ # Get a pretty-print subject name of the certificate
+ # let's try to make this a little more usable as is makes logs hairy
+ # FIXME: Consider adding 'urn:publicid' and 'uuid' back for GENI?
+ pretty_fields = ['email']
+
+ def filter_chunk(self, chunk):
+ for field in self.pretty_fields:
+ if field in chunk:
+ return " " + chunk
+
+ def pretty_cert(self):
+ message = "[Cert."
+ x = self.x509.get_subject()
+ ou = getattr(x, "OU")
+ if ou:
+ message += " OU: {}".format(ou)
+ cn = getattr(x, "CN")
+ if cn:
+ message += " CN: {}".format(cn)
+ data = self.get_data(field='subjectAltName')
+ if data:
+ message += " SubjectAltName:"
+ counter = 0
+ filtered = [self.filter_chunk(chunk) for chunk in data.split()]
+ message += " ".join([f for f in filtered if f])
+ omitted = len([f for f in filtered if not f])
+ if omitted:
+ message += "..+{} omitted".format(omitted)
+ message += "]"
+ return message
+
+ def pretty_chain(self):
+ message = "{}".format(self.x509.get_subject())
+ parent = self.parent
+ while parent:
+ message += "->{}".format(parent.x509.get_subject())
+ parent = parent.parent
+ return message
+
+ def pretty_name(self):
+ return self.get_filename() or self.pretty_chain()
+
+ ##
+ # Get the public key of the certificate.
+ #
+ # @param key Keypair object containing the public key
+
+ def set_pubkey(self, key):
+ assert(isinstance(key, Keypair))
+ self.x509.set_pubkey(key.get_openssl_pkey())
+
+ ##
+ # Get the public key of the certificate.
+ # It is returned in the form of a Keypair object.
+
+ def get_pubkey(self):
+ import M2Crypto
+ m2x509 = M2Crypto.X509.load_cert_string(self.save_to_string())
+ pkey = Keypair()
+ pkey.key = self.x509.get_pubkey()
+ pkey.m2key = m2x509.get_pubkey()
+ return pkey
+
+ def set_intermediate_ca(self, val):
+ return self.set_is_ca(val)
+
+ # Set whether this cert is for a CA.
+ # All signers and only signers should be CAs.
+ # The local member starts unset, letting us check that you only set it once
+ # @param val Boolean indicating whether this cert is for a CA
+ def set_is_ca(self, val):
+ if val is None:
+ return
+
+ if self.isCA is not None:
+ # Can't double set properties
+ raise Exception(
+ "Cannot set basicConstraints CA:?? more than once. "
+ "Was {}, trying to set as {}".format(self.isCA, val))
+
+ self.isCA = val
+ if val:
+ self.add_extension('basicConstraints', 1, 'CA:TRUE')
+ else:
+ self.add_extension('basicConstraints', 1, 'CA:FALSE')
+
+ ##
+ # Add an X509 extension to the certificate. Add_extension can only
+ # be called once for a particular extension name, due to
+ # limitations in the underlying library.
+ #
+ # @param name string containing name of extension
+ # @param value string containing value of the extension
+
+ def add_extension(self, name, critical, value):
+ oldExtVal = None
+ try:
+ oldExtVal = self.get_extension(name)
+ except:
+ # M2Crypto LookupError when the extension isn't there (yet)
+ pass
+
+ # This code limits you from adding the extension with the same value
+ # The method comment says you shouldn't do this with the same name
+ # But actually it (m2crypto) appears to allow you to do this.
+ if oldExtVal and oldExtVal == value:
+ # don't add this extension again
+ # just do nothing as here
+ return
+ # FIXME: What if they are trying to set with a different value?
+ # Is this ever OK? Or should we raise an exception?
+# elif oldExtVal:
+# raise "Cannot add extension {} which had val {} with new val {}"\
+# .format(name, oldExtVal, value)
+
+ ext = OpenSSL.crypto.X509Extension(name, critical, value)
+ self.x509.add_extensions([ext])
+
+ ##
+ # Get an X509 extension from the certificate
+
+ def get_extension(self, name):
+
+ import M2Crypto
+ if name is None:
+ return None
+
+ certstr = self.save_to_string()
+ if certstr is None or certstr == "":
+ return None
+ # pyOpenSSL does not have a way to get extensions
+ m2x509 = M2Crypto.X509.load_cert_string(certstr)
+ if m2x509 is None:
+ logger.warning("No cert loaded in get_extension")
+ return None
+ if m2x509.get_ext(name) is None:
+ return None
+ value = m2x509.get_ext(name).get_value()
+
+ return value
+
+ ##
+ # Set_data is a wrapper around add_extension. It stores the
+ # parameter str in the X509 subject_alt_name extension. Set_data
+ # can only be called once, due to limitations in the underlying
+ # library.
+
+ def set_data(self, string, field='subjectAltName'):
+ # pyOpenSSL only allows us to add extensions, so if we try to set the
+ # same extension more than once, it will not work
+ if field in self.data:
+ raise Exception("Cannot set {} more than once".format(field))
+ self.data[field] = string
+ # call str() because we've seen unicode there
+ # and the underlying C code doesn't like it
+ self.add_extension(field, 0, str(string))
+
+ ##
+ # Return the data string that was previously set with set_data
+
+ def get_data(self, field='subjectAltName'):
+ if field in self.data:
+ return self.data[field]
+
+ try:
+ uri = self.get_extension(field)
+ self.data[field] = uri
+ except LookupError:
+ return None
+
+ return self.data[field]
+
+ ##
+ # Sign the certificate using the issuer private key and issuer subject
+ # previous set with set_issuer().
+
+ def sign(self):
+ logger.debug('certificate.sign')
+ assert self.x509 is not None
+ assert self.issuerSubject is not None
+ assert self.issuerKey is not None
+ self.x509.set_issuer(self.issuerSubject)
+ self.x509.sign(self.issuerKey.get_openssl_pkey(), self.digest)