documented cert module
[sfa.git] / util / cert.py
1 ##
2 # Geniwrapper uses two crypto libraries: pyOpenSSL and M2Crypto to implement
3 # the necessary crypto functionality. Ideally just one of these libraries
4 # would be used, but unfortunately each of these libraries is independently
5 # lacking. The pyOpenSSL library is missing many necessary functions, and
6 # the M2Crypto library has crashed inside of some of the functions. The
7 # design decision is to use pyOpenSSL whenever possible as it seems more
8 # stable, and only use M2Crypto for those functions that are not possible
9 # in pyOpenSSL.
10 #
11 # This module exports two classes: Keypair and Certificate.
12 ##
13
14 import os
15 import tempfile
16 from OpenSSL import crypto
17 import M2Crypto
18 from M2Crypto import X509
19 from M2Crypto import EVP
20
21 from excep import *
22
23 ##
24 # Public-private key pairs are implemented by the Keypair class.
25 # A Keypair object may represent both a public and private key pair, or it
26 # may represent only a public key (this usage is consistent with OpenSSL).
27
28 class Keypair:
29    key = None       # public/private keypair
30    m2key = None     # public key (m2crypto format)
31
32    ##
33    # Creates a Keypair object
34    # @param create If create==True, creates a new public/private key and
35    #     stores it in the object
36    # @param string If string!=None, load the keypair from the string (PEM)
37    # @param filename If filename!=None, load the keypair from the file
38
39    def __init__(self, create=False, string=None, filename=None):
40       if create:
41          self.create()
42       if string:
43          self.load_from_string(string)
44       if filename:
45          self.load_from_file(filename)
46
47    ##
48    # Create a RSA public/private key pair and store it inside the keypair object
49
50    def create(self):\r
51       self.key = crypto.PKey()
52       self.key.generate_key(crypto.TYPE_RSA, 1024)
53
54    ##
55    # Save the private key to a file
56    # @param filename name of file to store the keypair in
57
58    def save_to_file(self, filename):
59       open(filename, 'w').write(self.as_pem())
60
61    ##
62    # Load the private key from a file. Implicity the private key includes the public key.
63
64    def load_from_file(self, filename):
65       buffer = open(filename, 'r').read()
66       self.load_from_string(buffer)
67
68    ##
69    # Load the private key from a string. Implicitly the private key includes the public key.
70
71    def load_from_string(self, string):
72       self.key = crypto.load_privatekey(crypto.FILETYPE_PEM, string)
73       self.m2key = M2Crypto.EVP.load_key_string(string)
74
75    ##
76    #  Load the public key from a string. No private key is loaded. 
77
78    def load_pubkey_from_file(self, filename):
79       # load the m2 public key
80       m2rsakey = M2Crypto.RSA.load_pub_key(filename)
81       self.m2key = M2Crypto.EVP.PKey()
82       self.m2key.assign_rsa(m2rsakey)
83
84       # create an m2 x509 cert
85       m2name = M2Crypto.X509.X509_Name()
86       m2name.add_entry_by_txt(field="CN", type=0x1001, entry="junk", len=-1, loc=-1, set=0)
87       m2x509 = M2Crypto.X509.X509()
88       m2x509.set_pubkey(self.m2key)
89       m2x509.set_serial_number(0)
90       m2x509.set_issuer_name(m2name)
91       m2x509.set_subject_name(m2name)
92       ASN1 = M2Crypto.ASN1.ASN1_UTCTIME()
93       ASN1.set_time(500)
94       m2x509.set_not_before(ASN1)
95       m2x509.set_not_after(ASN1)
96       junk_key = Keypair(create=True)
97       m2x509.sign(pkey=junk_key.get_m2_pkey(), md="sha1")
98
99       # convert the m2 x509 cert to a pyopenssl x509
100       m2pem = m2x509.as_pem()
101       pyx509 = crypto.load_certificate(crypto.FILETYPE_PEM, m2pem)
102
103       # get the pyopenssl pkey from the pyopenssl x509
104       self.key = pyx509.get_pubkey()
105
106    ##
107    # Load the public key from a string. No private key is loaded.
108
109    def load_pubkey_from_string(self, string):
110       (f, fn) = tempfile.mkstemp()
111       os.write(f, string)
112       os.close(f)
113       self.load_pubkey_from_file(fn)
114       os.remove(fn)
115
116    ##
117    # Return the private key in PEM format.
118
119    def as_pem(self):
120       return crypto.dump_privatekey(crypto.FILETYPE_PEM, self.key)
121
122    ##
123    # Return an OpenSSL pkey object
124
125    def get_m2_pkey(self):
126       if not self.m2key:
127          self.m2key = M2Crypto.EVP.load_key_string(self.as_pem())
128       return self.m2key
129
130    ##
131    # Given another Keypair object, return TRUE if the two keys are the same.
132
133    def get_openssl_pkey(self):
134       return self.key
135
136    def is_same(self, pkey):
137       return self.as_pem() == pkey.as_pem()
138
139 ##
140 # The certificate class implements a general purpose X509 certificate, making
141 # use of the appropriate pyOpenSSL or M2Crypto abstractions. It also adds
142 # several addition features, such as the ability to maintain a chain of
143 # parent certificates, and storage of application-specific data.
144 #
145 # Certificates include the ability to maintain a chain of parents. Each\r
146 # certificate includes a pointer to it's parent certificate. When loaded\r
147 # from a file or a string, the parent chain will be automatically loaded.\r
148 # When saving a certificate to a file or a string, the caller can choose\r
149 # whether to save the parent certificates as well.\r
150
151 class Certificate:
152    digest = "md5"
153
154    data = None
155    cert = None
156    issuerKey = None
157    issuerSubject = None
158    parent = None
159
160    ##
161    # Create a certificate object.
162    #\r
163    # @param create If create==True, then also create a blank X509 certificate.\r
164    # @param subject If subject!=None, then create a blank certificate and set\r
165    #     it's subject name.\r
166    # @param string If string!=None, load the certficate from the string.\r
167    # @param filename If filename!=None, load the certficiate from the file.\r
168
169    def __init__(self, create=False, subject=None, string=None, filename=None):
170        if create or subject:
171            self.create()
172        if subject:
173            self.set_subject(subject)
174        if string:
175            self.load_from_string(string)
176        if filename:
177            self.load_from_file(filename)
178
179    ##
180    # Create a blank X509 certificate and store it in this object.
181
182    def create(self):
183        self.cert = crypto.X509()
184        self.cert.set_serial_number(1)
185        self.cert.gmtime_adj_notBefore(0)
186        self.cert.gmtime_adj_notAfter(60*60*24*365*5) # five years
187
188    ##
189    # Given a pyOpenSSL X509 object, store that object inside of this
190    # certificate object.
191
192    def load_from_pyopenssl_x509(self, x509):
193        self.cert = x509
194
195    ##
196    # Return another instance of the same class.
197    # XXX: probably will be deleted, can use cls() function instead
198
199    def create_similar(self):
200        return Certificate()
201
202    ##
203    # Load the certificate from a string
204
205    def load_from_string(self, string):
206        # if it is a chain of multiple certs, then split off the first one and
207        # load it
208        parts = string.split("-----parent-----", 1)
209        self.cert = crypto.load_certificate(crypto.FILETYPE_PEM, parts[0])
210
211        # if there are more certs, then create a parent and let the parent load
212        # itself from the remainder of the string
213        if len(parts) > 1:
214            self.parent = self.create_similar()
215            self.parent.load_from_string(parts[1])
216
217    ##
218    # Load the certificate from a file
219
220    def load_from_file(self, filename):
221        file = open(filename)
222        string = file.read()
223        self.load_from_string(string)
224
225    ##
226    # Save the certificate to a string.
227    #
228    # @param save_parents If save_parents==True, then also save the parent certificates.
229
230    def save_to_string(self, save_parents=False):
231        string = crypto.dump_certificate(crypto.FILETYPE_PEM, self.cert)
232        if save_parents and self.parent:
233           string = string + "-----parent-----" + self.parent.save_to_string(save_parents)
234        return string
235
236    ##
237    # Save the certificate to a file.
238    # @param save_parents If save_parents==True, then also save the parent certificates.
239
240    def save_to_file(self, filename, save_parents=False):
241        string = self.save_to_string(save_parents=save_parents)
242        open(filename, 'w').write(string)
243
244    ##
245    # Sets the issuer private key and name
246    # @param key Keypair object containing the private key of the issuer
247    # @param subject String containing the name of the issuer
248    # @param cert (optional) Certificate object containing the name of the issuer
249
250    def set_issuer(self, key, subject=None, cert=None):
251        self.issuerKey = key
252        if subject:
253           # it's a mistake to use subject and cert params at the same time
254           assert(not cert)
255           if isinstance(subject, dict) or isinstance(subject, str):
256              req = crypto.X509Req()
257              reqSubject = req.get_subject()
258              if (isinstance(subject, dict)):
259                 for key in reqSubject.keys():
260                     setattr(reqSubject, key, name[key])
261              else:
262                 setattr(reqSubject, "CN", subject)
263              subject = reqSubject
264              # subject is not valid once req is out of scope, so save req
265              self.issuerReq = req
266        if cert:
267           # if a cert was supplied, then get the subject from the cert
268           subject = cert.cert.get_issuer()
269        assert(subject)
270        self.issuerSubject = subject
271
272    ##
273    # Get the issuer name
274
275    def get_issuer(self, which="CN"):
276        x = self.cert.get_issuer()
277        return getattr(x, which)
278
279    ##
280    # Set the subject name of the certificate
281
282    def set_subject(self, name):
283        req = crypto.X509Req()
284        subj = req.get_subject()
285        if (isinstance(name, dict)):
286            for key in name.keys():
287                setattr(subj, key, name[key])
288        else:
289            setattr(subj, "CN", name)
290        self.cert.set_subject(subj)
291    ##
292    # Get the subject name of the certificate
293
294    def get_subject(self, which="CN"):
295        x = self.cert.get_subject()
296        return getattr(x, which)
297
298    ##
299    # Get the public key of the certificate.
300    #
301    # @param key Keypair object containing the public key
302
303    def set_pubkey(self, key):
304        assert(isinstance(key, Keypair))
305        self.cert.set_pubkey(key.get_openssl_pkey())
306
307    ##
308    # Get the public key of the certificate.
309    # It is returned in the form of a Keypair object.
310
311    def get_pubkey(self):
312        m2x509 = X509.load_cert_string(self.save_to_string())
313        pkey = Keypair()
314        pkey.key = self.cert.get_pubkey()
315        pkey.m2key = m2x509.get_pubkey()
316        return pkey
317
318    ##
319    # Add an X509 extension to the certificate. Add_extension can only be called
320    # once for a particular extension name, due to limitations in the underlying
321    # library.
322    #
323    # @param name string containing name of extension
324    # @param value string containing value of the extension
325
326    def add_extension(self, name, critical, value):
327        ext = crypto.X509Extension (name, critical, value)
328        self.cert.add_extensions([ext])
329
330    ##
331    # Get an X509 extension from the certificate
332
333    def get_extension(self, name):
334        # pyOpenSSL does not have a way to get extensions
335        m2x509 = X509.load_cert_string(self.save_to_string())
336        value = m2x509.get_ext(name).get_value()
337        return value
338
339    ##
340    # Set_data is a wrapper around add_extension. It stores the parameter str in
341    # the X509 subject_alt_name extension. Set_data can only be called once, due
342    # to limitations in the underlying library.
343
344    def set_data(self, str):
345        # pyOpenSSL only allows us to add extensions, so if we try to set the
346        # same extension more than once, it will not work
347        if self.data != None:
348           raise "cannot set subjectAltName more than once"
349        self.data = str
350        self.add_extension("subjectAltName", 0, "URI:http://" + str)
351
352    ##
353    # Return the data string that was previously set with set_data
354
355    def get_data(self):
356        if self.data:
357            return self.data
358
359        try:
360            uri = self.get_extension("subjectAltName")
361        except LookupError:
362            self.data = None
363            return self.data
364
365        if not uri.startswith("URI:http://"):
366            raise "bad encoding in subjectAltName"
367        self.data = uri[11:]
368        return self.data
369
370    ##
371    # Sign the certificate using the issuer private key and issuer subject previous set with set_issuer().
372
373    def sign(self):
374        assert self.cert != None
375        assert self.issuerSubject != None
376        assert self.issuerKey != None
377        self.cert.set_issuer(self.issuerSubject)
378        self.cert.sign(self.issuerKey.get_openssl_pkey(), self.digest)
379
380     ##
381     # Verify the authenticity of a certificate.
382     # @param pkey is a Keypair object representing a public key. If Pkey
383     #     did not sign the certificate, then an exception will be thrown.
384 \r
385    def verify(self, pkey):
386        # pyOpenSSL does not have a way to verify signatures
387        m2x509 = X509.load_cert_string(self.save_to_string())
388        m2pkey = pkey.get_m2_pkey()
389        # verify it
390        return m2x509.verify(m2pkey)
391
392        # XXX alternatively, if openssl has been patched, do the much simpler:
393        # try:
394        #   self.cert.verify(pkey.get_openssl_key())
395        #   return 1
396        # except:
397        #   return 0
398
399    ##
400    # Return True if pkey is identical to the public key that is contained in the certificate.
401    # @param pkey Keypair object
402
403    def is_pubkey(self, pkey):
404        return self.get_pubkey().is_same(pkey)
405
406    ##
407    # Given a certificate cert, verify that this certificate was signed by the
408    # public key contained in cert. Throw an exception otherwise.
409    #
410    # @param cert certificate object
411
412    def is_signed_by_cert(self, cert):
413        k = cert.get_pubkey()
414        result = self.verify(k)
415        return result
416
417    ##
418    # Set the parent certficiate.
419    #
420    # @param p certificate object.
421
422    def set_parent(self, p):
423         self.parent = p
424
425    ##
426    # Return the certificate object of the parent of this certificate.
427
428    def get_parent(self):
429         return self.parent
430
431    ##
432    # Verify a chain of certificates.
433    #
434    # Verification is a basic recursion: <pre>
435    #     if this_certificate was signed by trusted_certs:\r
436    #         return\r
437    #     else\r
438    #         return verify_chain(parent, trusted_certs)\r
439    # </pre>\r
440    #\r
441    # At each recursion, the parent is tested to ensure that it did sign the
442    # child. If a parent did not sign a child, then an exception is thrown. If
443    # the bottom of the recursion is reached and the certificate does not match
444    # a trusted root, then an exception is thrown.
445    #
446    # @param Trusted_certs is a list of certificates that are trusted.\r
447    #
448
449    def verify_chain(self, trusted_certs = None):
450         # Verify a chain of certificates. Each certificate must be signed by
451         # the public key contained in it's parent. The chain is recursed
452         # until a certificate is found that is signed by a trusted root.
453
454         # TODO: verify expiration time
455
456         # if this cert is signed by a trusted_cert, then we are set
457         for trusted_cert in trusted_certs:
458             # TODO: verify expiration of trusted_cert ?
459             if self.is_signed_by_cert(trusted_cert):
460                 #print self.get_subject(), "is signed by a root"
461                 return
462
463         # if there is no parent, then no way to verify the chain
464         if not self.parent:
465             #print self.get_subject(), "has no parent"
466             raise CertMissingParent(self.get_subject())
467
468         # if it wasn't signed by the parent...
469         if not self.is_signed_by_cert(self.parent):
470             #print self.get_subject(), "is not signed by parent"
471             return CertNotSignedByParent(self.get_subject())
472
473         # if the parent isn't verified...
474         self.parent.verify_chain(trusted_certs)
475
476         return