ensure that the generated CRL is in DER format
[stack/cam.git] / cam / ca.py
1 import errno
2 import fcntl
3 import logging
4 import re
5 import os
6 import getpass
7 import random
8 import shutil
9 import tempfile
10 import time
11 from cam import openssl_wrap
12 from cam import utils
13
14 log = logging.getLogger(__name__)
15
16
17 class _CAFiles(object):
18
19     def __init__(self, basedir, **attrs):
20         for key, value in attrs.items():
21             setattr(self, key, os.path.join(basedir, value))
22
23
24 class CA(object):
25
26     def __init__(self, basedir, config, password=None):
27         self._pw = password
28         self.basedir = basedir
29         self.config = {'basedir': basedir, 'default_days': '365', 'ou': 'CA',
30                        'days': '3650', 'country': 'XX', 'crl_url': '',
31                        'bits': '4096'}
32         self.config.update(config)
33         self.files = _CAFiles(basedir, 
34                               conf='conf/ca.conf',
35                               public_key='public/ca.pem',
36                               private_key='private/ca.key',
37                               crl='public/ca.crl',
38                               serial='serial',
39                               crlnumber='crlnumber',
40                               index='index')
41         self._lock()
42
43     def _getpw(self):
44         if self._pw is None:
45             self._pw = getpass.getpass(prompt='CA Password: ')
46         return self._pw
47
48     def _lock(self):
49         self._lockfd = open(os.path.join(self.basedir, '_lock'), 'w+')
50         n = 3
51         while True:
52             try:
53                 fcntl.lockf(self._lockfd, fcntl.LOCK_EX | fcntl.LOCK_NB)
54                 break
55             except IOError, e:
56                 if e.errno in (errno.EACCES, errno.EAGAIN):
57                     n -= 1
58                     if n == 0:
59                         log.error('another instance is running')
60                         raise
61                     time.sleep(1)
62                     continue
63                 raise
64
65     def _unlock(self):
66         fcntl.lockf(self._lockfd, fcntl.LOCK_UN)
67         self._lockfd.close()
68
69     def close(self):
70         self._unlock()
71
72     def create(self):
73         old_umask = os.umask(077)
74
75         for pathext in ('', 'conf', 'public', 'public/certs',
76                         'public/crl', 'private', 'newcerts'):
77             fullpath = os.path.join(self.basedir, pathext)
78             if not os.path.isdir(fullpath):
79                 os.mkdir(fullpath)
80
81         if not os.path.exists(self.files.index):
82             log.info('creating new index file')
83             open(self.files.index, 'w').close()
84
85         if not os.path.exists(self.files.serial):
86             serial = random.randint(1, 1000000000)
87             log.info('initializing serial number (%d)', serial)
88             with open(self.files.serial, 'w') as fd:
89                 fd.write('%08X\n' % serial)
90
91         if not os.path.exists(self.files.crlnumber):
92             with open(self.files.crlnumber, 'w') as fd:
93                 fd.write('01\n')
94
95         # Create the OpenSSL configuration file.
96         utils.render(self.files.conf, 'openssl_config', self.config)
97
98         # Generate keys if they do not exist.
99         if not os.path.exists(self.files.public_key):
100             tmpdir = tempfile.mkdtemp()
101             csr_file = os.path.join(tmpdir, 'ca.csr')
102             log.info('creating new RSA CA CSR')
103             openssl_wrap.run_with_config(
104                 self.basedir, self.files.conf,
105                 'req', '-new',
106                 '-passout', 'pass:%s' % self._getpw(),
107                 '-keyout', self.files.private_key, '-out', csr_file)
108             log.info('self-signing RSA CA certificate')
109             openssl_wrap.run_with_config(
110                 self.basedir, self.files.conf,
111                 'ca', '-keyfile', self.files.private_key,
112                 '-key', self._getpw(),
113                 '-extensions', 'v3_ca', '-out', self.files.public_key,
114                 '-days', self.config.get('days', self.config['default_days']),
115                 '-selfsign', '-infiles', csr_file)
116             shutil.rmtree(tmpdir)
117
118         os.umask(old_umask)
119
120         # Make some files public.
121         for path in (os.path.join(self.basedir, 'public'),
122                      os.path.join(self.basedir, 'public/certs'),
123                      self.files.public_key):
124             if os.path.isdir(path):
125                 os.chmod(path, 0755)
126             else:
127                 os.chmod(path, 0644)
128
129     def gencrl(self):
130         log.info('generating CRL')
131         # Write the CRL in PEM format to a temporary file.
132         tmpf = self.files.crl + '.tmp'
133         openssl_wrap.run_with_config(
134             self.basedir, self.files.conf,
135             'ca', '-gencrl', '-out', tmpf,
136             '-key', self._getpw())
137         # Convert to DER format for distribution.
138         openssl_wrap.run(
139             'crl', '-inform', 'PEM', '-outform', 'DER',
140             '-in', tmpf, '-out', self.files.crl)
141         os.remove(tmpf)
142         os.chmod(self.files.crl, 0644)
143
144     def revoke(self, cert):
145         log.info('revoking certificate %s', cert.name)
146         openssl_wrap.run_with_config(
147             self.basedir, self.files.conf,
148             'ca', '-revoke', cert.public_key_file,
149             '-key', self._getpw())
150         self.gencrl()
151
152     def generate(self, cert):
153         expiry = cert.get_expiration_date()
154         if expiry and expiry > time.time():
155             log.warn('certificate is still valid, revoking previous version')
156             self.revoke(cert)
157
158         log.info('generating new certificate %s', cert.name)
159         tmpdir = tempfile.mkdtemp()
160         try:
161             csr_file = os.path.join(tmpdir, '%s.csr' % cert.name)
162             conf_file = os.path.join(tmpdir, '%s.conf' % cert.name)
163             ext_file = os.path.join(tmpdir, '%s-ext.conf' % cert.name)
164             conf = {}
165             conf.update(self.config)
166             conf['cn'] = cert.cn
167             conf['days'] = cert.days or self.config['default_days']
168             if cert.ou:
169                 conf['ou'] = cert.ou
170             conf['alt_names'] = ''.join(
171                 ['DNS.%d=%s\n' % (idx + 1, x) 
172                  for idx, x in enumerate(cert.alt_names)])
173             utils.render(conf_file, 'openssl_config', conf)
174             utils.render(ext_file, 'ext_config', conf)
175             openssl_wrap.run_with_config(
176                 self.basedir, conf_file,
177                 'req', '-new', '-keyout', cert.private_key_file,
178                 '-nodes', '-out', csr_file)
179             os.chmod(cert.private_key_file, 0600)
180             openssl_wrap.run_with_config(
181                 self.basedir, conf_file,
182                 'ca', '-days', conf['days'],
183                 '-key', self._getpw(),
184                 '-policy', 'policy_anything', '-out', cert.public_key_file,
185                 '-extfile', ext_file, '-infiles', csr_file)
186         finally:
187             shutil.rmtree(tmpdir)
188