1 # ----------------------------------------------------------------------
2 # Copyright (c) 2008 Board of Trustees, Princeton University
4 # Permission is hereby granted, free of charge, to any person obtaining
5 # a copy of this software and/or hardware specification (the "Work") to
6 # deal in the Work without restriction, including without limitation the
7 # rights to use, copy, modify, merge, publish, distribute, sublicense,
8 # and/or sell copies of the Work, and to permit persons to whom the Work
9 # is furnished to do so, subject to the following conditions:
11 # The above copyright notice and this permission notice shall be
12 # included in all copies or substantial portions of the Work.
14 # THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
18 # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
19 # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 # OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
22 # ----------------------------------------------------------------------
25 # SFA uses two crypto libraries: pyOpenSSL and M2Crypto to implement
26 # the necessary crypto functionality. Ideally just one of these libraries
27 # would be used, but unfortunately each of these libraries is independently
28 # lacking. The pyOpenSSL library is missing many necessary functions, and
29 # the M2Crypto library has crashed inside of some of the functions. The
30 # design decision is to use pyOpenSSL whenever possible as it seems more
31 # stable, and only use M2Crypto for those functions that are not possible
34 # This module exports two classes: Keypair and Certificate.
38 # Notes on using the openssl command line
40 # for verifying the chain in a gid,
41 # assuming it is split into pieces p1.pem p2.pem p3.pem
42 # you can use openssl to verify the chain using this command
43 # openssl verify -verbose -CAfile <(cat p2.pem p3.pem) p1.pem
44 # also you can use sfax509 to invoke openssl x509 on all parts of the gid
54 from tempfile import mkstemp
57 # M2Crypto is imported on the fly to minimize crashes
60 from sfa.util.py23 import PY3
62 from sfa.util.faults import (CertExpired, CertMissingParent,
63 CertNotSignedByParent)
64 from sfa.util.sfalogging import logger
66 # this tends to generate quite some logs for little or no value
67 debug_verify_chain = True
69 glo_passphrase_callback = None
72 # A global callback may be implemented for requesting passphrases from the
73 # user. The function will be called with three arguments:
75 # keypair_obj: the keypair object that is calling the passphrase
76 # string: the string containing the private key that's being loaded
77 # x: unknown, appears to be 0, comes from pyOpenSSL and/or m2crypto
79 # The callback should return a string containing the passphrase.
82 def set_passphrase_callback(callback_func):
83 global glo_passphrase_callback
85 glo_passphrase_callback = callback_func
88 # Sets a fixed passphrase.
91 def set_passphrase(passphrase):
92 set_passphrase_callback(lambda k, s, x: passphrase)
95 # Check to see if a passphrase works for a particular private key string.
96 # Intended to be used by passphrase callbacks for input validation.
99 def test_passphrase(string, passphrase):
101 OpenSSL.crypto.load_privatekey(
102 OpenSSL.crypto.FILETYPE_PEM, string, (lambda x: passphrase))
108 def convert_public_key(key):
109 keyconvert_path = "/usr/bin/keyconvert.py"
110 if not os.path.isfile(keyconvert_path):
112 "Could not find keyconvert in {}".format(keyconvert_path))
114 # we can only convert rsa keys
116 raise Exception("keyconvert: dss keys are not supported")
118 (ssh_f, ssh_fn) = tempfile.mkstemp()
119 ssl_fn = tempfile.mktemp()
123 cmd = keyconvert_path + " " + ssh_fn + " " + ssl_fn
126 # this check leaves the temporary file containing the public key so
127 # that it can be expected to see why it failed.
128 # TODO: for production, cleanup the temporary files
129 if not os.path.exists(ssl_fn):
131 "generated certificate not found. keyconvert may have failed.")
135 k.load_pubkey_from_file(ssl_fn)
138 logger.log_exc("convert_public_key caught exception")
141 # remove the temporary files
142 if os.path.exists(ssh_fn):
144 if os.path.exists(ssl_fn):
148 # Public-private key pairs are implemented by the Keypair class.
149 # A Keypair object may represent both a public and private key pair, or it
150 # may represent only a public key (this usage is consistent with OpenSSL).
154 key = None # public/private keypair
155 m2key = None # public key (m2crypto format)
158 # Creates a Keypair object
159 # @param create If create==True, creates a new public/private key and
160 # stores it in the object
161 # @param string If string != None, load the keypair from the string (PEM)
162 # @param filename If filename != None, load the keypair from the file
164 def __init__(self, create=False, string=None, filename=None):
168 self.load_from_string(string)
170 self.load_from_file(filename)
173 # Create a RSA public/private key pair and store it inside the keypair
177 self.key = OpenSSL.crypto.PKey()
178 self.key.generate_key(OpenSSL.crypto.TYPE_RSA, 2048)
181 # Save the private key to a file
182 # @param filename name of file to store the keypair in
184 def save_to_file(self, filename):
185 with open(filename, 'w') as output:
186 output.write(self.as_pem())
187 self.filename = filename
190 # Load the private key from a file. Implicity the private key includes the
193 def load_from_file(self, filename):
194 self.filename = filename
195 buffer = open(filename, 'r').read()
196 self.load_from_string(buffer)
199 # Load the private key from a string. Implicitly the private key includes
202 def load_from_string(self, string):
204 if glo_passphrase_callback:
205 self.key = OpenSSL.crypto.load_privatekey(
206 OpenSSL.crypto.FILETYPE_PEM, string,
207 functools.partial(glo_passphrase_callback, self, string))
208 self.m2key = M2Crypto.EVP.load_key_string(
209 string.encode(encoding="utf-8"),
210 functools.partial(glo_passphrase_callback, self, string))
212 self.key = OpenSSL.crypto.load_privatekey(
213 OpenSSL.crypto.FILETYPE_PEM, string)
214 self.m2key = M2Crypto.EVP.load_key_string(
215 string.encode(encoding="utf-8"))
218 # Load the public key from a string. No private key is loaded.
220 def load_pubkey_from_file(self, filename):
222 # load the m2 public key
223 m2rsakey = M2Crypto.RSA.load_pub_key(filename)
224 self.m2key = M2Crypto.EVP.PKey()
225 self.m2key.assign_rsa(m2rsakey)
227 # create an m2 x509 cert
228 m2name = M2Crypto.X509.X509_Name()
229 m2name.add_entry_by_txt(field="CN", type=0x1001,
230 entry="junk", len=-1, loc=-1, set=0)
231 m2x509 = M2Crypto.X509.X509()
232 m2x509.set_pubkey(self.m2key)
233 m2x509.set_serial_number(0)
234 m2x509.set_issuer_name(m2name)
235 m2x509.set_subject_name(m2name)
236 ASN1 = M2Crypto.ASN1.ASN1_UTCTIME()
238 m2x509.set_not_before(ASN1)
239 m2x509.set_not_after(ASN1)
240 # x509v3 so it can have extensions
241 # prob not necc since this cert itself is junk but still...
242 m2x509.set_version(2)
243 junk_key = Keypair(create=True)
244 m2x509.sign(pkey=junk_key.get_m2_pubkey(), md="sha1")
246 # convert the m2 x509 cert to a pyopenssl x509
247 m2pem = m2x509.as_pem()
248 pyx509 = OpenSSL.crypto.load_certificate(
249 OpenSSL.crypto.FILETYPE_PEM, m2pem)
251 # get the pyopenssl pkey from the pyopenssl x509
252 self.key = pyx509.get_pubkey()
253 self.filename = filename
256 # Load the public key from a string. No private key is loaded.
258 def load_pubkey_from_string(self, string):
259 (f, fn) = tempfile.mkstemp()
262 self.load_pubkey_from_file(fn)
266 # Return the private key in PEM format.
269 return OpenSSL.crypto.dump_privatekey(
270 OpenSSL.crypto.FILETYPE_PEM, self.key)
273 # Return an M2Crypto key object
275 def get_m2_pubkey(self):
278 self.m2key = M2Crypto.EVP.load_key_string(
279 self.as_pem().encode(encoding="utf-8"))
283 # Returns a string containing the public key represented by this object.
285 def get_pubkey_string(self):
286 m2pkey = self.get_m2_pubkey()
287 return base64.b64encode(m2pkey.as_der())
290 # Return an OpenSSL pkey object
292 def get_openssl_pkey(self):
296 # Given another Keypair object, return TRUE if the two keys are the same.
298 def is_same(self, pkey):
299 return self.as_pem() == pkey.as_pem()
301 def sign_string(self, data):
302 k = self.get_m2_pubkey()
305 return base64.b64encode(k.sign_final())
307 def verify_string(self, data, sig):
309 k = self.get_m2_pubkey()
311 k.verify_update(data)
312 return M2Crypto.m2.verify_final(k.ctx, base64.b64decode(sig), k.pkey)
314 def compute_hash(self, value):
315 return self.sign_string(str(value))
318 def get_filename(self):
319 return getattr(self, 'filename', None)
321 def dump(self, *args, **kwargs):
322 print(self.dump_string(*args, **kwargs))
324 def dump_string(self):
326 result += "KEYPAIR: pubkey={:>40}...".format(self.get_pubkey_string())
327 filename = self.get_filename()
329 result += "Filename {}\n".format(filename)
333 # The certificate class implements a general purpose X509 certificate, making
334 # use of the appropriate pyOpenSSL or M2Crypto abstractions. It also adds
335 # several addition features, such as the ability to maintain a chain of
336 # parent certificates, and storage of application-specific data.
338 # Certificates include the ability to maintain a chain of parents. Each
339 # certificate includes a pointer to it's parent certificate. When loaded
340 # from a file or a string, the parent chain will be automatically loaded.
341 # When saving a certificate to a file or a string, the caller can choose
342 # whether to save the parent certificates as well.
350 # issuerSubject = None
352 isCA = None # will be a boolean once set
354 separator = "-----parent-----"
357 # Create a certificate object.
359 # @param lifeDays life of cert in days - default is 1825==5 years
360 # @param create If create==True, then also create a blank X509 certificate.
361 # @param subject If subject!=None, then create a blank certificate and set
363 # @param string If string!=None, load the certficate from the string.
364 # @param filename If filename!=None, load the certficiate from the file.
365 # @param isCA If !=None, set whether this cert is for a CA
367 def __init__(self, lifeDays=1825, create=False, subject=None, string=None,
368 filename=None, isCA=None):
369 # these used to be defined in the class !
371 self.issuerKey = None
372 self.issuerSubject = None
376 if create or subject:
377 self.create(lifeDays)
379 self.set_subject(subject)
381 self.load_from_string(string)
383 self.load_from_file(filename)
385 # Set the CA bit if a value was supplied
389 # Create a blank X509 certificate and store it in this object.
391 def create(self, lifeDays=1825):
392 self.x509 = OpenSSL.crypto.X509()
393 # FIXME: Use different serial #s
394 self.x509.set_serial_number(3)
395 self.x509.gmtime_adj_notBefore(0) # 0 means now
396 self.x509.gmtime_adj_notAfter(
397 lifeDays * 60 * 60 * 24) # five years is default
398 self.x509.set_version(2) # x509v3 so it can have extensions
401 # Given a pyOpenSSL X509 object, store that object inside of this
402 # certificate object.
404 def load_from_pyopenssl_x509(self, x509):
408 # Load the certificate from a string
410 def load_from_string(self, string):
411 # if it is a chain of multiple certs, then split off the first one and
412 # load it (support for the ---parent--- tag as well as normal chained
415 if string is None or string.strip() == "":
416 logger.warning("Empty string in load_from_string")
419 string = string.strip()
421 # If it's not in proper PEM format, wrap it
422 if string.count('-----BEGIN CERTIFICATE') == 0:
423 string = '-----BEGIN CERTIFICATE-----'\
424 '\n{}\n-----END CERTIFICATE-----'\
427 # If there is a PEM cert in there, but there is some other text first
428 # such as the text of the certificate, skip the text
429 beg = string.find('-----BEGIN CERTIFICATE')
431 # skipping over non cert beginning
432 string = string[beg:]
436 if string.count('-----BEGIN CERTIFICATE-----') > 1 and \
437 string.count(Certificate.separator) == 0:
438 parts = string.split('-----END CERTIFICATE-----', 1)
439 parts[0] += '-----END CERTIFICATE-----'
441 parts = string.split(Certificate.separator, 1)
443 self.x509 = OpenSSL.crypto.load_certificate(
444 OpenSSL.crypto.FILETYPE_PEM, parts[0])
446 if self.x509 is None:
448 "Loaded from string but cert is None: {}".format(string))
450 # if there are more certs, then create a parent and let the parent load
451 # itself from the remainder of the string
452 if len(parts) > 1 and parts[1] != '':
453 self.parent = self.__class__()
454 self.parent.load_from_string(parts[1])
457 # Load the certificate from a file
459 def load_from_file(self, filename):
460 file = open(filename)
462 self.load_from_string(string)
463 self.filename = filename
466 # Save the certificate to a string.
468 # @param save_parents If save_parents==True,
469 # then also save the parent certificates.
471 def save_to_string(self, save_parents=True):
472 if self.x509 is None:
473 logger.warning("None cert in certificate.save_to_string")
475 string = OpenSSL.crypto.dump_certificate(
476 OpenSSL.crypto.FILETYPE_PEM, self.x509)
477 if PY3 and isinstance(string, bytes):
478 string = string.decode()
479 if save_parents and self.parent:
480 string = string + self.parent.save_to_string(save_parents)
484 # Save the certificate to a file.
485 # @param save_parents If save_parents==True,
486 # then also save the parent certificates.
488 def save_to_file(self, filename, save_parents=True, filep=None):
489 string = self.save_to_string(save_parents=save_parents)
493 f = open(filename, 'w')
494 if PY3 and isinstance(string, bytes):
495 string = string.decode()
498 self.filename = filename
501 # Save the certificate to a random file in /tmp/
502 # @param save_parents If save_parents==True,
503 # then also save the parent certificates.
504 def save_to_random_tmp_file(self, save_parents=True):
505 fp, filename = mkstemp(suffix='cert', text=True)
506 fp = os.fdopen(fp, "w")
507 self.save_to_file(filename, save_parents=True, filep=fp)
511 # Sets the issuer private key and name
512 # @param key Keypair object containing the private key of the issuer
513 # @param subject String containing the name of the issuer
514 # @param cert (optional)
515 # Certificate object containing the name of the issuer
517 def set_issuer(self, key, subject=None, cert=None):
520 # it's a mistake to use subject and cert params at the same time
522 if isinstance(subject, dict) or isinstance(subject, str):
523 req = OpenSSL.crypto.X509Req()
524 reqSubject = req.get_subject()
525 if isinstance(subject, dict):
526 for key in list(reqSubject.keys()):
527 setattr(reqSubject, key, subject[key])
529 setattr(reqSubject, "CN", subject)
531 # subject is not valid once req is out of scope, so save req
534 # if a cert was supplied, then get the subject from the cert
535 subject = cert.x509.get_subject()
537 self.issuerSubject = subject
540 # Get the issuer name
542 def get_issuer(self, which="CN"):
543 x = self.x509.get_issuer()
544 return getattr(x, which)
547 # Set the subject name of the certificate
549 def set_subject(self, name):
550 req = OpenSSL.crypto.X509Req()
551 subj = req.get_subject()
552 if isinstance(name, dict):
553 for key in list(name.keys()):
554 setattr(subj, key, name[key])
556 setattr(subj, "CN", name)
557 self.x509.set_subject(subj)
560 # Get the subject name of the certificate
562 def get_subject(self, which="CN"):
563 x = self.x509.get_subject()
564 return getattr(x, which)
567 # Get a pretty-print subject name of the certificate
568 # let's try to make this a little more usable as is makes logs hairy
569 # FIXME: Consider adding 'urn:publicid' and 'uuid' back for GENI?
570 pretty_fields = ['email']
572 def filter_chunk(self, chunk):
573 for field in self.pretty_fields:
577 def pretty_cert(self):
579 x = self.x509.get_subject()
580 ou = getattr(x, "OU")
582 message += " OU: {}".format(ou)
583 cn = getattr(x, "CN")
585 message += " CN: {}".format(cn)
586 data = self.get_data(field='subjectAltName')
588 message += " SubjectAltName:"
589 filtered = [self.filter_chunk(chunk) for chunk in data.split()]
590 message += " ".join([f for f in filtered if f])
591 omitted = len([f for f in filtered if not f])
593 message += "..+{} omitted".format(omitted)
597 def pretty_chain(self):
598 message = "{}".format(self.x509.get_subject())
601 message += "->{}".format(parent.x509.get_subject())
602 parent = parent.parent
605 def pretty_name(self):
606 return self.get_filename() or self.pretty_chain()
609 # Get the public key of the certificate.
611 # @param key Keypair object containing the public key
613 def set_pubkey(self, key):
614 assert(isinstance(key, Keypair))
615 self.x509.set_pubkey(key.get_openssl_pkey())
618 # Get the public key of the certificate.
619 # It is returned in the form of a Keypair object.
621 def get_pubkey(self):
623 m2x509 = M2Crypto.X509.load_cert_string(self.save_to_string())
625 pkey.key = self.x509.get_pubkey()
626 pkey.m2key = m2x509.get_pubkey()
629 def set_intermediate_ca(self, val):
630 return self.set_is_ca(val)
632 # Set whether this cert is for a CA.
633 # All signers and only signers should be CAs.
634 # The local member starts unset, letting us check that you only set it once
635 # @param val Boolean indicating whether this cert is for a CA
636 def set_is_ca(self, val):
640 if self.isCA is not None:
641 # Can't double set properties
643 "Cannot set basicConstraints CA:?? more than once. "
644 "Was {}, trying to set as {}".format(self.isCA, val))
648 self.add_extension('basicConstraints', 1, 'CA:TRUE')
650 self.add_extension('basicConstraints', 1, 'CA:FALSE')
653 # Add an X509 extension to the certificate. Add_extension can only
654 # be called once for a particular extension name, due to
655 # limitations in the underlying library.
657 # @param name string containing name of extension
658 # @param value string containing value of the extension
660 def add_extension(self, name, critical, value):
663 oldExtVal = self.get_extension(name)
665 # M2Crypto LookupError when the extension isn't there (yet)
668 # This code limits you from adding the extension with the same value
669 # The method comment says you shouldn't do this with the same name
670 # But actually it (m2crypto) appears to allow you to do this.
671 if oldExtVal and oldExtVal == value:
672 # don't add this extension again
673 # just do nothing as here
675 # FIXME: What if they are trying to set with a different value?
676 # Is this ever OK? Or should we raise an exception?
678 # raise "Cannot add extension {} which had val {} with new val {}"\
679 # .format(name, oldExtVal, value)
681 ext = OpenSSL.crypto.X509Extension(name, critical, value)
682 self.x509.add_extensions([ext])
685 # Get an X509 extension from the certificate
687 def get_extension(self, name):
693 certstr = self.save_to_string()
694 if certstr is None or certstr == "":
696 # pyOpenSSL does not have a way to get extensions
697 m2x509 = M2Crypto.X509.load_cert_string(certstr)
699 logger.warning("No cert loaded in get_extension")
701 if m2x509.get_ext(name) is None:
703 value = m2x509.get_ext(name).get_value()
708 # Set_data is a wrapper around add_extension. It stores the
709 # parameter str in the X509 subject_alt_name extension. Set_data
710 # can only be called once, due to limitations in the underlying
713 def set_data(self, string, field='subjectAltName'):
714 # pyOpenSSL only allows us to add extensions, so if we try to set the
715 # same extension more than once, it will not work
716 if field in self.data:
717 raise Exception("Cannot set {} more than once".format(field))
718 self.data[field] = string
719 # call str() because we've seen unicode there
720 # and the underlying C code doesn't like it
721 self.add_extension(field, 0, str(string))
724 # Return the data string that was previously set with set_data
726 def get_data(self, field='subjectAltName'):
727 if field in self.data:
728 return self.data[field]
731 uri = self.get_extension(field)
732 self.data[field] = uri
736 return self.data[field]
739 # Sign the certificate using the issuer private key and issuer subject
740 # previous set with set_issuer().
743 logger.debug('certificate.sign')
744 assert self.x509 is not None
745 assert self.issuerSubject is not None
746 assert self.issuerKey is not None
747 self.x509.set_issuer(self.issuerSubject)
748 self.x509.sign(self.issuerKey.get_openssl_pkey(), self.digest)
751 # Verify the authenticity of a certificate.
752 # @param pkey is a Keypair object representing a public key. If Pkey
753 # did not sign the certificate, then an exception will be thrown.
755 def verify(self, pubkey):
757 # pyOpenSSL does not have a way to verify signatures
758 m2x509 = M2Crypto.X509.load_cert_string(self.save_to_string())
759 m2pubkey = pubkey.get_m2_pubkey()
761 # https://www.openssl.org/docs/man1.1.0/crypto/X509_verify.html
765 # -1 if it could not be checked 'for some reason'
766 m2result = m2x509.verify(m2pubkey)
767 result = m2result == 1
768 if debug_verify_chain:
769 logger.debug("Certificate.verify: <- {} (m2={}) ({} x {})"
770 .format(result, m2result,
771 self.pretty_cert(), m2pubkey))
774 # XXX alternatively, if openssl has been patched, do the much simpler:
776 # self.x509.verify(pkey.get_openssl_key())
782 # Return True if pkey is identical to the public key that is
783 # contained in the certificate.
784 # @param pkey Keypair object
786 def is_pubkey(self, pkey):
787 return self.get_pubkey().is_same(pkey)
790 # Given a certificate cert, verify that this certificate was signed by the
791 # public key contained in cert. Throw an exception otherwise.
793 # @param cert certificate object
795 def is_signed_by_cert(self, cert):
796 key = cert.get_pubkey()
797 logger.debug("Certificate.is_signed_by_cert -> verify on {}\n"
800 result = self.verify(key)
804 # Set the parent certficiate.
806 # @param p certificate object.
808 def set_parent(self, p):
812 # Return the certificate object of the parent of this certificate.
814 def get_parent(self):
818 # Verification examines a chain of certificates to ensure that each parent
819 # signs the child, and that some certificate in the chain is signed by a
820 # trusted certificate.
822 # Verification is a basic recursion: <pre>
823 # if this_certificate was signed by trusted_certs:
826 # return verify_chain(parent, trusted_certs)
829 # At each recursion, the parent is tested to ensure that it did sign the
830 # child. If a parent did not sign a child, then an exception is thrown. If
831 # the bottom of the recursion is reached and the certificate does not match
832 # a trusted root, then an exception is thrown.
833 # Also require that parents are CAs.
835 # @param Trusted_certs is a list of certificates that are trusted.
838 def verify_chain(self, trusted_certs=None):
839 # Verify a chain of certificates. Each certificate must be signed by
840 # the public key contained in it's parent. The chain is recursed
841 # until a certificate is found that is signed by a trusted root.
843 # verify expiration time
844 if self.x509.has_expired():
845 if debug_verify_chain:
846 logger.debug("verify_chain: NO, Certificate {} has expired"
847 .format(self.pretty_cert()))
848 raise CertExpired(self.pretty_cert(), "client cert")
850 # if this cert is signed by a trusted_cert, then we are set
851 for i, trusted_cert in enumerate(trusted_certs, 1):
853 " Certificate.verify_chain - trying trusted #{} : {}"
854 .format(i, trusted_cert.pretty_name()))
855 if self.is_signed_by_cert(trusted_cert):
856 # verify expiration of trusted_cert ?
857 if not trusted_cert.x509.has_expired():
858 if debug_verify_chain:
859 logger.debug("verify_chain: YES."
860 " Cert {} signed by trusted cert {}"
861 .format(self.pretty_name(),
862 trusted_cert.pretty_name()))
865 if debug_verify_chain:
866 logger.debug("verify_chain: NO. Cert {} "
867 "is signed by trusted_cert {}, "
868 "but that signer is expired..."
869 .format(self.pretty_cert(),
870 trusted_cert.pretty_cert()))
871 raise CertExpired("{} signer trusted_cert {}"
872 .format(self.pretty_name(),
873 trusted_cert.pretty_name()))
875 logger.debug("verify_chain: not a direct"
876 " descendant of trusted root #{}".format(i))
878 # if there is no parent, then no way to verify the chain
880 if debug_verify_chain:
881 logger.debug("verify_chain: NO. {} has no parent "
882 "and issuer {} is not in {} trusted roots"
883 .format(self.pretty_name(), self.get_issuer(),
885 raise CertMissingParent("{}: Issuer {} is not "
886 "one of the {} trusted roots, "
887 "and cert has no parent."
888 .format(self.pretty_name(),
892 # if it wasn't signed by the parent...
893 if not self.is_signed_by_cert(self.parent):
894 if debug_verify_chain:
895 logger.debug("verify_chain: NO. {} is not signed by parent {}"
896 .format(self.pretty_name(),
897 self.parent.pretty_name()))
898 self.save_to_file("/tmp/xxx-capture.pem", save_parents=True)
899 raise CertNotSignedByParent("{}: Parent {}, issuer {}"
900 .format(self.pretty_name(),
901 self.parent.pretty_name(),
904 # Confirm that the parent is a CA. Only CAs can be trusted as
906 # Note that trusted roots are not parents, so don't need to be
908 # Ugly - cert objects aren't parsed so we need to read the
909 # extension and hope there are no other basicConstraints
910 if not self.parent.isCA and not (
911 self.parent.get_extension('basicConstraints') == 'CA:TRUE'):
912 logger.warning("verify_chain: cert {}'s parent {} is not a CA"
913 .format(self.pretty_name(), self.parent.pretty_name()))
914 raise CertNotSignedByParent("{}: Parent {} not a CA"
915 .format(self.pretty_name(),
916 self.parent.pretty_name()))
918 # if the parent isn't verified...
919 if debug_verify_chain:
920 logger.debug("verify_chain: .. {}, -> verifying parent {}"
921 .format(self.pretty_name(),
922 self.parent.pretty_name()))
923 self.parent.verify_chain(trusted_certs)
928 def get_extensions(self):
930 # pyOpenSSL does not have a way to get extensions
932 m2x509 = M2Crypto.X509.load_cert_string(self.save_to_string())
933 nb_extensions = m2x509.get_ext_count()
934 logger.debug("X509 had {} extensions".format(nb_extensions))
935 for i in range(nb_extensions):
936 ext = m2x509.get_ext_at(i)
938 (ext.get_name(), ext.get_value(), ext.get_critical(),))
941 def get_data_names(self):
942 return list(self.data.keys())
944 def get_all_datas(self):
945 triples = self.get_extensions()
946 for name in self.get_data_names():
947 triples.append((name, self.get_data(name), 'data',))
951 def get_filename(self):
952 return getattr(self, 'filename', None)
954 def dump(self, *args, **kwargs):
955 print(self.dump_string(*args, **kwargs))
957 def dump_string(self, show_extensions=False):
959 result += "CERTIFICATE for {}\n".format(self.pretty_cert())
960 result += "Issued by {}\n".format(self.get_issuer())
961 filename = self.get_filename()
963 result += "Filename {}\n".format(filename)
965 all_datas = self.get_all_datas()
966 result += " has {} extensions/data attached".format(len(all_datas))
967 for n, v, c in all_datas:
969 result += " data: {}={}\n".format(n, v)
971 result += " ext: {} (crit={})=<<<{}>>>\n".format(n, c, v)