651bbc648ca2d779a338e1ff493d482b077553b0
[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
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         with open(filename, 'w') as output:
186             output.write(self.as_pem())
187         self.filename = filename
188
189     ##
190     # Load the private key from a file. Implicity the private key includes the
191     # public key.
192
193     def load_from_file(self, filename):
194         self.filename = filename
195         buffer = open(filename, 'r').read()
196         self.load_from_string(buffer)
197
198     ##
199     # Load the private key from a string. Implicitly the private key includes
200     # the public key.
201
202     def load_from_string(self, string):
203         import M2Crypto
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))
211         else:
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"))
216
217     ##
218     #  Load the public key from a string. No private key is loaded.
219
220     def load_pubkey_from_file(self, filename):
221         import M2Crypto
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)
226
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()
237         ASN1.set_time(500)
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")
245
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)
250
251         # get the pyopenssl pkey from the pyopenssl x509
252         self.key = pyx509.get_pubkey()
253         self.filename = filename
254
255     ##
256     # Load the public key from a string. No private key is loaded.
257
258     def load_pubkey_from_string(self, string):
259         (f, fn) = tempfile.mkstemp()
260         os.write(f, string)
261         os.close(f)
262         self.load_pubkey_from_file(fn)
263         os.remove(fn)
264
265     ##
266     # Return the private key in PEM format.
267
268     def as_pem(self):
269         return OpenSSL.crypto.dump_privatekey(
270             OpenSSL.crypto.FILETYPE_PEM, self.key)
271
272     ##
273     # Return an M2Crypto key object
274
275     def get_m2_pubkey(self):
276         import M2Crypto
277         if not self.m2key:
278             self.m2key = M2Crypto.EVP.load_key_string(
279                 self.as_pem().encode(encoding="utf-8"))
280         return self.m2key
281
282     ##
283     # Returns a string containing the public key represented by this object.
284
285     def get_pubkey_string(self):
286         m2pkey = self.get_m2_pubkey()
287         return base64.b64encode(m2pkey.as_der())
288
289     ##
290     # Return an OpenSSL pkey object
291
292     def get_openssl_pkey(self):
293         return self.key
294
295     ##
296     # Given another Keypair object, return TRUE if the two keys are the same.
297
298     def is_same(self, pkey):
299         return self.as_pem() == pkey.as_pem()
300
301     def sign_string(self, data):
302         k = self.get_m2_pubkey()
303         k.sign_init()
304         k.sign_update(data)
305         return base64.b64encode(k.sign_final())
306
307     def verify_string(self, data, sig):
308         import M2Crypto
309         k = self.get_m2_pubkey()
310         k.verify_init()
311         k.verify_update(data)
312         return M2Crypto.m2.verify_final(k.ctx, base64.b64decode(sig), k.pkey)
313
314     def compute_hash(self, value):
315         return self.sign_string(str(value))
316
317     # only informative
318     def get_filename(self):
319         return getattr(self, 'filename', None)
320
321     def dump(self, *args, **kwargs):
322         print(self.dump_string(*args, **kwargs))
323
324     def dump_string(self):
325         result = ""
326         result += "KEYPAIR: pubkey={:>40}...".format(self.get_pubkey_string())
327         filename = self.get_filename()
328         if filename:
329             result += "Filename {}\n".format(filename)
330         return result
331
332 ##
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.
337 #
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.
343
344
345 class Certificate:
346     digest = "sha256"
347
348 #    x509 = None
349 #    issuerKey = None
350 #    issuerSubject = None
351 #    parent = None
352     isCA = None  # will be a boolean once set
353
354     separator = "-----parent-----"
355
356     ##
357     # Create a certificate object.
358     #
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
362     #     it's subject name.
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
366
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 !
370         self.x509 = None
371         self.issuerKey = None
372         self.issuerSubject = None
373         self.parent = None
374
375         self.data = {}
376         if create or subject:
377             self.create(lifeDays)
378         if subject:
379             self.set_subject(subject)
380         if string:
381             self.load_from_string(string)
382         if filename:
383             self.load_from_file(filename)
384
385         # Set the CA bit if a value was supplied
386         if isCA is not None:
387             self.set_is_ca(isCA)
388
389     # Create a blank X509 certificate and store it in this object.
390
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
399
400     ##
401     # Given a pyOpenSSL X509 object, store that object inside of this
402     # certificate object.
403
404     def load_from_pyopenssl_x509(self, x509):
405         self.x509 = x509
406
407     ##
408     # Load the certificate from a string
409
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
413         # certs)
414
415         if string is None or string.strip() == "":
416             logger.warning("Empty string in load_from_string")
417             return
418
419         string = string.strip()
420
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-----'\
425                      .format(string)
426
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')
430         if beg > 0:
431             # skipping over non cert beginning
432             string = string[beg:]
433
434         parts = []
435
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-----'
440         else:
441             parts = string.split(Certificate.separator, 1)
442
443         self.x509 = OpenSSL.crypto.load_certificate(
444             OpenSSL.crypto.FILETYPE_PEM, parts[0])
445
446         if self.x509 is None:
447             logger.warning(
448                 "Loaded from string but cert is None: {}".format(string))
449
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])
455
456     ##
457     # Load the certificate from a file
458
459     def load_from_file(self, filename):
460         file = open(filename)
461         string = file.read()
462         self.load_from_string(string)
463         self.filename = filename
464
465     ##
466     # Save the certificate to a string.
467     #
468     # @param save_parents If save_parents==True,
469     # then also save the parent certificates.
470
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")
474             return ""
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)
481         return string
482
483     ##
484     # Save the certificate to a file.
485     # @param save_parents If save_parents==True,
486     #  then also save the parent certificates.
487
488     def save_to_file(self, filename, save_parents=True, filep=None):
489         string = self.save_to_string(save_parents=save_parents)
490         if filep:
491             f = filep
492         else:
493             f = open(filename, 'w')
494         if PY3 and isinstance(string, bytes):
495             string = string.decode()
496         f.write(string)
497         f.close()
498         self.filename = filename
499
500     ##
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)
508         return filename
509
510     ##
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
516
517     def set_issuer(self, key, subject=None, cert=None):
518         self.issuerKey = key
519         if subject:
520             # it's a mistake to use subject and cert params at the same time
521             assert(not cert)
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])
528                 else:
529                     setattr(reqSubject, "CN", subject)
530                 subject = reqSubject
531                 # subject is not valid once req is out of scope, so save req
532                 self.issuerReq = req
533         if cert:
534             # if a cert was supplied, then get the subject from the cert
535             subject = cert.x509.get_subject()
536         assert(subject)
537         self.issuerSubject = subject
538
539     ##
540     # Get the issuer name
541
542     def get_issuer(self, which="CN"):
543         x = self.x509.get_issuer()
544         return getattr(x, which)
545
546     ##
547     # Set the subject name of the certificate
548
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])
555         else:
556             setattr(subj, "CN", name)
557         self.x509.set_subject(subj)
558
559     ##
560     # Get the subject name of the certificate
561
562     def get_subject(self, which="CN"):
563         x = self.x509.get_subject()
564         return getattr(x, which)
565
566     ##
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']
571
572     def filter_chunk(self, chunk):
573         for field in self.pretty_fields:
574             if field in chunk:
575                 return " " + chunk
576
577     def pretty_cert(self):
578         message = "[Cert."
579         x = self.x509.get_subject()
580         ou = getattr(x, "OU")
581         if ou:
582             message += " OU: {}".format(ou)
583         cn = getattr(x, "CN")
584         if cn:
585             message += " CN: {}".format(cn)
586         data = self.get_data(field='subjectAltName')
587         if data:
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])
592             if omitted:
593                 message += "..+{} omitted".format(omitted)
594         message += "]"
595         return message
596
597     def pretty_chain(self):
598         message = "{}".format(self.x509.get_subject())
599         parent = self.parent
600         while parent:
601             message += "->{}".format(parent.x509.get_subject())
602             parent = parent.parent
603         return message
604
605     def pretty_name(self):
606         return self.get_filename() or self.pretty_chain()
607
608     ##
609     # Get the public key of the certificate.
610     #
611     # @param key Keypair object containing the public key
612
613     def set_pubkey(self, key):
614         assert(isinstance(key, Keypair))
615         self.x509.set_pubkey(key.get_openssl_pkey())
616
617     ##
618     # Get the public key of the certificate.
619     # It is returned in the form of a Keypair object.
620
621     def get_pubkey(self):
622         import M2Crypto
623         m2x509 = M2Crypto.X509.load_cert_string(self.save_to_string())
624         pkey = Keypair()
625         pkey.key = self.x509.get_pubkey()
626         pkey.m2key = m2x509.get_pubkey()
627         return pkey
628
629     def set_intermediate_ca(self, val):
630         return self.set_is_ca(val)
631
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):
637         if val is None:
638             return
639
640         if self.isCA is not None:
641             # Can't double set properties
642             raise Exception(
643                 "Cannot set basicConstraints CA:?? more than once. "
644                 "Was {}, trying to set as {}".format(self.isCA, val))
645
646         self.isCA = val
647         if val:
648             self.add_extension('basicConstraints', 1, 'CA:TRUE')
649         else:
650             self.add_extension('basicConstraints', 1, 'CA:FALSE')
651
652     ##
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.
656     #
657     # @param name string containing name of extension
658     # @param value string containing value of the extension
659
660     def add_extension(self, name, critical, value):
661         oldExtVal = None
662         try:
663             oldExtVal = self.get_extension(name)
664         except:
665             # M2Crypto LookupError when the extension isn't there (yet)
666             pass
667
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
674             return
675         # FIXME: What if they are trying to set with a different value?
676         # Is this ever OK? Or should we raise an exception?
677 #        elif oldExtVal:
678 #            raise "Cannot add extension {} which had val {} with new val {}"\
679 #                  .format(name, oldExtVal, value)
680
681         ext = OpenSSL.crypto.X509Extension(name, critical, value)
682         self.x509.add_extensions([ext])
683
684     ##
685     # Get an X509 extension from the certificate
686
687     def get_extension(self, name):
688
689         import M2Crypto
690         if name is None:
691             return None
692
693         certstr = self.save_to_string()
694         if certstr is None or certstr == "":
695             return None
696         # pyOpenSSL does not have a way to get extensions
697         m2x509 = M2Crypto.X509.load_cert_string(certstr)
698         if m2x509 is None:
699             logger.warning("No cert loaded in get_extension")
700             return None
701         if m2x509.get_ext(name) is None:
702             return None
703         value = m2x509.get_ext(name).get_value()
704
705         return value
706
707     ##
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
711     # library.
712
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))
722
723     ##
724     # Return the data string that was previously set with set_data
725
726     def get_data(self, field='subjectAltName'):
727         if field in self.data:
728             return self.data[field]
729
730         try:
731             uri = self.get_extension(field)
732             self.data[field] = uri
733         except LookupError:
734             return None
735
736         return self.data[field]
737
738     ##
739     # Sign the certificate using the issuer private key and issuer subject
740     # previous set with set_issuer().
741
742     def sign(self):
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)
749
750     ##
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.
754
755     def verify(self, pubkey):
756         import M2Crypto
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()
760         # verify it
761         # https://www.openssl.org/docs/man1.1.0/crypto/X509_verify.html
762         # verify returns
763         # 1  if it checks out
764         # 0  if if does not
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))
772         return result
773
774         # XXX alternatively, if openssl has been patched, do the much simpler:
775         # try:
776         #   self.x509.verify(pkey.get_openssl_key())
777         #   return 1
778         # except:
779         #   return 0
780
781     ##
782     # Return True if pkey is identical to the public key that is
783     # contained in the certificate.
784     # @param pkey Keypair object
785
786     def is_pubkey(self, pkey):
787         return self.get_pubkey().is_same(pkey)
788
789     ##
790     # Given a certificate cert, verify that this certificate was signed by the
791     # public key contained in cert. Throw an exception otherwise.
792     #
793     # @param cert certificate object
794
795     def is_signed_by_cert(self, cert):
796         key = cert.get_pubkey()
797         logger.debug("Certificate.is_signed_by_cert -> verify on {}\n"
798                      "with pubkey {}"
799                      .format(self, key))
800         result = self.verify(key)
801         return result
802
803     ##
804     # Set the parent certficiate.
805     #
806     # @param p certificate object.
807
808     def set_parent(self, p):
809         self.parent = p
810
811     ##
812     # Return the certificate object of the parent of this certificate.
813
814     def get_parent(self):
815         return self.parent
816
817     ##
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.
821     #
822     # Verification is a basic recursion: <pre>
823     #     if this_certificate was signed by trusted_certs:
824     #         return
825     #     else
826     #         return verify_chain(parent, trusted_certs)
827     # </pre>
828     #
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.
834     #
835     # @param Trusted_certs is a list of certificates that are trusted.
836     #
837
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.
842
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")
849
850         # if this cert is signed by a trusted_cert, then we are set
851         for i, trusted_cert in enumerate(trusted_certs, 1):
852             logger.debug(5*'-' +
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()))
863                     return trusted_cert
864                 else:
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()))
874             else:
875                 logger.debug("verify_chain: not a direct"
876                              " descendant of trusted root #{}".format(i))
877
878         # if there is no parent, then no way to verify the chain
879         if not self.parent:
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(),
884                                      len(trusted_certs)))
885             raise CertMissingParent("{}: Issuer {} is not "
886                                     "one of the {} trusted roots, "
887                                     "and cert has no parent."
888                                     .format(self.pretty_name(),
889                                             self.get_issuer(),
890                                             len(trusted_certs)))
891
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(),
902                                                 self.get_issuer()))
903
904         # Confirm that the parent is a CA. Only CAs can be trusted as
905         # signers.
906         # Note that trusted roots are not parents, so don't need to be
907         # CAs.
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()))
917
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)
924
925         return
926
927     # more introspection
928     def get_extensions(self):
929         import M2Crypto
930         # pyOpenSSL does not have a way to get extensions
931         triples = []
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)
937             triples.append(
938                 (ext.get_name(), ext.get_value(), ext.get_critical(),))
939         return triples
940
941     def get_data_names(self):
942         return list(self.data.keys())
943
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',))
948         return triples
949
950     # only informative
951     def get_filename(self):
952         return getattr(self, 'filename', None)
953
954     def dump(self, *args, **kwargs):
955         print(self.dump_string(*args, **kwargs))
956
957     def dump_string(self, show_extensions=False):
958         result = ""
959         result += "CERTIFICATE for {}\n".format(self.pretty_cert())
960         result += "Issued by {}\n".format(self.get_issuer())
961         filename = self.get_filename()
962         if filename:
963             result += "Filename {}\n".format(filename)
964         if show_extensions:
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:
968                 if c == 'data':
969                     result += "   data: {}={}\n".format(n, v)
970                 else:
971                     result += "    ext: {} (crit={})=<<<{}>>>\n".format(n, c, v)
972         return result