11 from cam import openssl_wrap
14 log = logging.getLogger(__name__)
17 class _CAFiles(object):
19 def __init__(self, basedir, **attrs):
20 for key, value in attrs.items():
21 setattr(self, key, os.path.join(basedir, value))
26 def __init__(self, basedir, config, password=None):
28 self.basedir = basedir
29 self.config = {'basedir': basedir, 'default_days': '365', 'ou': 'CA',
30 'days': '3650', 'country': 'XX', 'crl_url': '',
32 self.config.update(config)
33 self.files = _CAFiles(basedir,
35 public_key='public/ca.pem',
36 private_key='private/ca.key',
39 crlnumber='crlnumber',
45 self._pw = getpass.getpass(prompt='CA Password: ')
49 self._lockfd = open(os.path.join(self.basedir, '_lock'), 'w+')
53 fcntl.lockf(self._lockfd, fcntl.LOCK_EX | fcntl.LOCK_NB)
56 if e.errno in (errno.EACCES, errno.EAGAIN):
59 log.error('another instance is running')
66 fcntl.lockf(self._lockfd, fcntl.LOCK_UN)
69 def _update_config(self):
70 # Create the OpenSSL configuration file.
71 utils.render(self.files.conf, 'openssl_config', self.config)
77 old_umask = os.umask(077)
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):
85 if not os.path.exists(self.files.index):
86 log.info('creating new index file')
87 open(self.files.index, 'w').close()
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)
95 if not os.path.exists(self.files.crlnumber):
96 with open(self.files.crlnumber, 'w') as fd:
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,
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 '-extensions', 'v3_ca', '-out', self.files.public_key,
117 '-days', self.config.get('days', self.config['default_days']),
118 '-selfsign', '-infiles', csr_file)
119 shutil.rmtree(tmpdir)
123 # Make some files public.
124 for path in (os.path.join(self.basedir, 'public'),
125 os.path.join(self.basedir, 'public/certs'),
126 self.files.public_key):
127 if os.path.isdir(path):
133 log.info('generating CRL')
135 self._update_config()
137 # Write the CRL in PEM format to a temporary file.
138 tmpf = self.files.crl + '.tmp'
139 openssl_wrap.run_with_config(
140 self.basedir, self.files.conf,
141 'ca', '-gencrl', '-out', tmpf,
142 '-key', self._getpw())
143 # Convert to DER format for distribution.
145 'crl', '-inform', 'PEM', '-outform', 'DER',
146 '-in', tmpf, '-out', self.files.crl)
148 os.chmod(self.files.crl, 0644)
150 def revoke(self, cert):
151 log.info('revoking certificate %s', cert.name)
152 openssl_wrap.run_with_config(
153 self.basedir, self.files.conf,
154 'ca', '-revoke', cert.public_key_file,
155 '-key', self._getpw())
158 def generate(self, cert):
159 self._update_config()
161 expiry = cert.get_expiration_date()
162 if expiry and expiry > time.time():
163 log.warn('certificate is still valid')
166 log.warn('revoking previous version')
169 log.info('generating new certificate %s', cert.name)
170 tmpdir = tempfile.mkdtemp()
172 csr_file = os.path.join(tmpdir, '%s.csr' % cert.name)
173 conf_file = os.path.join(tmpdir, '%s.conf' % cert.name)
174 ext_file = os.path.join(tmpdir, '%s-ext.conf' % cert.name)
175 conf = {'usage': 'client, server'}
176 conf.update(self.config)
178 conf['days'] = cert.days or self.config['default_days']
181 conf['alt_names'] = ''.join(
182 ['DNS.%d=%s\n' % (idx + 1, x)
183 for idx, x in enumerate(cert.alt_names)])
184 utils.render(conf_file, 'openssl_config', conf)
185 utils.render(ext_file, 'ext_config', conf)
186 openssl_wrap.run_with_config(
187 self.basedir, conf_file,
188 'req', '-new', '-keyout', cert.private_key_file,
189 '-nodes', '-out', csr_file)
190 os.chmod(cert.private_key_file, 0600)
191 openssl_wrap.run_with_config(
192 self.basedir, conf_file,
193 'ca', '-days', conf['days'],
194 '-key', self._getpw(),
195 '-policy', 'policy_anything', '-out', cert.public_key_file,
196 '-extfile', ext_file, '-infiles', csr_file)
198 shutil.rmtree(tmpdir)