source: trunk/server/fedora/config/etc/httpd/export-scripts-certs @ 2825

Last change on this file since 2825 was 2825, checked in by andersk, 5 years ago
export-scripts-certs: use a lock file; reload Apache on changes
  • Property svn:executable set to *
File size: 4.8 KB
Line 
1#!/usr/bin/python
2
3import base64
4import errno
5import fcntl
6import hashlib
7import ldap
8import os
9import subprocess
10import sys
11import textwrap
12from OpenSSL import crypto, SSL
13
14CERTS_DIR = '/var/lib/scripts-certs'
15
16ll = ldap.initialize('ldapi://%2fvar%2frun%2fslapd-scripts.socket/')
17with open('/etc/signup-ldap-pw') as pw_file:
18    ll.simple_bind_s("cn=Directory Manager", pw_file.read())
19
20if not os.path.exists(CERTS_DIR):
21    os.mkdir(CERTS_DIR)
22
23vhosts = ll.search_s(
24    'ou=VirtualHosts,dc=scripts,dc=mit,dc=edu',
25    ldap.SCOPE_SUBTREE,
26    '(&(objectClass=scriptsVhost)(scriptsVhostCertificate=*))',
27    ['scriptsVhostName', 'scriptsVhostAlias', 'scriptsVhostCertificate', 'scriptsVhostCertificateKeyFile'])
28
29vhosts.sort(key=lambda (dn, vhost): vhost['scriptsVhostName'])
30
31cert_filenames = set()
32error = False
33
34def err(e):
35    global error
36    sys.stderr.write(e)
37    error = True
38
39def conf(vhost):
40    name, = vhost['scriptsVhostName']
41    aliases = vhost.get('scriptsVhostAlias', [])
42    certs, = vhost['scriptsVhostCertificate']
43    try:
44        key_filename, = vhost['scriptsVhostCertificateKeyFile']
45    except KeyError:
46        err('Error: missing scriptsVhostCertificateKeyFile for vhost {}\n'.format(name))
47        return
48
49    try:
50        certs = [crypto.load_certificate(crypto.FILETYPE_ASN1, base64.b64decode(cert)) for cert in certs.split()]
51    except (TypeError, crypto.Error) as e:
52        err('Error: malformed certificate list for vhost {}: {}\n'.format(name, e))
53        return
54
55    if not certs:
56        err('Error: empty certificate list for vhost {}\n'.format(name))
57        return
58
59    key_path = os.path.join('/etc/pki/tls/private', key_filename)
60    if os.path.split(os.path.abspath(key_path)) != ('/etc/pki/tls/private', key_filename):
61        err('Error: bad key filename {} for vhost {}\n'.format(key_path, name))
62        return
63
64    ctx = SSL.Context(SSL.SSLv23_METHOD)
65    try:
66        ctx.use_privatekey_file(key_path, crypto.FILETYPE_PEM)
67    except (SSL.Error, crypto.Error) as e:
68        err('Error: could not read key {} for vhost {}: {}\n'.format(key_path, name, e))
69        return
70
71    ctx.use_certificate(certs[0])
72    for cert in certs[1:]:
73        ctx.add_extra_chain_cert(cert)
74
75    try:
76        ctx.check_privatekey()
77    except SSL.Error as e:
78        err('Error: key {} does not match certificate for vhost {}: {}\n'.format(key_path, name, e))
79        return
80
81    certs_pem = ''.join(crypto.dump_certificate(crypto.FILETYPE_PEM, cert) for cert in certs)
82    cert_filename = base64.urlsafe_b64encode(hashlib.sha256(certs_pem).digest()).strip() + '.pem'
83    cert_filenames.add(cert_filename)
84    cert_path = os.path.join(CERTS_DIR, cert_filename)
85    if not os.path.exists(cert_path):
86        with open(cert_path + '.new', 'w') as cert_file:
87            cert_file.write(certs_pem)
88        os.rename(cert_path + '.new', cert_path)
89
90    for port in 443, 444:
91        yield '<VirtualHost *:{}>\n'.format(port)
92        yield '\tServerName {}\n'.format(name)
93        if aliases:
94            yield '\tServerAlias {}\n'.format(' '.join(aliases))
95        yield '\tInclude conf.d/vhost_ldap.conf\n'
96        yield '\tInclude conf.d/vhosts-common-ssl.conf\n'
97        if port == 444:
98            yield '\tInclude conf.d/vhosts-common-ssl-cert.conf\n'
99        yield '\tSSLCertificateFile {}\n'.format(cert_path)
100        yield '\tSSLCertificateKeyFile {}\n'.format(key_path)
101        yield '</VirtualHost>\n'
102
103with open(os.path.join(CERTS_DIR, '.lock'), 'w') as lock_file:
104    fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
105
106    new_vhosts_conf = \
107        '# Generated by {}.  Manual changes will be lost.\n\n'.format(os.path.realpath(__file__)) + \
108        ''.join(l for dn, vhost in vhosts for l in conf(vhost))
109
110    try:
111        with open(os.path.join(CERTS_DIR, 'vhosts.conf')) as vhosts_file:
112            old_vhosts_conf = vhosts_file.read()
113    except IOError as e:
114        if e.errno == errno.ENOENT:
115            old_vhosts_conf = None
116        else:
117            raise
118
119    if old_vhosts_conf is not None and new_vhosts_conf != old_vhosts_conf:
120        with open(os.path.join(CERTS_DIR, 'vhosts.conf.new'), 'w') as new_vhosts_file:
121            new_vhosts_file.write(new_vhosts_conf)
122        os.rename(os.path.join(CERTS_DIR, 'vhosts.conf.new'), os.path.join(CERTS_DIR, 'vhosts.conf'))
123
124        configtest = subprocess.Popen(['apachectl', 'configtest'], stderr=subprocess.PIPE)
125        e = configtest.communicate()[1]
126        if configtest.returncode == 0 and e == 'Syntax OK\n':
127            subprocess.check_call(['apachectl', 'graceful'])
128        else:
129            err('apachectl configtest failed:\n' + e)
130
131    for filename in os.listdir(CERTS_DIR):
132        if filename.endswith('.pem') and filename not in cert_filenames:
133            os.remove(os.path.join(CERTS_DIR, filename))
134
135    fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
136
137sys.exit(1 if error else 0)
Note: See TracBrowser for help on using the repository browser.