add .gitignore
[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 exists(self):
36         return os.path.exists(self.public_key_file)
37
38     def get_fingerprint(self, digest='sha1'):
39         if self.exists():
40             output = openssl_wrap.run('x509', '-in', self.public_key_file,
41                                       '-noout', '-fingerprint', '-%s' % digest)
42             m = re.search(r'=(.*)$', output)
43             if m:
44                 return m.group(1)
45         return None
46
47     def get_expiration_date(self):
48         if self.exists():
49             output = openssl_wrap.run('x509', '-in', self.public_key_file,
50                                       '-noout', '-dates')
51             m = re.search(r'notAfter=(.*)', output)
52             if m:
53                 return time.mktime(time.strptime(m.group(1),
54                                                  '%b %d %H:%M:%S %Y %Z'))
55         return None
56
57     def expired(self):
58         now = time.time()
59         return self.get_expiration_date() > now
60
61