cert.py 1.8 KB
Newer Older
ale's avatar
ale committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
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)

35 36 37
    def exists(self):
        return os.path.exists(self.public_key_file)

ale's avatar
ale committed
38
    def get_fingerprint(self, digest='sha1'):
39
        if self.exists():
ale's avatar
ale committed
40 41 42 43 44 45 46 47
            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):
48
        if self.exists():
ale's avatar
ale committed
49 50 51 52 53 54 55 56 57 58 59 60 61
            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