ca_storage.py 2.3 KB
Newer Older
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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
import fcntl
import os
import time

import certutil


class FileStorage(object):

    def __init__(self, root):
        self.root = root
        self.certs_dir = os.path.join(root, 'certs')
        self.key_dir = os.path.join(root, 'private')
        for path in (self.root, self.certs_dir, self.key_dir):
            if not os.path.isdir(path):
                os.mkdir(path, 0700)

        # Special files.
        self.serial_path = os.path.join(root, 'serial')
        self.ca_crt_path = os.path.join(root, 'ca.pem')
        self.ca_key_path = os.path.join(self.key_dir, 'ca.key')
        self.crl_path = os.path.join(root, 'crl.pem')

    def _cert_path(self, cn):
        return os.path.join(self.certs_dir,
                            cn.replace('/', '_') + '.pem')

    def get_ca(self):
        if (os.path.exists(self.ca_crt_path) 
            and os.path.exists(self.ca_key_path)):
            return (certutil.readfrom(self.ca_key_path),
                    certutil.readfrom(self.ca_crt_path))
        else:
            return (None, None)

    def set_ca(self, key_str, cert_str):
        certutil.writeto(self.ca_crt_path, cert_str)
        certutil.writeto(self.ca_key_path, key_str)
        os.chmod(self.ca_key_path, 0400)

    def get_crl(self):
        if os.path.exists(self.crl_path):
            return certutil.readfrom(self.crl_path)

    def set_crl(self, crl_str):
        certutil.writeto(self.crl_path, crl_str)

    def get_certificate(self, cn):
        path = self._cert_path(cn)
        if os.path.exists(path):
            return certutil.readfrom(path)

    def store_certificate(self, cn, cert_data):
        certutil.writeto(self._cert_path(cn), cert_data)

    def delete_certificate(self, cn):
        os.unlink(self._cert_path(cn))

    def get_next_serial(self):
        try:
            fd = open(self.serial_path, 'r+')
        except IOError:
            fd = open(self.serial_path, 'w+')
        fcntl.lockf(fd, fcntl.LOCK_EX)
        try:
            contents = fd.read()
            fd.seek(0)
            if contents:
                fd.truncate()
                serial = int(contents.strip()) + 1
            else:
                serial = int(time.time())
            fd.write('%d\n' % serial)
            return serial
        finally:
            fcntl.lockf(fd, fcntl.LOCK_UN)
            fd.close()