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
11 # This module exports two classes: Keypair and Certificate.
16 from OpenSSL import crypto
18 from M2Crypto import X509
19 from M2Crypto import EVP
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).
29 key = None # public/private keypair
30 m2key = None # public key (m2crypto format)
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
39 def __init__(self, create=False, string=None, filename=None):
43 self.load_from_string(string)
45 self.load_from_file(filename)
48 # Create a RSA public/private key pair and store it inside the keypair object
51 self.key = crypto.PKey()
52 self.key.generate_key(crypto.TYPE_RSA, 1024)
55 # Save the private key to a file
56 # @param filename name of file to store the keypair in
58 def save_to_file(self, filename):
59 open(filename, 'w').write(self.as_pem())
62 # Load the private key from a file. Implicity the private key includes the public key.
64 def load_from_file(self, filename):
65 buffer = open(filename, 'r').read()
66 self.load_from_string(buffer)
69 # Load the private key from a string. Implicitly the private key includes the public key.
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)
76 # Load the public key from a string. No private key is loaded.
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)
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()
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")
99 # convert the m2 x509 cert to a pyopenssl x509
100 m2pem = m2x509.as_pem()
101 pyx509 = crypto.load_certificate(crypto.FILETYPE_PEM, m2pem)
103 # get the pyopenssl pkey from the pyopenssl x509
104 self.key = pyx509.get_pubkey()
107 # Load the public key from a string. No private key is loaded.
109 def load_pubkey_from_string(self, string):
110 (f, fn) = tempfile.mkstemp()
113 self.load_pubkey_from_file(fn)
117 # Return the private key in PEM format.
120 return crypto.dump_privatekey(crypto.FILETYPE_PEM, self.key)
123 # Return an OpenSSL pkey object
125 def get_m2_pkey(self):
127 self.m2key = M2Crypto.EVP.load_key_string(self.as_pem())
131 # Given another Keypair object, return TRUE if the two keys are the same.
133 def get_openssl_pkey(self):
136 def is_same(self, pkey):
137 return self.as_pem() == pkey.as_pem()
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.
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
161 # Create a certificate object.
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
169 def __init__(self, create=False, subject=None, string=None, filename=None):
170 if create or subject:
173 self.set_subject(subject)
175 self.load_from_string(string)
177 self.load_from_file(filename)
180 # Create a blank X509 certificate and store it in this object.
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
189 # Given a pyOpenSSL X509 object, store that object inside of this
190 # certificate object.
192 def load_from_pyopenssl_x509(self, x509):
196 # Load the certificate from a string
198 def load_from_string(self, string):
199 # if it is a chain of multiple certs, then split off the first one and
201 parts = string.split("-----parent-----", 1)
202 self.cert = crypto.load_certificate(crypto.FILETYPE_PEM, parts[0])
204 # if there are more certs, then create a parent and let the parent load
205 # itself from the remainder of the string
207 self.parent = self.__class__()
208 self.parent.load_from_string(parts[1])
211 # Load the certificate from a file
213 def load_from_file(self, filename):
214 file = open(filename)
216 self.load_from_string(string)
219 # Save the certificate to a string.
221 # @param save_parents If save_parents==True, then also save the parent certificates.
223 def save_to_string(self, save_parents=False):
224 string = crypto.dump_certificate(crypto.FILETYPE_PEM, self.cert)
225 if save_parents and self.parent:
226 string = string + "-----parent-----" + self.parent.save_to_string(save_parents)
230 # Save the certificate to a file.
231 # @param save_parents If save_parents==True, then also save the parent certificates.
233 def save_to_file(self, filename, save_parents=False):
234 string = self.save_to_string(save_parents=save_parents)
235 open(filename, 'w').write(string)
238 # Sets the issuer private key and name
239 # @param key Keypair object containing the private key of the issuer
240 # @param subject String containing the name of the issuer
241 # @param cert (optional) Certificate object containing the name of the issuer
243 def set_issuer(self, key, subject=None, cert=None):
246 # it's a mistake to use subject and cert params at the same time
248 if isinstance(subject, dict) or isinstance(subject, str):
249 req = crypto.X509Req()
250 reqSubject = req.get_subject()
251 if (isinstance(subject, dict)):
252 for key in reqSubject.keys():
253 setattr(reqSubject, key, name[key])
255 setattr(reqSubject, "CN", subject)
257 # subject is not valid once req is out of scope, so save req
260 # if a cert was supplied, then get the subject from the cert
261 subject = cert.cert.get_issuer()
263 self.issuerSubject = subject
266 # Get the issuer name
268 def get_issuer(self, which="CN"):
269 x = self.cert.get_issuer()
270 return getattr(x, which)
273 # Set the subject name of the certificate
275 def set_subject(self, name):
276 req = crypto.X509Req()
277 subj = req.get_subject()
278 if (isinstance(name, dict)):
279 for key in name.keys():
280 setattr(subj, key, name[key])
282 setattr(subj, "CN", name)
283 self.cert.set_subject(subj)
285 # Get the subject name of the certificate
287 def get_subject(self, which="CN"):
288 x = self.cert.get_subject()
289 return getattr(x, which)
292 # Get the public key of the certificate.
294 # @param key Keypair object containing the public key
296 def set_pubkey(self, key):
297 assert(isinstance(key, Keypair))
298 self.cert.set_pubkey(key.get_openssl_pkey())
301 # Get the public key of the certificate.
302 # It is returned in the form of a Keypair object.
304 def get_pubkey(self):
305 m2x509 = X509.load_cert_string(self.save_to_string())
307 pkey.key = self.cert.get_pubkey()
308 pkey.m2key = m2x509.get_pubkey()
312 # Add an X509 extension to the certificate. Add_extension can only be called
313 # once for a particular extension name, due to limitations in the underlying
316 # @param name string containing name of extension
317 # @param value string containing value of the extension
319 def add_extension(self, name, critical, value):
320 ext = crypto.X509Extension (name, critical, value)
321 self.cert.add_extensions([ext])
324 # Get an X509 extension from the certificate
326 def get_extension(self, name):
327 # pyOpenSSL does not have a way to get extensions
328 m2x509 = X509.load_cert_string(self.save_to_string())
329 value = m2x509.get_ext(name).get_value()
333 # Set_data is a wrapper around add_extension. It stores the parameter str in
334 # the X509 subject_alt_name extension. Set_data can only be called once, due
335 # to limitations in the underlying library.
337 def set_data(self, str):
338 # pyOpenSSL only allows us to add extensions, so if we try to set the
339 # same extension more than once, it will not work
340 if self.data != None:
341 raise "cannot set subjectAltName more than once"
343 self.add_extension("subjectAltName", 0, "URI:http://" + str)
346 # Return the data string that was previously set with set_data
353 uri = self.get_extension("subjectAltName")
358 if not uri.startswith("URI:http://"):
359 raise "bad encoding in subjectAltName"
364 # Sign the certificate using the issuer private key and issuer subject previous set with set_issuer().
367 assert self.cert != None
368 assert self.issuerSubject != None
369 assert self.issuerKey != None
370 self.cert.set_issuer(self.issuerSubject)
371 self.cert.sign(self.issuerKey.get_openssl_pkey(), self.digest)
374 # Verify the authenticity of a certificate.
375 # @param pkey is a Keypair object representing a public key. If Pkey
376 # did not sign the certificate, then an exception will be thrown.
378 def verify(self, pkey):
379 # pyOpenSSL does not have a way to verify signatures
380 m2x509 = X509.load_cert_string(self.save_to_string())
381 m2pkey = pkey.get_m2_pkey()
383 return m2x509.verify(m2pkey)
385 # XXX alternatively, if openssl has been patched, do the much simpler:
387 # self.cert.verify(pkey.get_openssl_key())
393 # Return True if pkey is identical to the public key that is contained in the certificate.
394 # @param pkey Keypair object
396 def is_pubkey(self, pkey):
397 return self.get_pubkey().is_same(pkey)
400 # Given a certificate cert, verify that this certificate was signed by the
401 # public key contained in cert. Throw an exception otherwise.
403 # @param cert certificate object
405 def is_signed_by_cert(self, cert):
406 k = cert.get_pubkey()
407 result = self.verify(k)
411 # Set the parent certficiate.
413 # @param p certificate object.
415 def set_parent(self, p):
419 # Return the certificate object of the parent of this certificate.
421 def get_parent(self):
425 # Verification examines a chain of certificates to ensure that each parent
426 # signs the child, and that some certificate in the chain is signed by a
427 # trusted certificate.
429 # Verification is a basic recursion: <pre>
430 # if this_certificate was signed by trusted_certs:
\r
433 # return verify_chain(parent, trusted_certs)
\r
436 # At each recursion, the parent is tested to ensure that it did sign the
437 # child. If a parent did not sign a child, then an exception is thrown. If
438 # the bottom of the recursion is reached and the certificate does not match
439 # a trusted root, then an exception is thrown.
441 # @param Trusted_certs is a list of certificates that are trusted.
\r
444 def verify_chain(self, trusted_certs = None):
445 # Verify a chain of certificates. Each certificate must be signed by
446 # the public key contained in it's parent. The chain is recursed
447 # until a certificate is found that is signed by a trusted root.
449 # TODO: verify expiration time
451 # if this cert is signed by a trusted_cert, then we are set
452 for trusted_cert in trusted_certs:
453 # TODO: verify expiration of trusted_cert ?
454 if self.is_signed_by_cert(trusted_cert):
455 #print self.get_subject(), "is signed by a root"
458 # if there is no parent, then no way to verify the chain
460 #print self.get_subject(), "has no parent"
461 raise CertMissingParent(self.get_subject())
463 # if it wasn't signed by the parent...
464 if not self.is_signed_by_cert(self.parent):
465 #print self.get_subject(), "is not signed by parent"
466 return CertNotSignedByParent(self.get_subject())
468 # if the parent isn't verified...
469 self.parent.verify_chain(trusted_certs)