upgrade to CAM v2.0
[stack/cam.git] / cam / cert.py
diff --git a/cam/cert.py b/cam/cert.py
new file mode 100644 (file)
index 0000000..9254fb0
--- /dev/null
@@ -0,0 +1,58 @@
+import os
+import re
+import string
+import time
+from cam import openssl_wrap
+
+
+def _parse_alt_names(s):
+    if not s:
+        return []
+    if ',' in s:
+        parts = s.split(',')
+    else:
+        parts = s.split()
+    return [x.strip() for x in parts if x]
+
+
+class Cert(object):
+
+    def __init__(self, ca, name, config):
+        self.name = name
+        self.ca = ca
+        self.cn = config['cn']
+        self.ou = config.get('ou', '')
+        self.days = config.get('days')
+
+        self.alt_names = _parse_alt_names(config.get('alt_names'))
+        if self.cn not in self.alt_names:
+            self.alt_names.insert(0, self.cn)
+        self.public_key_file = os.path.join(ca.basedir, 'public', 'certs', 
+                                            '%s.pem' % name)
+        self.private_key_file = os.path.join(ca.basedir, 'private',
+                                             '%s.key' % name)
+
+    def get_fingerprint(self, digest='sha1'):
+        if os.path.exists(self.public_key_file):
+            output = openssl_wrap.run('x509', '-in', self.public_key_file,
+                                      '-noout', '-fingerprint', '-%s' % digest)
+            m = re.search(r'=(.*)$', output)
+            if m:
+                return m.group(1)
+        return None
+
+    def get_expiration_date(self):
+        if os.path.exists(self.public_key_file):
+            output = openssl_wrap.run('x509', '-in', self.public_key_file,
+                                      '-noout', '-dates')
+            m = re.search(r'notAfter=(.*)', output)
+            if m:
+                return time.mktime(time.strptime(m.group(1),
+                                                 '%b %d %H:%M:%S %Y %Z'))
+        return None
+
+    def expired(self):
+        now = time.time()
+        return self.get_expiration_date() > now
+
+