add 'verify' subcommand
[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                        'signature_algorithm': 'sha256', 'bits': '2048'}
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 _update_config(self):
70         # Create the OpenSSL configuration file.
71         utils.render(self.files.conf, 'openssl_config', self.config)
72
73     def close(self):
74         self._unlock()
75
76     def create(self):
77         old_umask = os.umask(077)
78
79         for pathext in ('', 'conf', 'public', 'public/certs',
80                         'public/crl', 'private', 'newcerts'):
81             fullpath = os.path.join(self.basedir, pathext)
82             if not os.path.isdir(fullpath):
83                 os.mkdir(fullpath)
84
85         if not os.path.exists(self.files.index):
86             log.info('creating new index file')
87             open(self.files.index, 'w').close()
88
89         if not os.path.exists(self.files.serial):
90             serial = random.randint(1, 1000000000)
91             log.info('initializing serial number (%d)', serial)
92             with open(self.files.serial, 'w') as fd:
93                 fd.write('%08X\n' % serial)
94
95         if not os.path.exists(self.files.crlnumber):
96             with open(self.files.crlnumber, 'w') as fd:
97                 fd.write('01\n')
98
99         self._update_config()
100
101         # Generate keys if they do not exist.
102         if not os.path.exists(self.files.public_key):
103             tmpdir = tempfile.mkdtemp()
104             csr_file = os.path.join(tmpdir, 'ca.csr')
105             log.info('creating new RSA CA CSR')
106             openssl_wrap.run_with_config(
107                 self.basedir, self.files.conf,
108                 'req', '-new',
109                 '-passout', 'pass:%s' % self._getpw(),
110                 '-keyout', self.files.private_key, '-out', csr_file)
111             log.info('self-signing RSA CA certificate')
112             openssl_wrap.run_with_config(
113                 self.basedir, self.files.conf,
114                 'ca', '-keyfile', self.files.private_key,
115                 '-key', self._getpw(),
116                 '-md', self.config['signature_algorithm'],
117                 '-extensions', 'v3_ca', '-out', self.files.public_key,
118                 '-days', self.config.get('days', self.config['default_days']),
119                 '-selfsign', '-infiles', csr_file)
120             shutil.rmtree(tmpdir)
121
122         os.umask(old_umask)
123
124         # Make some files public.
125         for path in (os.path.join(self.basedir, 'public'),
126                      os.path.join(self.basedir, 'public/certs'),
127                      self.files.public_key):
128             if os.path.isdir(path):
129                 os.chmod(path, 0755)
130             else:
131                 os.chmod(path, 0644)
132
133     def gencrl(self):
134         log.info('generating CRL')
135
136         self._update_config()
137
138         # Write the CRL in PEM format to a temporary file.
139         tmpf = self.files.crl + '.tmp'
140         openssl_wrap.run_with_config(
141             self.basedir, self.files.conf,
142             'ca', '-gencrl', '-out', tmpf,
143             '-key', self._getpw())
144         # Convert to DER format for distribution.
145         openssl_wrap.run(
146             'crl', '-inform', 'PEM', '-outform', 'DER',
147             '-in', tmpf, '-out', self.files.crl)
148         os.remove(tmpf)
149         os.chmod(self.files.crl, 0644)
150
151     def revoke(self, cert):
152         log.info('revoking certificate %s', cert.name)
153         openssl_wrap.run_with_config(
154             self.basedir, self.files.conf,
155             'ca', '-revoke', cert.public_key_file,
156             '-key', self._getpw())
157         self.gencrl()
158
159     def verify(self, path):
160         log.info('verifying certificate %s', path)
161         args = ['verify', '-CAfile', self.files.public_key, path]
162         try:
163             openssl_wrap.run(*args, CAROOT=os.path.abspath(self.basedir))
164         except openssl_wrap.CommandError:
165             return False
166         return True
167
168     def generate(self, cert):
169         self._update_config()
170
171         expiry = cert.get_expiration_date()
172         if expiry and expiry > time.time():
173             log.warn('certificate is still valid')
174
175         if cert.exists():
176             log.warn('revoking previous version')
177             self.revoke(cert)
178
179         log.info('generating new certificate %s', cert.name)
180         tmpdir = tempfile.mkdtemp()
181         try:
182             csr_file = os.path.join(tmpdir, '%s.csr' % cert.name)
183             conf_file = os.path.join(tmpdir, '%s.conf' % cert.name)
184             ext_file = os.path.join(tmpdir, '%s-ext.conf' % cert.name)
185             conf = {'usage': 'client, server'}
186             conf.update(self.config)
187             conf['cn'] = cert.cn
188             conf['days'] = cert.days or self.config['default_days']
189             if cert.ou:
190                 conf['ou'] = cert.ou
191             conf['alt_names'] = ''.join(
192                 ['DNS.%d=%s\n' % (idx + 1, x) 
193                  for idx, x in enumerate(cert.alt_names)])
194             utils.render(conf_file, 'openssl_config', conf)
195             utils.render(ext_file, 'ext_config', conf)
196             openssl_wrap.run_with_config(
197                 self.basedir, conf_file,
198                 'req', '-new', '-keyout', cert.private_key_file,
199                 '-' + self.config['signature_algorithm'],
200                 '-nodes', '-out', csr_file)
201             os.chmod(cert.private_key_file, 0600)
202             openssl_wrap.run_with_config(
203                 self.basedir, conf_file,
204                 'ca', '-days', conf['days'],
205                 '-key', self._getpw(),
206                 '-md', self.config['signature_algorithm'],
207                 '-policy', 'policy_anything', '-out', cert.public_key_file,
208                 '-extfile', ext_file, '-infiles', csr_file)
209         finally:
210             shutil.rmtree(tmpdir)
211