upgrade to CAM v2.0
[stack/cam.git] / cam / ca.py
diff --git a/cam/ca.py b/cam/ca.py
new file mode 100644 (file)
index 0000000..a14075c
--- /dev/null
+++ b/cam/ca.py
@@ -0,0 +1,175 @@
+import errno
+import fcntl
+import logging
+import re
+import os
+import getpass
+import random
+import shutil
+import tempfile
+import time
+from cam import openssl_wrap
+from cam import utils
+
+log = logging.getLogger(__name__)
+
+
+class _CAFiles(object):
+
+    def __init__(self, basedir, **attrs):
+        for key, value in attrs.items():
+            setattr(self, key, os.path.join(basedir, value))
+
+
+class CA(object):
+
+    def __init__(self, basedir, config, password=None):
+        self._pw = password
+        self.basedir = basedir
+        self.config = {'basedir': basedir, 'default_days': '365', 'ou': 'CA',
+                       'days': '3650', 'country': 'XX', 'crl_url': '',
+                       'bits': '4096'}
+        self.config.update(config)
+        self.files = _CAFiles(basedir, 
+                              conf='conf/ca.conf',
+                              public_key='public/ca.pem',
+                              private_key='private/ca.key',
+                              crl='public/crl.pem',
+                              serial='serial',
+                              crlnumber='crlnumber',
+                              index='index')
+        self._lock()
+
+    def _getpw(self):
+        if self._pw is None:
+            self._pw = getpass.getpass(prompt='CA Password: ')
+        return self._pw
+
+    def _lock(self):
+        self._lockfd = open(os.path.join(self.basedir, '_lock'), 'w+')
+        n = 3
+        while True:
+            try:
+                fcntl.lockf(self._lockfd, fcntl.LOCK_EX | fcntl.LOCK_NB)
+                break
+            except IOError, e:
+                if e.errno in (errno.EACCES, errno.EAGAIN):
+                    n -= 1
+                    if n == 0:
+                        log.error('another instance is running')
+                        raise
+                    time.sleep(1)
+                    continue
+                raise
+
+    def _unlock(self):
+        fcntl.lockf(self._lockfd, fcntl.LOCK_UN)
+        self._lockfd.close()
+
+    def close(self):
+        self._unlock()
+
+    def create(self):
+        old_umask = os.umask(077)
+
+        for pathext in ('', 'conf', 'public', 'public/certs',
+                        'public/crl', 'private', 'newcerts'):
+            fullpath = os.path.join(self.basedir, pathext)
+            if not os.path.isdir(fullpath):
+                os.mkdir(fullpath)
+
+        if not os.path.exists(self.files.index):
+            log.info('creating new index file')
+            open(self.files.index, 'w').close()
+
+        if not os.path.exists(self.files.serial):
+            serial = random.randint(1, 1000000000)
+            log.info('initializing serial number (%d)', serial)
+            with open(self.files.serial, 'w') as fd:
+                fd.write('%08X\n' % serial)
+
+        if not os.path.exists(self.files.crlnumber):
+            with open(self.files.crlnumber, 'w') as fd:
+                fd.write('01\n')
+
+        # Create the OpenSSL configuration file.
+        utils.render(self.files.conf, 'openssl_config', self.config)
+
+        # Generate keys if they do not exist.
+        if not os.path.exists(self.files.public_key):
+            tmpdir = tempfile.mkdtemp()
+            csr_file = os.path.join(tmpdir, 'ca.csr')
+            log.info('creating new RSA CA CSR')
+            openssl_wrap.run_with_config(
+                self.files.conf, 'req', '-new',
+                '-passout', 'pass:%s' % self._getpw(),
+                '-keyout', self.files.private_key, '-out', csr_file)
+            log.info('self-signing RSA CA certificate')
+            openssl_wrap.run_with_config(
+                self.files.conf, 'ca', '-keyfile', self.files.private_key,
+                '-key', self._getpw(),
+                '-extensions', 'v3_ca', '-out', self.files.public_key,
+                '-days', self.config.get('days', self.config['default_days']),
+                '-selfsign', '-infiles', csr_file)
+            shutil.rmtree(tmpdir)
+
+        os.umask(old_umask)
+
+        # Make some files public.
+        for path in (os.path.join(self.basedir, 'public'),
+                     os.path.join(self.basedir, 'public/certs'),
+                     self.files.public_key):
+            if os.path.isdir(path):
+                os.chmod(path, 0755)
+            else:
+                os.chmod(path, 0644)
+
+    def gencrl(self):
+        log.info('generating CRL')
+        openssl_wrap.run_with_config(
+            self.files.conf, 'ca', '-gencrl', '-out', self.files.crl,
+            '-key', self._getpw())
+        os.chmod(self.files.crl, 0644)
+
+    def revoke(self, cert):
+        log.info('revoking certificate %s', cert.name)
+        openssl_wrap.run_with_config(
+            self.files.conf, 'ca', '-revoke', cert.public_key_file,
+            '-key', self._getpw())
+        self.gencrl()
+
+    def generate(self, cert):
+        expiry = cert.get_expiration_date()
+        if expiry and expiry > time.time():
+            log.warn('certificate is still valid, revoking previous version')
+            self.revoke(cert)
+
+        log.info('generating new certificate %s', cert.name)
+        tmpdir = tempfile.mkdtemp()
+        try:
+            csr_file = os.path.join(tmpdir, '%s.csr' % cert.name)
+            conf_file = os.path.join(tmpdir, '%s.conf' % cert.name)
+            ext_file = os.path.join(tmpdir, '%s-ext.conf' % cert.name)
+            conf = {}
+            conf.update(self.config)
+            conf['cn'] = cert.cn
+            conf['days'] = cert.days or self.config['default_days']
+            if cert.ou:
+                conf['ou'] = cert.ou
+            conf['alt_names'] = ''.join(
+                ['DNS.%d=%s\n' % (idx + 1, x) 
+                 for idx, x in enumerate(cert.alt_names)])
+            utils.render(conf_file, 'openssl_config', conf)
+            utils.render(ext_file, 'ext_config', conf)
+            openssl_wrap.run_with_config(
+                conf_file, 'req', '-new', '-keyout', cert.private_key_file,
+                '-nodes', '-out', csr_file)
+            os.chmod(cert.private_key_file, 0600)
+            openssl_wrap.run_with_config(
+                conf_file, 'ca', '-days', conf['days'],
+                '-key', self._getpw(),
+                '-policy', 'policy_anything', '-out', cert.public_key_file,
+                '-extfile', ext_file, '-infiles', csr_file)
+        finally:
+            shutil.rmtree(tmpdir)
+