upgrade to CAM v2.0
[stack/cam.git] / cam / cert.py
1 import os
2 import re
3 import string
4 import time
5 from cam import openssl_wrap
6
7
8 def _parse_alt_names(s):
9     if not s:
10         return []
11     if ',' in s:
12         parts = s.split(',')
13     else:
14         parts = s.split()
15     return [x.strip() for x in parts if x]
16
17
18 class Cert(object):
19
20     def __init__(self, ca, name, config):
21         self.name = name
22         self.ca = ca
23         self.cn = config['cn']
24         self.ou = config.get('ou', '')
25         self.days = config.get('days')
26
27         self.alt_names = _parse_alt_names(config.get('alt_names'))
28         if self.cn not in self.alt_names:
29             self.alt_names.insert(0, self.cn)
30         self.public_key_file = os.path.join(ca.basedir, 'public', 'certs', 
31                                             '%s.pem' % name)
32         self.private_key_file = os.path.join(ca.basedir, 'private',
33                                              '%s.key' % name)
34
35     def get_fingerprint(self, digest='sha1'):
36         if os.path.exists(self.public_key_file):
37             output = openssl_wrap.run('x509', '-in', self.public_key_file,
38                                       '-noout', '-fingerprint', '-%s' % digest)
39             m = re.search(r'=(.*)$', output)
40             if m:
41                 return m.group(1)
42         return None
43
44     def get_expiration_date(self):
45         if os.path.exists(self.public_key_file):
46             output = openssl_wrap.run('x509', '-in', self.public_key_file,
47                                       '-noout', '-dates')
48             m = re.search(r'notAfter=(.*)', output)
49             if m:
50                 return time.mktime(time.strptime(m.group(1),
51                                                  '%b %d %H:%M:%S %Y %Z'))
52         return None
53
54     def expired(self):
55         now = time.time()
56         return self.get_expiration_date() > now
57
58