avoid as much as possible accessing logger through class instances, whenever that...
[sfa.git] / sfa / trust / certificate.py
1 # ----------------------------------------------------------------------
2 # Copyright (c) 2008 Board of Trustees, Princeton University
3 #
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:
10 #
11 # The above copyright notice and this permission notice shall be
12 # included in all copies or substantial portions of the Work.
13 #
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
21 # IN THE WORK.
22 # ----------------------------------------------------------------------
23
24 #
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
32 # in pyOpenSSL.
33 #
34 # This module exports two classes: Keypair and Certificate.
35 ##
36 #
37
38 # Notes on using the openssl command line
39 #
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
45 #
46
47
48 from __future__ import print_function
49
50 import functools
51 import os
52 import tempfile
53 import base64
54 from tempfile import mkstemp
55
56 import OpenSSL
57 # M2Crypto is imported on the fly to minimize crashes
58 # import M2Crypto
59
60 from sfa.util.py23 import PY3
61
62 from sfa.util.faults import (CertExpired, CertMissingParent,
63                              CertNotSignedByParent)
64 from sfa.util.sfalogging import logger
65
66 # this tends to generate quite some logs for little or no value
67 debug_verify_chain = True
68
69 glo_passphrase_callback = None
70
71 ##
72 # A global callback may be implemented for requesting passphrases from the
73 # user. The function will be called with three arguments:
74 #
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
78 #
79 # The callback should return a string containing the passphrase.
80
81
82 def set_passphrase_callback(callback_func):
83     global glo_passphrase_callback
84
85     glo_passphrase_callback = callback_func
86
87 ##
88 # Sets a fixed passphrase.
89
90
91 def set_passphrase(passphrase):
92     set_passphrase_callback(lambda k, s, x: passphrase)
93
94 ##
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.
97
98
99 def test_passphrase(string, passphrase):
100     try:
101         OpenSSL.crypto.load_privatekey(
102             OpenSSL.crypto.FILETYPE_PEM, string, (lambda x: passphrase))
103         return True
104     except:
105         return False
106
107
108 def convert_public_key(key):
109     keyconvert_path = "/usr/bin/keyconvert.py"
110     if not os.path.isfile(keyconvert_path):
111         raise IOError(
112             "Could not find keyconvert in {}".format(keyconvert_path))
113
114     # we can only convert rsa keys
115     if "ssh-dss" in key:
116         raise Exception("keyconvert: dss keys are not supported")
117
118     (ssh_f, ssh_fn) = tempfile.mkstemp()
119     ssl_fn = tempfile.mktemp()
120     os.write(ssh_f, key)
121     os.close(ssh_f)
122
123     cmd = keyconvert_path + " " + ssh_fn + " " + ssl_fn
124     os.system(cmd)
125
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):
130         raise Exception(
131             "generated certificate not found. keyconvert may have failed.")
132
133     k = Keypair()
134     try:
135         k.load_pubkey_from_file(ssl_fn)
136         return k
137     except:
138         logger.log_exc("convert_public_key caught exception")
139         raise
140     finally:
141         # remove the temporary files
142         if os.path.exists(ssh_fn):
143             os.remove(ssh_fn)
144         if os.path.exists(ssl_fn):
145             os.remove(ssl_fn)
146
147 ##
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).
151
152
153 class Keypair:
154     key = None       # public/private keypair
155     m2key = None     # public key (m2crypto format)
156
157     ##
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
163
164     def __init__(self, create=False, string=None, filename=None):
165         if create:
166             self.create()
167         if string:
168             self.load_from_string(string)
169         if filename:
170             self.load_from_file(filename)
171
172     ##
173     # Create a RSA public/private key pair and store it inside the keypair
174     # object
175
176     def create(self):
177         self.key = OpenSSL.crypto.PKey()
178         self.key.generate_key(OpenSSL.crypto.TYPE_RSA, 2048)
179
180     ##
181     # Save the private key to a file
182     # @param filename name of file to store the keypair in
183
184     def save_to_file(self, filename):
185         open(filename, 'w').write(self.as_pem())
186         self.filename = filename
187
188     ##
189     # Load the private key from a file. Implicity the private key includes the
190     # public key.
191
192     def load_from_file(self, filename):
193         self.filename = filename
194         buffer = open(filename, 'r').read()
195         self.load_from_string(buffer)
196
197     ##
198     # Load the private key from a string. Implicitly the private key includes
199     # the public key.
200
201     def load_from_string(self, string):
202         import M2Crypto
203         if glo_passphrase_callback:
204             self.key = OpenSSL.crypto.load_privatekey(
205                 OpenSSL.crypto.FILETYPE_PEM, string,
206                 functools.partial(glo_passphrase_callback, self, string))
207             self.m2key = M2Crypto.EVP.load_key_string(
208                 string, functools.partial(glo_passphrase_callback,
209                                           self, string))
210         else:
211             self.key = OpenSSL.crypto.load_privatekey(
212                 OpenSSL.crypto.FILETYPE_PEM, string)
213             self.m2key = M2Crypto.EVP.load_key_string(string)
214
215     ##
216     #  Load the public key from a string. No private key is loaded.
217
218     def load_pubkey_from_file(self, filename):
219         import M2Crypto
220         # load the m2 public key
221         m2rsakey = M2Crypto.RSA.load_pub_key(filename)
222         self.m2key = M2Crypto.EVP.PKey()
223         self.m2key.assign_rsa(m2rsakey)
224
225         # create an m2 x509 cert
226         m2name = M2Crypto.X509.X509_Name()
227         m2name.add_entry_by_txt(field="CN", type=0x1001,
228                                 entry="junk", len=-1, loc=-1, set=0)
229         m2x509 = M2Crypto.X509.X509()
230         m2x509.set_pubkey(self.m2key)
231         m2x509.set_serial_number(0)
232         m2x509.set_issuer_name(m2name)
233         m2x509.set_subject_name(m2name)
234         ASN1 = M2Crypto.ASN1.ASN1_UTCTIME()
235         ASN1.set_time(500)
236         m2x509.set_not_before(ASN1)
237         m2x509.set_not_after(ASN1)
238         # x509v3 so it can have extensions
239         # prob not necc since this cert itself is junk but still...
240         m2x509.set_version(2)
241         junk_key = Keypair(create=True)
242         m2x509.sign(pkey=junk_key.get_m2_pubkey(), md="sha1")
243
244         # convert the m2 x509 cert to a pyopenssl x509
245         m2pem = m2x509.as_pem()
246         pyx509 = OpenSSL.crypto.load_certificate(
247             OpenSSL.crypto.FILETYPE_PEM, m2pem)
248
249         # get the pyopenssl pkey from the pyopenssl x509
250         self.key = pyx509.get_pubkey()
251         self.filename = filename
252
253     ##
254     # Load the public key from a string. No private key is loaded.
255
256     def load_pubkey_from_string(self, string):
257         (f, fn) = tempfile.mkstemp()
258         os.write(f, string)
259         os.close(f)
260         self.load_pubkey_from_file(fn)
261         os.remove(fn)
262
263     ##
264     # Return the private key in PEM format.
265
266     def as_pem(self):
267         return OpenSSL.crypto.dump_privatekey(
268             OpenSSL.crypto.FILETYPE_PEM, self.key)
269
270     ##
271     # Return an M2Crypto key object
272
273     def get_m2_pubkey(self):
274         import M2Crypto
275         if not self.m2key:
276             self.m2key = M2Crypto.EVP.load_key_string(self.as_pem())
277         return self.m2key
278
279     ##
280     # Returns a string containing the public key represented by this object.
281
282     def get_pubkey_string(self):
283         m2pkey = self.get_m2_pubkey()
284         return base64.b64encode(m2pkey.as_der())
285
286     ##
287     # Return an OpenSSL pkey object
288
289     def get_openssl_pkey(self):
290         return self.key
291
292     ##
293     # Given another Keypair object, return TRUE if the two keys are the same.
294
295     def is_same(self, pkey):
296         return self.as_pem() == pkey.as_pem()
297
298     def sign_string(self, data):
299         k = self.get_m2_pubkey()
300         k.sign_init()
301         k.sign_update(data)
302         return base64.b64encode(k.sign_final())
303
304     def verify_string(self, data, sig):
305         import M2Crypto
306         k = self.get_m2_pubkey()
307         k.verify_init()
308         k.verify_update(data)
309         return M2Crypto.m2.verify_final(k.ctx, base64.b64decode(sig), k.pkey)
310
311     def compute_hash(self, value):
312         return self.sign_string(str(value))
313
314     # only informative
315     def get_filename(self):
316         return getattr(self, 'filename', None)
317
318     def dump(self, *args, **kwargs):
319         print(self.dump_string(*args, **kwargs))
320
321     def dump_string(self):
322         result = ""
323         result += "KEYPAIR: pubkey={:>40}...".format(self.get_pubkey_string())
324         filename = self.get_filename()
325         if filename:
326             result += "Filename {}\n".format(filename)
327         return result
328
329 ##
330 # The certificate class implements a general purpose X509 certificate, making
331 # use of the appropriate pyOpenSSL or M2Crypto abstractions. It also adds
332 # several addition features, such as the ability to maintain a chain of
333 # parent certificates, and storage of application-specific data.
334 #
335 # Certificates include the ability to maintain a chain of parents. Each
336 # certificate includes a pointer to it's parent certificate. When loaded
337 # from a file or a string, the parent chain will be automatically loaded.
338 # When saving a certificate to a file or a string, the caller can choose
339 # whether to save the parent certificates as well.
340
341
342 class Certificate:
343     digest = "sha256"
344
345 #    x509 = None
346 #    issuerKey = None
347 #    issuerSubject = None
348 #    parent = None
349     isCA = None  # will be a boolean once set
350
351     separator = "-----parent-----"
352
353     ##
354     # Create a certificate object.
355     #
356     # @param lifeDays life of cert in days - default is 1825==5 years
357     # @param create If create==True, then also create a blank X509 certificate.
358     # @param subject If subject!=None, then create a blank certificate and set
359     #     it's subject name.
360     # @param string If string!=None, load the certficate from the string.
361     # @param filename If filename!=None, load the certficiate from the file.
362     # @param isCA If !=None, set whether this cert is for a CA
363
364     def __init__(self, lifeDays=1825, create=False, subject=None, string=None,
365                  filename=None, isCA=None):
366         # these used to be defined in the class !
367         self.x509 = None
368         self.issuerKey = None
369         self.issuerSubject = None
370         self.parent = None
371
372         self.data = {}
373         if create or subject:
374             self.create(lifeDays)
375         if subject:
376             self.set_subject(subject)
377         if string:
378             self.load_from_string(string)
379         if filename:
380             self.load_from_file(filename)
381
382         # Set the CA bit if a value was supplied
383         if isCA is not None:
384             self.set_is_ca(isCA)
385
386     # Create a blank X509 certificate and store it in this object.
387
388     def create(self, lifeDays=1825):
389         self.x509 = OpenSSL.crypto.X509()
390         # FIXME: Use different serial #s
391         self.x509.set_serial_number(3)
392         self.x509.gmtime_adj_notBefore(0)  # 0 means now
393         self.x509.gmtime_adj_notAfter(
394             lifeDays * 60 * 60 * 24)  # five years is default
395         self.x509.set_version(2)  # x509v3 so it can have extensions
396
397     ##
398     # Given a pyOpenSSL X509 object, store that object inside of this
399     # certificate object.
400
401     def load_from_pyopenssl_x509(self, x509):
402         self.x509 = x509
403
404     ##
405     # Load the certificate from a string
406
407     def load_from_string(self, string):
408         # if it is a chain of multiple certs, then split off the first one and
409         # load it (support for the ---parent--- tag as well as normal chained
410         # certs)
411
412         if string is None or string.strip() == "":
413             logger.warning("Empty string in load_from_string")
414             return
415
416         string = string.strip()
417
418         # If it's not in proper PEM format, wrap it
419         if string.count('-----BEGIN CERTIFICATE') == 0:
420             string = '-----BEGIN CERTIFICATE-----'\
421                      '\n{}\n-----END CERTIFICATE-----'\
422                      .format(string)
423
424         # If there is a PEM cert in there, but there is some other text first
425         # such as the text of the certificate, skip the text
426         beg = string.find('-----BEGIN CERTIFICATE')
427         if beg > 0:
428             # skipping over non cert beginning
429             string = string[beg:]
430
431         parts = []
432
433         if string.count('-----BEGIN CERTIFICATE-----') > 1 and \
434                 string.count(Certificate.separator) == 0:
435             parts = string.split('-----END CERTIFICATE-----', 1)
436             parts[0] += '-----END CERTIFICATE-----'
437         else:
438             parts = string.split(Certificate.separator, 1)
439
440         self.x509 = OpenSSL.crypto.load_certificate(
441             OpenSSL.crypto.FILETYPE_PEM, parts[0])
442
443         if self.x509 is None:
444             logger.warning(
445                 "Loaded from string but cert is None: {}".format(string))
446
447         # if there are more certs, then create a parent and let the parent load
448         # itself from the remainder of the string
449         if len(parts) > 1 and parts[1] != '':
450             self.parent = self.__class__()
451             self.parent.load_from_string(parts[1])
452
453     ##
454     # Load the certificate from a file
455
456     def load_from_file(self, filename):
457         file = open(filename)
458         string = file.read()
459         self.load_from_string(string)
460         self.filename = filename
461
462     ##
463     # Save the certificate to a string.
464     #
465     # @param save_parents If save_parents==True,
466     # then also save the parent certificates.
467
468     def save_to_string(self, save_parents=True):
469         if self.x509 is None:
470             logger.warning("None cert in certificate.save_to_string")
471             return ""
472         string = OpenSSL.crypto.dump_certificate(
473             OpenSSL.crypto.FILETYPE_PEM, self.x509)
474         if PY3 and isinstance(string, bytes):
475             string = string.decode()
476         if save_parents and self.parent:
477             string = string + self.parent.save_to_string(save_parents)
478         return string
479
480     ##
481     # Save the certificate to a file.
482     # @param save_parents If save_parents==True,
483     #  then also save the parent certificates.
484
485     def save_to_file(self, filename, save_parents=True, filep=None):
486         string = self.save_to_string(save_parents=save_parents)
487         if filep:
488             f = filep
489         else:
490             f = open(filename, 'w')
491         if PY3 and isinstance(string, bytes):
492             string = string.decode()
493         f.write(string)
494         f.close()
495         self.filename = filename
496
497     ##
498     # Save the certificate to a random file in /tmp/
499     # @param save_parents If save_parents==True,
500     #  then also save the parent certificates.
501     def save_to_random_tmp_file(self, save_parents=True):
502         fp, filename = mkstemp(suffix='cert', text=True)
503         fp = os.fdopen(fp, "w")
504         self.save_to_file(filename, save_parents=True, filep=fp)
505         return filename
506
507     ##
508     # Sets the issuer private key and name
509     # @param key Keypair object containing the private key of the issuer
510     # @param subject String containing the name of the issuer
511     # @param cert (optional)
512     #  Certificate object containing the name of the issuer
513
514     def set_issuer(self, key, subject=None, cert=None):
515         self.issuerKey = key
516         if subject:
517             # it's a mistake to use subject and cert params at the same time
518             assert(not cert)
519             if isinstance(subject, dict) or isinstance(subject, str):
520                 req = OpenSSL.crypto.X509Req()
521                 reqSubject = req.get_subject()
522                 if isinstance(subject, dict):
523                     for key in reqSubject.keys():
524                         setattr(reqSubject, key, subject[key])
525                 else:
526                     setattr(reqSubject, "CN", subject)
527                 subject = reqSubject
528                 # subject is not valid once req is out of scope, so save req
529                 self.issuerReq = req
530         if cert:
531             # if a cert was supplied, then get the subject from the cert
532             subject = cert.x509.get_subject()
533         assert(subject)
534         self.issuerSubject = subject
535
536     ##
537     # Get the issuer name
538
539     def get_issuer(self, which="CN"):
540         x = self.x509.get_issuer()
541         return getattr(x, which)
542
543     ##
544     # Set the subject name of the certificate
545
546     def set_subject(self, name):
547         req = OpenSSL.crypto.X509Req()
548         subj = req.get_subject()
549         if isinstance(name, dict):
550             for key in name.keys():
551                 setattr(subj, key, name[key])
552         else:
553             setattr(subj, "CN", name)
554         self.x509.set_subject(subj)
555
556     ##
557     # Get the subject name of the certificate
558
559     def get_subject(self, which="CN"):
560         x = self.x509.get_subject()
561         return getattr(x, which)
562
563     ##
564     # Get a pretty-print subject name of the certificate
565     # let's try to make this a little more usable as is makes logs hairy
566     # FIXME: Consider adding 'urn:publicid' and 'uuid' back for GENI?
567     pretty_fields = ['email']
568
569     def filter_chunk(self, chunk):
570         for field in self.pretty_fields:
571             if field in chunk:
572                 return " " + chunk
573
574     def pretty_cert(self):
575         message = "[Cert."
576         x = self.x509.get_subject()
577         ou = getattr(x, "OU")
578         if ou:
579             message += " OU: {}".format(ou)
580         cn = getattr(x, "CN")
581         if cn:
582             message += " CN: {}".format(cn)
583         data = self.get_data(field='subjectAltName')
584         if data:
585             message += " SubjectAltName:"
586             counter = 0
587             filtered = [self.filter_chunk(chunk) for chunk in data.split()]
588             message += " ".join([f for f in filtered if f])
589             omitted = len([f for f in filtered if not f])
590             if omitted:
591                 message += "..+{} omitted".format(omitted)
592         message += "]"
593         return message
594
595     def pretty_chain(self):
596         message = "{}".format(self.x509.get_subject())
597         parent = self.parent
598         while parent:
599             message += "->{}".format(parent.x509.get_subject())
600             parent = parent.parent
601         return message
602
603     def pretty_name(self):
604         return self.get_filename() or self.pretty_chain()
605
606     ##
607     # Get the public key of the certificate.
608     #
609     # @param key Keypair object containing the public key
610
611     def set_pubkey(self, key):
612         assert(isinstance(key, Keypair))
613         self.x509.set_pubkey(key.get_openssl_pkey())
614
615     ##
616     # Get the public key of the certificate.
617     # It is returned in the form of a Keypair object.
618
619     def get_pubkey(self):
620         import M2Crypto
621         m2x509 = M2Crypto.X509.load_cert_string(self.save_to_string())
622         pkey = Keypair()
623         pkey.key = self.x509.get_pubkey()
624         pkey.m2key = m2x509.get_pubkey()
625         return pkey
626
627     def set_intermediate_ca(self, val):
628         return self.set_is_ca(val)
629
630     # Set whether this cert is for a CA.
631     # All signers and only signers should be CAs.
632     # The local member starts unset, letting us check that you only set it once
633     # @param val Boolean indicating whether this cert is for a CA
634     def set_is_ca(self, val):
635         if val is None:
636             return
637
638         if self.isCA is not None:
639             # Can't double set properties
640             raise Exception(
641                 "Cannot set basicConstraints CA:?? more than once. "
642                 "Was {}, trying to set as {}".format(self.isCA, val))
643
644         self.isCA = val
645         if val:
646             self.add_extension('basicConstraints', 1, 'CA:TRUE')
647         else:
648             self.add_extension('basicConstraints', 1, 'CA:FALSE')
649
650     ##
651     # Add an X509 extension to the certificate. Add_extension can only
652     # be called once for a particular extension name, due to
653     # limitations in the underlying library.
654     #
655     # @param name string containing name of extension
656     # @param value string containing value of the extension
657
658     def add_extension(self, name, critical, value):
659         oldExtVal = None
660         try:
661             oldExtVal = self.get_extension(name)
662         except:
663             # M2Crypto LookupError when the extension isn't there (yet)
664             pass
665
666         # This code limits you from adding the extension with the same value
667         # The method comment says you shouldn't do this with the same name
668         # But actually it (m2crypto) appears to allow you to do this.
669         if oldExtVal and oldExtVal == value:
670             # don't add this extension again
671             # just do nothing as here
672             return
673         # FIXME: What if they are trying to set with a different value?
674         # Is this ever OK? Or should we raise an exception?
675 #        elif oldExtVal:
676 #            raise "Cannot add extension {} which had val {} with new val {}"\
677 #                  .format(name, oldExtVal, value)
678
679         ext = OpenSSL.crypto.X509Extension(name, critical, value)
680         self.x509.add_extensions([ext])
681
682     ##
683     # Get an X509 extension from the certificate
684
685     def get_extension(self, name):
686
687         import M2Crypto
688         if name is None:
689             return None
690
691         certstr = self.save_to_string()
692         if certstr is None or certstr == "":
693             return None
694         # pyOpenSSL does not have a way to get extensions
695         m2x509 = M2Crypto.X509.load_cert_string(certstr)
696         if m2x509 is None:
697             logger.warning("No cert loaded in get_extension")
698             return None
699         if m2x509.get_ext(name) is None:
700             return None
701         value = m2x509.get_ext(name).get_value()
702
703         return value
704
705     ##
706     # Set_data is a wrapper around add_extension. It stores the
707     # parameter str in the X509 subject_alt_name extension. Set_data
708     # can only be called once, due to limitations in the underlying
709     # library.
710
711     def set_data(self, string, field='subjectAltName'):
712         # pyOpenSSL only allows us to add extensions, so if we try to set the
713         # same extension more than once, it will not work
714         if field in self.data:
715             raise Exception("Cannot set {} more than once".format(field))
716         self.data[field] = string
717         self.add_extension(field, 0, string)
718
719     ##
720     # Return the data string that was previously set with set_data
721
722     def get_data(self, field='subjectAltName'):
723         if field in self.data:
724             return self.data[field]
725
726         try:
727             uri = self.get_extension(field)
728             self.data[field] = uri
729         except LookupError:
730             return None
731
732         return self.data[field]
733
734     ##
735     # Sign the certificate using the issuer private key and issuer subject
736     # previous set with set_issuer().
737
738     def sign(self):
739         logger.debug('certificate.sign')
740         assert self.x509 is not None
741         assert self.issuerSubject is not None
742         assert self.issuerKey is not None
743         self.x509.set_issuer(self.issuerSubject)
744         self.x509.sign(self.issuerKey.get_openssl_pkey(), self.digest)
745
746     ##
747     # Verify the authenticity of a certificate.
748     # @param pkey is a Keypair object representing a public key. If Pkey
749     #     did not sign the certificate, then an exception will be thrown.
750
751     def verify(self, pubkey):
752         import M2Crypto
753         # pyOpenSSL does not have a way to verify signatures
754         m2x509 = M2Crypto.X509.load_cert_string(self.save_to_string())
755         m2pubkey = pubkey.get_m2_pubkey()
756         # verify it
757         # https://www.openssl.org/docs/man1.1.0/crypto/X509_verify.html
758         # verify returns
759         # 1  if it checks out
760         # 0  if if does not
761         # -1 if it could not be checked 'for some reason'
762         m2result = m2x509.verify(m2pubkey)
763         result = m2result == 1
764         if debug_verify_chain:
765             logger.debug("Certificate.verify: <- {} (m2={}) ({} x {})"
766                          .format(result, m2result,
767                                  self.pretty_cert(), m2pubkey))
768         return result
769
770         # XXX alternatively, if openssl has been patched, do the much simpler:
771         # try:
772         #   self.x509.verify(pkey.get_openssl_key())
773         #   return 1
774         # except:
775         #   return 0
776
777     ##
778     # Return True if pkey is identical to the public key that is
779     # contained in the certificate.
780     # @param pkey Keypair object
781
782     def is_pubkey(self, pkey):
783         return self.get_pubkey().is_same(pkey)
784
785     ##
786     # Given a certificate cert, verify that this certificate was signed by the
787     # public key contained in cert. Throw an exception otherwise.
788     #
789     # @param cert certificate object
790
791     def is_signed_by_cert(self, cert):
792         k = cert.get_pubkey()
793         logger.debug("Certificate.is_signed_by_cert -> verify on {}\n"
794                      "with pubkey {}"
795                      .format(self, k))
796         result = self.verify(k)
797         return result
798
799     ##
800     # Set the parent certficiate.
801     #
802     # @param p certificate object.
803
804     def set_parent(self, p):
805         self.parent = p
806
807     ##
808     # Return the certificate object of the parent of this certificate.
809
810     def get_parent(self):
811         return self.parent
812
813     ##
814     # Verification examines a chain of certificates to ensure that each parent
815     # signs the child, and that some certificate in the chain is signed by a
816     # trusted certificate.
817     #
818     # Verification is a basic recursion: <pre>
819     #     if this_certificate was signed by trusted_certs:
820     #         return
821     #     else
822     #         return verify_chain(parent, trusted_certs)
823     # </pre>
824     #
825     # At each recursion, the parent is tested to ensure that it did sign the
826     # child. If a parent did not sign a child, then an exception is thrown. If
827     # the bottom of the recursion is reached and the certificate does not match
828     # a trusted root, then an exception is thrown.
829     # Also require that parents are CAs.
830     #
831     # @param Trusted_certs is a list of certificates that are trusted.
832     #
833
834     def verify_chain(self, trusted_certs=None):
835         # Verify a chain of certificates. Each certificate must be signed by
836         # the public key contained in it's parent. The chain is recursed
837         # until a certificate is found that is signed by a trusted root.
838
839         logger.debug("Certificate.verify_chain {}".format(self.pretty_name()))
840         # verify expiration time
841         if self.x509.has_expired():
842             if debug_verify_chain:
843                 logger.debug("verify_chain: NO, Certificate {} has expired"
844                              .format(self.pretty_cert()))
845             raise CertExpired(self.pretty_cert(), "client cert")
846
847         # if this cert is signed by a trusted_cert, then we are set
848         for i, trusted_cert in enumerate(trusted_certs, 1):
849             logger.debug("Certificate.verify_chain - trying trusted #{} : {}"
850                          .format(i, trusted_cert.pretty_name()))
851             if self.is_signed_by_cert(trusted_cert):
852                 # verify expiration of trusted_cert ?
853                 if not trusted_cert.x509.has_expired():
854                     if debug_verify_chain:
855                         logger.debug("verify_chain: YES."
856                                      " Cert {} signed by trusted cert {}"
857                                      .format(self.pretty_name(),
858                                              trusted_cert.pretty_name()))
859                     return trusted_cert
860                 else:
861                     if debug_verify_chain:
862                         logger.debug("verify_chain: NO. Cert {} "
863                                      "is signed by trusted_cert {}, "
864                                      "but that signer is expired..."
865                                      .format(self.pretty_cert(),
866                                              trusted_cert.pretty_cert()))
867                     raise CertExpired("{} signer trusted_cert {}"
868                                       .format(self.pretty_name(),
869                                               trusted_cert.pretty_name()))
870             else:
871                 logger.debug("verify_chain: not a direct"
872                              " descendant of trusted root #{}".format(i))
873
874         # if there is no parent, then no way to verify the chain
875         if not self.parent:
876             if debug_verify_chain:
877                 logger.debug("verify_chain: NO. {} has no parent "
878                              "and issuer {} is not in {} trusted roots"
879                              .format(self.pretty_name(), self.get_issuer(),
880                                      len(trusted_certs)))
881             raise CertMissingParent("{}: Issuer {} is not "
882                                     "one of the {} trusted roots, "
883                                     "and cert has no parent."
884                                     .format(self.pretty_name(),
885                                             self.get_issuer(),
886                                             len(trusted_certs)))
887
888         # if it wasn't signed by the parent...
889         if not self.is_signed_by_cert(self.parent):
890             if debug_verify_chain:
891                 logger.debug("verify_chain: NO. {} is not signed by parent {}"
892                              .format(self.pretty_name(),
893                                      self.parent.pretty_name()))
894                 self.save_to_file("/tmp/xxx-capture.pem", save_parents=True)
895             raise CertNotSignedByParent("{}: Parent {}, issuer {}"
896                                         .format(self.pretty_name(),
897                                                 self.parent.pretty_name(),
898                                                 self.get_issuer()))
899
900         # Confirm that the parent is a CA. Only CAs can be trusted as
901         # signers.
902         # Note that trusted roots are not parents, so don't need to be
903         # CAs.
904         # Ugly - cert objects aren't parsed so we need to read the
905         # extension and hope there are no other basicConstraints
906         if not self.parent.isCA and not (
907                 self.parent.get_extension('basicConstraints') == 'CA:TRUE'):
908             logger.warning("verify_chain: cert {}'s parent {} is not a CA"
909                             .format(self.pretty_name(), self.parent.pretty_name()))
910             raise CertNotSignedByParent("{}: Parent {} not a CA"
911                                         .format(self.pretty_name(),
912                                                 self.parent.pretty_name()))
913
914         # if the parent isn't verified...
915         if debug_verify_chain:
916             logger.debug("verify_chain: .. {}, -> verifying parent {}"
917                          .format(self.pretty_name(),
918                                  self.parent.pretty_name()))
919         self.parent.verify_chain(trusted_certs)
920
921         return
922
923     # more introspection
924     def get_extensions(self):
925         import M2Crypto
926         # pyOpenSSL does not have a way to get extensions
927         triples = []
928         m2x509 = M2Crypto.X509.load_cert_string(self.save_to_string())
929         nb_extensions = m2x509.get_ext_count()
930         logger.debug("X509 had {} extensions".format(nb_extensions))
931         for i in range(nb_extensions):
932             ext = m2x509.get_ext_at(i)
933             triples.append(
934                 (ext.get_name(), ext.get_value(), ext.get_critical(),))
935         return triples
936
937     def get_data_names(self):
938         return self.data.keys()
939
940     def get_all_datas(self):
941         triples = self.get_extensions()
942         for name in self.get_data_names():
943             triples.append((name, self.get_data(name), 'data',))
944         return triples
945
946     # only informative
947     def get_filename(self):
948         return getattr(self, 'filename', None)
949
950     def dump(self, *args, **kwargs):
951         print(self.dump_string(*args, **kwargs))
952
953     def dump_string(self, show_extensions=False):
954         result = ""
955         result += "CERTIFICATE for {}\n".format(self.pretty_cert())
956         result += "Issued by {}\n".format(self.get_issuer())
957         filename = self.get_filename()
958         if filename:
959             result += "Filename {}\n".format(filename)
960         if show_extensions:
961             all_datas = self.get_all_datas()
962             result += " has {} extensions/data attached".format(len(all_datas))
963             for n, v, c in all_datas:
964                 if c == 'data':
965                     result += "   data: {}={}\n".format(n, v)
966                 else:
967                     result += "    ext: {} (crit={})=<<<{}>>>\n".format(n, c, v)
968         return result