2014-06-20 01:16:38 +00:00
|
|
|
# Creates an nginx configuration file so we serve HTTP/HTTPS on all
|
|
|
|
# domains for which a mail account has been set up.
|
|
|
|
########################################################################
|
|
|
|
|
2014-10-21 11:45:14 +00:00
|
|
|
import os, os.path, shutil, re, rtyaml
|
2014-06-20 01:16:38 +00:00
|
|
|
|
|
|
|
from mailconfig import get_mail_domains
|
2014-10-28 11:38:04 +00:00
|
|
|
from dns_update import get_custom_dns_config, do_dns_update
|
2014-06-22 15:34:36 +00:00
|
|
|
from utils import shell, safe_domain_name, sort_domains
|
2014-06-20 01:16:38 +00:00
|
|
|
|
|
|
|
def get_web_domains(env):
|
2014-07-20 15:15:33 +00:00
|
|
|
# What domains should we serve websites for?
|
2014-06-20 01:16:38 +00:00
|
|
|
domains = set()
|
|
|
|
|
2014-07-20 15:15:33 +00:00
|
|
|
# At the least it's the PRIMARY_HOSTNAME so we can serve webmail
|
|
|
|
# as well as Z-Push for Exchange ActiveSync.
|
|
|
|
domains.add(env['PRIMARY_HOSTNAME'])
|
|
|
|
|
|
|
|
# Also serve web for all mail domains so that we might at least
|
|
|
|
# provide Webfinger and ActiveSync auto-discover of email settings
|
|
|
|
# (though the latter isn't really working). These will require that
|
|
|
|
# an SSL cert be installed.
|
2014-06-20 01:16:38 +00:00
|
|
|
domains |= get_mail_domains(env)
|
|
|
|
|
2014-07-20 15:15:33 +00:00
|
|
|
# ...Unless the domain has an A/AAAA record that maps it to a different
|
|
|
|
# IP address than this box. Remove those domains from our list.
|
|
|
|
dns = get_custom_dns_config(env)
|
|
|
|
for domain, value in dns.items():
|
|
|
|
if domain not in domains: continue
|
|
|
|
if (isinstance(value, str) and (value != "local")) \
|
|
|
|
or (isinstance(value, dict) and ("A" in value) and (value["A"] != "local")) \
|
|
|
|
or (isinstance(value, dict) and ("AAAA" in value) and (value["AAAA"] != "local")):
|
|
|
|
domains.remove(domain)
|
2014-06-20 01:16:38 +00:00
|
|
|
|
2014-06-30 13:15:36 +00:00
|
|
|
# Sort the list. Put PRIMARY_HOSTNAME first so it becomes the
|
2014-06-20 01:16:38 +00:00
|
|
|
# default server (nginx's default_server).
|
2014-06-22 15:34:36 +00:00
|
|
|
domains = sort_domains(domains, env)
|
2014-06-20 01:16:38 +00:00
|
|
|
|
|
|
|
return domains
|
|
|
|
|
2014-10-10 15:49:14 +00:00
|
|
|
def do_web_update(env, ok_status="web updated\n"):
|
2014-06-20 01:16:38 +00:00
|
|
|
# Build an nginx configuration file.
|
2014-08-12 11:00:54 +00:00
|
|
|
nginx_conf = open(os.path.join(os.path.dirname(__file__), "../conf/nginx-top.conf")).read()
|
|
|
|
|
|
|
|
# Add configuration for each web domain.
|
2014-08-16 12:33:10 +00:00
|
|
|
template1 = open(os.path.join(os.path.dirname(__file__), "../conf/nginx.conf")).read()
|
|
|
|
template2 = open(os.path.join(os.path.dirname(__file__), "../conf/nginx-primaryonly.conf")).read()
|
2014-06-20 01:16:38 +00:00
|
|
|
for domain in get_web_domains(env):
|
2014-08-16 12:33:10 +00:00
|
|
|
nginx_conf += make_domain_config(domain, template1, template2, env)
|
2014-06-20 01:16:38 +00:00
|
|
|
|
2014-07-06 12:16:50 +00:00
|
|
|
# Did the file change? If not, don't bother writing & restarting nginx.
|
|
|
|
nginx_conf_fn = "/etc/nginx/conf.d/local.conf"
|
|
|
|
if os.path.exists(nginx_conf_fn):
|
|
|
|
with open(nginx_conf_fn) as f:
|
|
|
|
if f.read() == nginx_conf:
|
|
|
|
return ""
|
|
|
|
|
2014-06-20 01:16:38 +00:00
|
|
|
# Save the file.
|
2014-07-06 12:16:50 +00:00
|
|
|
with open(nginx_conf_fn, "w") as f:
|
2014-06-20 01:16:38 +00:00
|
|
|
f.write(nginx_conf)
|
|
|
|
|
2014-08-17 22:43:57 +00:00
|
|
|
# Kick nginx. Since this might be called from the web admin
|
|
|
|
# don't do a 'restart'. That would kill the connection before
|
|
|
|
# the API returns its response. A 'reload' should be good
|
|
|
|
# enough and doesn't break any open connections.
|
|
|
|
shell('check_call', ["/usr/sbin/service", "nginx", "reload"])
|
2014-06-20 01:16:38 +00:00
|
|
|
|
2014-10-10 15:49:14 +00:00
|
|
|
return ok_status
|
2014-06-20 01:16:38 +00:00
|
|
|
|
2014-08-16 12:33:10 +00:00
|
|
|
def make_domain_config(domain, template, template_for_primaryhost, env):
|
2014-06-20 01:16:38 +00:00
|
|
|
# How will we configure this domain.
|
|
|
|
|
2014-06-23 10:53:09 +00:00
|
|
|
# Where will its root directory be for static files?
|
|
|
|
|
|
|
|
root = get_web_root(domain, env)
|
2014-06-20 01:16:38 +00:00
|
|
|
|
2014-06-22 15:34:36 +00:00
|
|
|
# What private key and SSL certificate will we use for this domain?
|
|
|
|
ssl_key, ssl_certificate, csr_path = get_domain_ssl_files(domain, env)
|
|
|
|
|
|
|
|
# For hostnames created after the initial setup, ensure we have an SSL certificate
|
|
|
|
# available. Make a self-signed one now if one doesn't exist.
|
|
|
|
ensure_ssl_certificate_exists(domain, ssl_key, ssl_certificate, csr_path, env)
|
|
|
|
|
2014-08-16 12:33:10 +00:00
|
|
|
# Put pieces together.
|
|
|
|
nginx_conf_parts = re.split("\s*# ADDITIONAL DIRECTIVES HERE\s*", template)
|
|
|
|
nginx_conf = nginx_conf_parts[0] + "\n"
|
|
|
|
if domain == env['PRIMARY_HOSTNAME']:
|
|
|
|
nginx_conf += template_for_primaryhost + "\n"
|
|
|
|
|
2014-06-22 15:34:36 +00:00
|
|
|
# Replace substitution strings in the template & return.
|
2014-08-15 23:10:05 +00:00
|
|
|
nginx_conf = nginx_conf.replace("$STORAGE_ROOT", env['STORAGE_ROOT'])
|
2014-06-22 15:34:36 +00:00
|
|
|
nginx_conf = nginx_conf.replace("$HOSTNAME", domain)
|
|
|
|
nginx_conf = nginx_conf.replace("$ROOT", root)
|
|
|
|
nginx_conf = nginx_conf.replace("$SSL_KEY", ssl_key)
|
|
|
|
nginx_conf = nginx_conf.replace("$SSL_CERTIFICATE", ssl_certificate)
|
2014-07-09 12:31:32 +00:00
|
|
|
|
2014-10-10 15:49:14 +00:00
|
|
|
# Because the certificate may change, we should recognize this so we
|
|
|
|
# can trigger an nginx update.
|
|
|
|
def hashfile(filepath):
|
|
|
|
import hashlib
|
|
|
|
sha1 = hashlib.sha1()
|
|
|
|
f = open(filepath, 'rb')
|
|
|
|
try:
|
|
|
|
sha1.update(f.read())
|
|
|
|
finally:
|
|
|
|
f.close()
|
|
|
|
return sha1.hexdigest()
|
|
|
|
nginx_conf += "# ssl files sha1: %s / %s\n" % (hashfile(ssl_key), hashfile(ssl_certificate))
|
|
|
|
|
2014-08-24 21:34:15 +00:00
|
|
|
# Add in any user customizations in YAML format.
|
2014-07-09 12:31:32 +00:00
|
|
|
nginx_conf_custom_fn = os.path.join(env["STORAGE_ROOT"], "www/custom.yaml")
|
|
|
|
if os.path.exists(nginx_conf_custom_fn):
|
|
|
|
yaml = rtyaml.load(open(nginx_conf_custom_fn))
|
|
|
|
if domain in yaml:
|
|
|
|
yaml = yaml[domain]
|
2014-08-16 17:43:55 +00:00
|
|
|
for path, url in yaml.get("proxies", {}).items():
|
|
|
|
nginx_conf += "\tlocation %s {\n\t\tproxy_pass %s;\n\t}\n" % (path, url)
|
2014-07-09 12:31:32 +00:00
|
|
|
|
2014-08-26 16:16:20 +00:00
|
|
|
# Add in any user customizations in the includes/ folder.
|
|
|
|
nginx_conf_custom_include = os.path.join(env["STORAGE_ROOT"], "www", safe_domain_name(domain) + ".conf")
|
|
|
|
if os.path.exists(nginx_conf_custom_include):
|
|
|
|
nginx_conf += "\tinclude %s;\n" % (nginx_conf_custom_include)
|
2014-08-24 21:34:15 +00:00
|
|
|
|
2014-08-16 12:33:10 +00:00
|
|
|
# Ending.
|
|
|
|
nginx_conf += nginx_conf_parts[1]
|
2014-07-09 12:31:32 +00:00
|
|
|
|
2014-06-22 15:34:36 +00:00
|
|
|
return nginx_conf
|
|
|
|
|
2014-10-07 16:05:38 +00:00
|
|
|
def get_web_root(domain, env, test_exists=True):
|
2014-06-23 10:53:09 +00:00
|
|
|
# Try STORAGE_ROOT/web/domain_name if it exists, but fall back to STORAGE_ROOT/web/default.
|
|
|
|
for test_domain in (domain, 'default'):
|
|
|
|
root = os.path.join(env["STORAGE_ROOT"], "www", safe_domain_name(test_domain))
|
2014-10-07 16:05:38 +00:00
|
|
|
if os.path.exists(root) or not test_exists: break
|
2014-06-23 10:53:09 +00:00
|
|
|
return root
|
|
|
|
|
2014-06-22 15:34:36 +00:00
|
|
|
def get_domain_ssl_files(domain, env):
|
2014-06-20 01:16:38 +00:00
|
|
|
# What SSL private key will we use? Allow the user to override this, but
|
|
|
|
# in many cases using the same private key for all domains would be fine.
|
2014-06-30 13:15:36 +00:00
|
|
|
# Don't allow the user to override the key for PRIMARY_HOSTNAME because
|
2014-06-20 01:16:38 +00:00
|
|
|
# that's what's in the main file.
|
|
|
|
ssl_key = os.path.join(env["STORAGE_ROOT"], 'ssl/ssl_private_key.pem')
|
2014-07-09 16:38:42 +00:00
|
|
|
ssl_key_is_alt = False
|
2014-06-30 20:41:29 +00:00
|
|
|
alt_key = os.path.join(env["STORAGE_ROOT"], 'ssl/%s/private_key.pem' % safe_domain_name(domain))
|
2014-06-30 13:15:36 +00:00
|
|
|
if domain != env['PRIMARY_HOSTNAME'] and os.path.exists(alt_key):
|
2014-06-20 01:16:38 +00:00
|
|
|
ssl_key = alt_key
|
2014-07-09 16:38:42 +00:00
|
|
|
ssl_key_is_alt = True
|
2014-06-20 01:16:38 +00:00
|
|
|
|
2014-07-09 16:38:42 +00:00
|
|
|
# What SSL certificate will we use?
|
|
|
|
ssl_certificate_primary = os.path.join(env["STORAGE_ROOT"], 'ssl/ssl_certificate.pem')
|
2014-06-30 13:15:36 +00:00
|
|
|
if domain == env['PRIMARY_HOSTNAME']:
|
2014-07-09 16:38:42 +00:00
|
|
|
# For PRIMARY_HOSTNAME, use the one we generated at set-up time.
|
|
|
|
ssl_certificate = ssl_certificate_primary
|
2014-06-20 01:16:38 +00:00
|
|
|
else:
|
2014-07-09 16:38:42 +00:00
|
|
|
# For other domains, we'll probably use a certificate in a different path.
|
2014-06-30 20:41:29 +00:00
|
|
|
ssl_certificate = os.path.join(env["STORAGE_ROOT"], 'ssl/%s/ssl_certificate.pem' % safe_domain_name(domain))
|
2014-06-20 01:16:38 +00:00
|
|
|
|
2014-07-09 16:38:42 +00:00
|
|
|
# But we can be smart and reuse the main SSL certificate if is has
|
|
|
|
# a Subject Alternative Name matching this domain. Don't do this if
|
|
|
|
# the user has uploaded a different private key for this domain.
|
|
|
|
if not ssl_key_is_alt:
|
2014-08-21 10:43:55 +00:00
|
|
|
from status_checks import check_certificate
|
2014-10-07 14:49:36 +00:00
|
|
|
if check_certificate(domain, ssl_certificate_primary, None)[0] == "OK":
|
2014-07-09 16:38:42 +00:00
|
|
|
ssl_certificate = ssl_certificate_primary
|
|
|
|
|
2014-06-30 19:49:41 +00:00
|
|
|
# Where would the CSR go? As with the SSL cert itself, the CSR must be
|
|
|
|
# different for each domain name.
|
|
|
|
if domain == env['PRIMARY_HOSTNAME']:
|
|
|
|
csr_path = os.path.join(env["STORAGE_ROOT"], 'ssl/ssl_cert_sign_req.csr')
|
|
|
|
else:
|
2014-06-30 20:41:29 +00:00
|
|
|
csr_path = os.path.join(env["STORAGE_ROOT"], 'ssl/%s/certificate_signing_request.csr' % safe_domain_name(domain))
|
2014-06-22 15:34:36 +00:00
|
|
|
|
|
|
|
return ssl_key, ssl_certificate, csr_path
|
|
|
|
|
|
|
|
def ensure_ssl_certificate_exists(domain, ssl_key, ssl_certificate, csr_path, env):
|
2014-07-09 16:38:42 +00:00
|
|
|
# For domains besides PRIMARY_HOSTNAME, generate a self-signed certificate if
|
|
|
|
# a certificate doesn't already exist. See setup/mail.sh for documentation.
|
2014-06-22 15:34:36 +00:00
|
|
|
|
2014-06-30 13:15:36 +00:00
|
|
|
if domain == env['PRIMARY_HOSTNAME']:
|
2014-06-22 15:34:36 +00:00
|
|
|
return
|
|
|
|
|
2014-07-09 16:38:42 +00:00
|
|
|
# Sanity check. Shouldn't happen. A non-primary domain might use this
|
|
|
|
# certificate (see above), but then the certificate should exist anyway.
|
|
|
|
if ssl_certificate == os.path.join(env["STORAGE_ROOT"], 'ssl/ssl_certificate.pem'):
|
|
|
|
return
|
|
|
|
|
2014-06-22 15:34:36 +00:00
|
|
|
if os.path.exists(ssl_certificate):
|
|
|
|
return
|
|
|
|
|
|
|
|
os.makedirs(os.path.dirname(ssl_certificate), exist_ok=True)
|
|
|
|
|
|
|
|
# Generate a new self-signed certificate using the same private key that we already have.
|
|
|
|
|
|
|
|
# Start with a CSR.
|
2014-10-10 15:49:14 +00:00
|
|
|
with open(csr_path, "w") as f:
|
|
|
|
f.write(create_csr(domain, ssl_key, env))
|
2014-06-22 15:34:36 +00:00
|
|
|
|
|
|
|
# And then make the certificate.
|
|
|
|
shell("check_call", [
|
|
|
|
"openssl", "x509", "-req",
|
|
|
|
"-days", "365",
|
|
|
|
"-in", csr_path,
|
|
|
|
"-signkey", ssl_key,
|
|
|
|
"-out", ssl_certificate])
|
|
|
|
|
2014-10-10 15:49:14 +00:00
|
|
|
def create_csr(domain, ssl_key, env):
|
|
|
|
return shell("check_output", [
|
|
|
|
"openssl", "req", "-new",
|
|
|
|
"-key", ssl_key,
|
|
|
|
"-out", "/dev/stdout",
|
|
|
|
"-sha256",
|
|
|
|
"-subj", "/C=%s/ST=/L=/O=/CN=%s" % (env["CSR_COUNTRY"], domain)])
|
|
|
|
|
|
|
|
def install_cert(domain, ssl_cert, ssl_chain, env):
|
|
|
|
if domain not in get_web_domains(env):
|
|
|
|
return "Invalid domain name."
|
|
|
|
|
|
|
|
# Write the combined cert+chain to a temporary path and validate that it is OK.
|
|
|
|
# The certificate always goes above the chain.
|
|
|
|
import tempfile, os
|
|
|
|
fd, fn = tempfile.mkstemp('.pem')
|
|
|
|
os.write(fd, (ssl_cert + '\n' + ssl_chain).encode("ascii"))
|
|
|
|
os.close(fd)
|
|
|
|
|
|
|
|
# Do validation on the certificate before installing it.
|
|
|
|
from status_checks import check_certificate
|
|
|
|
ssl_key, ssl_certificate, ssl_csr_path = get_domain_ssl_files(domain, env)
|
|
|
|
cert_status, cert_status_details = check_certificate(domain, fn, ssl_key)
|
|
|
|
if cert_status != "OK":
|
|
|
|
if cert_status == "SELF-SIGNED":
|
|
|
|
cert_status = "This is a self-signed certificate. I can't install that."
|
|
|
|
os.unlink(fn)
|
2014-10-24 21:30:33 +00:00
|
|
|
if cert_status_details is not None:
|
|
|
|
cert_status += " " + cert_status_details
|
2014-10-10 15:49:14 +00:00
|
|
|
return cert_status
|
|
|
|
|
|
|
|
# Copy the certificate to its expected location.
|
|
|
|
os.makedirs(os.path.dirname(ssl_certificate), exist_ok=True)
|
2014-10-21 11:45:14 +00:00
|
|
|
shutil.move(fn, ssl_certificate)
|
2014-10-10 15:49:14 +00:00
|
|
|
|
2014-10-28 11:38:04 +00:00
|
|
|
ret = []
|
|
|
|
|
|
|
|
# When updating the cert for PRIMARY_HOSTNAME, also update DNS because it is
|
|
|
|
# used in the DANE TLSA record and restart postfix and dovecot which use
|
|
|
|
# that certificate.
|
|
|
|
if domain == env['PRIMARY_HOSTNAME']:
|
|
|
|
ret.append( do_dns_update(env) )
|
|
|
|
|
|
|
|
shell('check_call', ["/usr/sbin/service", "postfix", "restart"])
|
|
|
|
shell('check_call', ["/usr/sbin/service", "dovecot", "restart"])
|
|
|
|
ret.append("mail services restarted")
|
|
|
|
|
2014-10-10 15:49:14 +00:00
|
|
|
# Kick nginx so it sees the cert.
|
2014-10-28 11:38:04 +00:00
|
|
|
ret.append( do_web_update(env, ok_status="") )
|
|
|
|
return "\n".join(r for r in ret if r.strip() != "")
|
2014-10-10 15:49:14 +00:00
|
|
|
|
2014-10-07 16:05:38 +00:00
|
|
|
def get_web_domains_info(env):
|
2014-10-10 15:49:14 +00:00
|
|
|
def check_cert(domain):
|
|
|
|
from status_checks import check_certificate
|
|
|
|
ssl_key, ssl_certificate, ssl_csr_path = get_domain_ssl_files(domain, env)
|
|
|
|
if not os.path.exists(ssl_certificate):
|
|
|
|
return ("danger", "No Certificate Installed")
|
|
|
|
cert_status, cert_status_details = check_certificate(domain, ssl_certificate, ssl_key)
|
|
|
|
if cert_status == "OK":
|
|
|
|
return ("success", "Signed & valid. " + cert_status_details)
|
|
|
|
elif cert_status == "SELF-SIGNED":
|
|
|
|
return ("warning", "Self-signed. Get a signed certificate to stop warnings.")
|
|
|
|
else:
|
|
|
|
return ("danger", "Certificate has a problem: " + cert_status)
|
|
|
|
|
2014-10-07 16:05:38 +00:00
|
|
|
return [
|
|
|
|
{
|
|
|
|
"domain": domain,
|
|
|
|
"root": get_web_root(domain, env),
|
|
|
|
"custom_root": get_web_root(domain, env, test_exists=False),
|
2014-10-10 15:49:14 +00:00
|
|
|
"ssl_certificate": check_cert(domain),
|
2014-10-07 16:05:38 +00:00
|
|
|
}
|
|
|
|
for domain in get_web_domains(env)
|
|
|
|
]
|