1 | #!/usr/bin/python |
---|
2 | |
---|
3 | import base64 |
---|
4 | import hashlib |
---|
5 | import ldap |
---|
6 | import os |
---|
7 | import sys |
---|
8 | import textwrap |
---|
9 | |
---|
10 | CERTS_DIR = '/var/lib/scripts-certs' |
---|
11 | |
---|
12 | ll = ldap.initialize('ldapi://%2fvar%2frun%2fslapd-scripts.socket/') |
---|
13 | with open('/etc/signup-ldap-pw') as pw_file: |
---|
14 | ll.simple_bind_s("cn=Directory Manager", pw_file.read()) |
---|
15 | |
---|
16 | if not os.path.exists(CERTS_DIR): |
---|
17 | os.mkdir(CERTS_DIR) |
---|
18 | |
---|
19 | vhosts = ll.search_s( |
---|
20 | 'ou=VirtualHosts,dc=scripts,dc=mit,dc=edu', |
---|
21 | ldap.SCOPE_SUBTREE, |
---|
22 | '(&(objectClass=scriptsVhost)(scriptsVhostCertificate=*))', |
---|
23 | ['scriptsVhostName', 'scriptsVhostAlias', 'scriptsVhostCertificate', 'scriptsVhostCertificateKeyFile']) |
---|
24 | |
---|
25 | vhosts.sort(key=lambda (dn, vhost): vhost['scriptsVhostName']) |
---|
26 | |
---|
27 | def conf(vhost): |
---|
28 | name, = vhost['scriptsVhostName'] |
---|
29 | aliases = vhost.get('scriptsVhostAlias', []) |
---|
30 | certs, = vhost['scriptsVhostCertificate'] |
---|
31 | key_filename, = vhost['scriptsVhostCertificateKeyFile'] |
---|
32 | |
---|
33 | certs = ''.join('-----BEGIN CERTIFICATE-----\n' + '\n'.join(textwrap.wrap(cert, 64)) + '\n-----END CERTIFICATE-----\n' for cert in certs.split()) |
---|
34 | cert_filename = os.path.join(CERTS_DIR, base64.urlsafe_b64encode(hashlib.sha256(certs).digest()).strip() + '.pem') |
---|
35 | if not os.path.exists(cert_filename): |
---|
36 | with open(cert_filename + '.new', 'w') as cert_file: |
---|
37 | cert_file.write(certs) |
---|
38 | os.rename(cert_filename + '.new', cert_filename) |
---|
39 | |
---|
40 | for port in 443, 444: |
---|
41 | yield '<VirtualHost *:{}>\n'.format(port) |
---|
42 | yield '\tServerName {}\n'.format(name) |
---|
43 | if aliases: |
---|
44 | yield '\tServerAlias {}\n'.format(' '.join(aliases)) |
---|
45 | yield '\tInclude conf.d/vhost_ldap.conf\n' |
---|
46 | yield '\tInclude conf.d/vhosts-common-ssl.conf\n' |
---|
47 | if port == 444: |
---|
48 | yield '\tInclude conf.d/vhosts-common-ssl-cert.conf\n' |
---|
49 | yield '\tSSLCertificateFile {}\n'.format(cert_filename) |
---|
50 | yield '\tSSLCertificateKeyFile {}\n'.format(os.path.join('/etc/pki/tls/private', key_filename)) |
---|
51 | yield '</VirtualHost>\n' |
---|
52 | |
---|
53 | with open(os.path.join(CERTS_DIR, 'vhosts.conf.new'), 'w') as vhosts_file: |
---|
54 | vhosts_file.write('# Generated by {}. Manual changes will be lost.\n\n'.format(os.path.realpath(__file__))) |
---|
55 | vhosts_file.write(''.join(l for dn, vhost in vhosts for l in conf(vhost))) |
---|
56 | os.rename(os.path.join(CERTS_DIR, 'vhosts.conf.new'), os.path.join(CERTS_DIR, 'vhosts.conf')) |
---|