|
|
|
|
@@ -9,7 +9,6 @@ import ipaddress
|
|
|
|
|
import rtyaml
|
|
|
|
|
import dns.resolver
|
|
|
|
|
|
|
|
|
|
from mailconfig import get_mail_domains, get_mail_aliases
|
|
|
|
|
from utils import shell, load_env_vars_from_file, safe_domain_name, sort_domains
|
|
|
|
|
from ssl_certificates import get_ssl_certificates, check_certificate
|
|
|
|
|
|
|
|
|
|
@@ -20,10 +19,14 @@ from ssl_certificates import get_ssl_certificates, check_certificate
|
|
|
|
|
DOMAIN_RE = "^(?!\-)(?:[*][.])?(?:[a-zA-Z\d\-_]{0,62}[a-zA-Z\d_]\.){1,126}(?!\d+)[a-zA-Z\d_]{1,63}(\.?)$"
|
|
|
|
|
|
|
|
|
|
def get_dns_domains(env):
|
|
|
|
|
# Add all domain names in use by email users and mail aliases and ensure
|
|
|
|
|
# PRIMARY_HOSTNAME is in the list.
|
|
|
|
|
# Add all domain names in use by email users and mail aliases, any
|
|
|
|
|
# domains we serve web for (except www redirects because that would
|
|
|
|
|
# lead to infinite recursion here) and ensure PRIMARY_HOSTNAME is in the list.
|
|
|
|
|
from mailconfig import get_mail_domains
|
|
|
|
|
from web_update import get_web_domains
|
|
|
|
|
domains = set()
|
|
|
|
|
domains |= get_mail_domains(env)
|
|
|
|
|
domains |= set(get_mail_domains(env))
|
|
|
|
|
domains |= set(get_web_domains(env, include_www_redirects=False))
|
|
|
|
|
domains.add(env['PRIMARY_HOSTNAME'])
|
|
|
|
|
return domains
|
|
|
|
|
|
|
|
|
|
@@ -97,7 +100,8 @@ def do_dns_update(env, force=False):
|
|
|
|
|
if len(updated_domains) > 0:
|
|
|
|
|
shell('check_call', ["/usr/sbin/service", "nsd", "restart"])
|
|
|
|
|
|
|
|
|
|
# Write the OpenDKIM configuration tables for all of the domains.
|
|
|
|
|
# Write the OpenDKIM configuration tables for all of the mail domains.
|
|
|
|
|
from mailconfig import get_mail_domains
|
|
|
|
|
if write_opendkim_tables(get_mail_domains(env), env):
|
|
|
|
|
# Settings changed. Kick opendkim.
|
|
|
|
|
shell('check_call', ["/usr/sbin/service", "opendkim", "restart"])
|
|
|
|
|
@@ -122,18 +126,47 @@ def build_zones(env):
|
|
|
|
|
domains = get_dns_domains(env)
|
|
|
|
|
zonefiles = get_dns_zones(env)
|
|
|
|
|
|
|
|
|
|
# Custom records to add to zones.
|
|
|
|
|
additional_records = list(get_custom_dns_config(env))
|
|
|
|
|
# Create a dictionary of domains to a set of attributes for each
|
|
|
|
|
# domain, such as whether there are mail users at the domain.
|
|
|
|
|
from mailconfig import get_mail_domains
|
|
|
|
|
from web_update import get_web_domains
|
|
|
|
|
www_redirect_domains = set(get_web_domains(env)) - set(get_web_domains(env, include_www_redirects=False))
|
|
|
|
|
mail_domains = set(get_mail_domains(env))
|
|
|
|
|
mail_user_domains = set(get_mail_domains(env, users_only=True)) # i.e. will log in for mail, Nextcloud
|
|
|
|
|
web_domains = set(get_web_domains(env))
|
|
|
|
|
auto_domains = web_domains - set(get_web_domains(env, include_auto=False))
|
|
|
|
|
domains |= auto_domains # www redirects not included in the initial list, see above
|
|
|
|
|
|
|
|
|
|
# Add ns1/ns2+PRIMARY_HOSTNAME which must also have A/AAAA records
|
|
|
|
|
# when the box is acting as authoritative DNS server for its domains.
|
|
|
|
|
for ns in ("ns1", "ns2"):
|
|
|
|
|
d = ns + "." + env["PRIMARY_HOSTNAME"]
|
|
|
|
|
domains.add(d)
|
|
|
|
|
auto_domains.add(d)
|
|
|
|
|
|
|
|
|
|
domains = {
|
|
|
|
|
domain: {
|
|
|
|
|
"user": domain in mail_user_domains,
|
|
|
|
|
"mail": domain in mail_domains,
|
|
|
|
|
"web": domain in web_domains,
|
|
|
|
|
"auto": domain in auto_domains,
|
|
|
|
|
}
|
|
|
|
|
for domain in domains
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
# For MTA-STS, we'll need to check if the PRIMARY_HOSTNAME certificate is
|
|
|
|
|
# singned and valid. Check that now rather than repeatedly for each domain.
|
|
|
|
|
domains[env["PRIMARY_HOSTNAME"]]["certificate-is-valid"] = is_domain_cert_signed_and_valid(env["PRIMARY_HOSTNAME"], env)
|
|
|
|
|
|
|
|
|
|
# Load custom records to add to zones.
|
|
|
|
|
additional_records = list(get_custom_dns_config(env))
|
|
|
|
|
|
|
|
|
|
# Build DNS records for each zone.
|
|
|
|
|
for domain, zonefile in zonefiles:
|
|
|
|
|
# Build the records to put in the zone.
|
|
|
|
|
records = build_zone(domain, domains, additional_records, www_redirect_domains, env)
|
|
|
|
|
records = build_zone(domain, domains, additional_records, env)
|
|
|
|
|
yield (domain, zonefile, records)
|
|
|
|
|
|
|
|
|
|
def build_zone(domain, all_domains, additional_records, www_redirect_domains, env, is_zone=True):
|
|
|
|
|
def build_zone(domain, domain_properties, additional_records, env, is_zone=True):
|
|
|
|
|
records = []
|
|
|
|
|
|
|
|
|
|
# For top-level zones, define the authoritative name servers.
|
|
|
|
|
@@ -170,15 +203,6 @@ def build_zone(domain, all_domains, additional_records, www_redirect_domains, en
|
|
|
|
|
|
|
|
|
|
# In PRIMARY_HOSTNAME...
|
|
|
|
|
if domain == env["PRIMARY_HOSTNAME"]:
|
|
|
|
|
# Define ns1 and ns2.
|
|
|
|
|
# 'False' in the tuple indicates these records would not be used if the zone
|
|
|
|
|
# is managed outside of the box.
|
|
|
|
|
records.append(("ns1", "A", env["PUBLIC_IP"], False))
|
|
|
|
|
records.append(("ns2", "A", env["PUBLIC_IP"], False))
|
|
|
|
|
if env.get('PUBLIC_IPV6'):
|
|
|
|
|
records.append(("ns1", "AAAA", env["PUBLIC_IPV6"], False))
|
|
|
|
|
records.append(("ns2", "AAAA", env["PUBLIC_IPV6"], False))
|
|
|
|
|
|
|
|
|
|
# Set the A/AAAA records. Do this early for the PRIMARY_HOSTNAME so that the user cannot override them
|
|
|
|
|
# and we can provide different explanatory text.
|
|
|
|
|
records.append((None, "A", env["PUBLIC_IP"], "Required. Sets the IP address of the box."))
|
|
|
|
|
@@ -196,16 +220,17 @@ def build_zone(domain, all_domains, additional_records, www_redirect_domains, en
|
|
|
|
|
|
|
|
|
|
# Add DNS records for any subdomains of this domain. We should not have a zone for
|
|
|
|
|
# both a domain and one of its subdomains.
|
|
|
|
|
subdomains = [d for d in all_domains if d.endswith("." + domain)]
|
|
|
|
|
for subdomain in subdomains:
|
|
|
|
|
subdomain_qname = subdomain[0:-len("." + domain)]
|
|
|
|
|
subzone = build_zone(subdomain, [], additional_records, www_redirect_domains, env, is_zone=False)
|
|
|
|
|
for child_qname, child_rtype, child_value, child_explanation in subzone:
|
|
|
|
|
if child_qname == None:
|
|
|
|
|
child_qname = subdomain_qname
|
|
|
|
|
else:
|
|
|
|
|
child_qname += "." + subdomain_qname
|
|
|
|
|
records.append((child_qname, child_rtype, child_value, child_explanation))
|
|
|
|
|
if is_zone: # don't recurse when we're just loading data for a subdomain
|
|
|
|
|
subdomains = [d for d in domain_properties if d.endswith("." + domain)]
|
|
|
|
|
for subdomain in subdomains:
|
|
|
|
|
subdomain_qname = subdomain[0:-len("." + domain)]
|
|
|
|
|
subzone = build_zone(subdomain, domain_properties, additional_records, env, is_zone=False)
|
|
|
|
|
for child_qname, child_rtype, child_value, child_explanation in subzone:
|
|
|
|
|
if child_qname == None:
|
|
|
|
|
child_qname = subdomain_qname
|
|
|
|
|
else:
|
|
|
|
|
child_qname += "." + subdomain_qname
|
|
|
|
|
records.append((child_qname, child_rtype, child_value, child_explanation))
|
|
|
|
|
|
|
|
|
|
has_rec_base = list(records) # clone current state
|
|
|
|
|
def has_rec(qname, rtype, prefix=None):
|
|
|
|
|
@@ -232,21 +257,23 @@ def build_zone(domain, all_domains, additional_records, www_redirect_domains, en
|
|
|
|
|
continue
|
|
|
|
|
records.append((qname, rtype, value, "(Set by user.)"))
|
|
|
|
|
|
|
|
|
|
# Add defaults if not overridden by the user's custom settings (and not otherwise configured).
|
|
|
|
|
# Add A/AAAA defaults if not overridden by the user's custom settings (and not otherwise configured).
|
|
|
|
|
# Any CNAME or A record on the qname overrides A and AAAA. But when we set the default A record,
|
|
|
|
|
# we should not cause the default AAAA record to be skipped because it thinks a custom A record
|
|
|
|
|
# was set. So set has_rec_base to a clone of the current set of DNS settings, and don't update
|
|
|
|
|
# during this process.
|
|
|
|
|
has_rec_base = list(records)
|
|
|
|
|
a_expl = "Required. May have a different value. Sets the IP address that %s resolves to for web hosting and other services besides mail. The A record must be present but its value does not affect mail delivery." % domain
|
|
|
|
|
if domain_properties[domain]["auto"]:
|
|
|
|
|
if domain.startswith("ns1.") or domain.startswith("ns2."): a_expl = False # omit from 'External DNS' page since this only applies if box is its own DNS server
|
|
|
|
|
if domain.startswith("www."): a_expl = "Optional. Sets the IP address that %s resolves to so that the box can provide a redirect to the parent domain." % domain
|
|
|
|
|
if domain.startswith("mta-sts."): a_expl = "Optional. MTA-STS Policy Host serving /.well-known/mta-sts.txt."
|
|
|
|
|
if domain.startswith("autoconfig."): a_expl = "Provides email configuration autodiscovery support for Thunderbird Autoconfig."
|
|
|
|
|
if domain.startswith("autodiscover."): a_expl = "Provides email configuration autodiscovery support for Z-Push ActiveSync Autodiscover."
|
|
|
|
|
defaults = [
|
|
|
|
|
(None, "A", env["PUBLIC_IP"], "Required. May have a different value. Sets the IP address that %s resolves to for web hosting and other services besides mail. The A record must be present but its value does not affect mail delivery." % domain),
|
|
|
|
|
(None, "A", env["PUBLIC_IP"], a_expl),
|
|
|
|
|
(None, "AAAA", env.get('PUBLIC_IPV6'), "Optional. Sets the IPv6 address that %s resolves to, e.g. for web hosting. (It is not necessary for receiving mail on this domain.)" % domain),
|
|
|
|
|
]
|
|
|
|
|
if "www." + domain in www_redirect_domains:
|
|
|
|
|
defaults += [
|
|
|
|
|
("www", "A", env["PUBLIC_IP"], "Optional. Sets the IP address that www.%s resolves to so that the box can provide a redirect to the parent domain." % domain),
|
|
|
|
|
("www", "AAAA", env.get('PUBLIC_IPV6'), "Optional. Sets the IPv6 address that www.%s resolves to so that the box can provide a redirect to the parent domain." % domain),
|
|
|
|
|
]
|
|
|
|
|
for qname, rtype, value, explanation in defaults:
|
|
|
|
|
if value is None or value.strip() == "": continue # skip IPV6 if not set
|
|
|
|
|
if not is_zone and qname == "www": continue # don't create any default 'www' subdomains on what are themselves subdomains
|
|
|
|
|
@@ -260,63 +287,40 @@ def build_zone(domain, all_domains, additional_records, www_redirect_domains, en
|
|
|
|
|
# Don't pin the list of records that has_rec checks against anymore.
|
|
|
|
|
has_rec_base = records
|
|
|
|
|
|
|
|
|
|
# The MX record says where email for the domain should be delivered: Here!
|
|
|
|
|
if not has_rec(None, "MX", prefix="10 "):
|
|
|
|
|
records.append((None, "MX", "10 %s." % env["PRIMARY_HOSTNAME"], "Required. Specifies the hostname (and priority) of the machine that handles @%s mail." % domain))
|
|
|
|
|
if domain_properties[domain]["mail"]:
|
|
|
|
|
# The MX record says where email for the domain should be delivered: Here!
|
|
|
|
|
if not has_rec(None, "MX", prefix="10 "):
|
|
|
|
|
records.append((None, "MX", "10 %s." % env["PRIMARY_HOSTNAME"], "Required. Specifies the hostname (and priority) of the machine that handles @%s mail." % domain))
|
|
|
|
|
|
|
|
|
|
# SPF record: Permit the box ('mx', see above) to send mail on behalf of
|
|
|
|
|
# the domain, and no one else.
|
|
|
|
|
# Skip if the user has set a custom SPF record.
|
|
|
|
|
if not has_rec(None, "TXT", prefix="v=spf1 "):
|
|
|
|
|
records.append((None, "TXT", 'v=spf1 mx -all', "Recommended. Specifies that only the box is permitted to send @%s mail." % domain))
|
|
|
|
|
# SPF record: Permit the box ('mx', see above) to send mail on behalf of
|
|
|
|
|
# the domain, and no one else.
|
|
|
|
|
# Skip if the user has set a custom SPF record.
|
|
|
|
|
if not has_rec(None, "TXT", prefix="v=spf1 "):
|
|
|
|
|
records.append((None, "TXT", 'v=spf1 mx -all', "Recommended. Specifies that only the box is permitted to send @%s mail." % domain))
|
|
|
|
|
|
|
|
|
|
# Append the DKIM TXT record to the zone as generated by OpenDKIM.
|
|
|
|
|
# Skip if the user has set a DKIM record already.
|
|
|
|
|
opendkim_record_file = os.path.join(env['STORAGE_ROOT'], 'mail/dkim/mail.txt')
|
|
|
|
|
with open(opendkim_record_file) as orf:
|
|
|
|
|
m = re.match(r'(\S+)\s+IN\s+TXT\s+\( ((?:"[^"]+"\s+)+)\)', orf.read(), re.S)
|
|
|
|
|
val = "".join(re.findall(r'"([^"]+)"', m.group(2)))
|
|
|
|
|
if not has_rec(m.group(1), "TXT", prefix="v=DKIM1; "):
|
|
|
|
|
records.append((m.group(1), "TXT", val, "Recommended. Provides a way for recipients to verify that this machine sent @%s mail." % domain))
|
|
|
|
|
# Append the DKIM TXT record to the zone as generated by OpenDKIM.
|
|
|
|
|
# Skip if the user has set a DKIM record already.
|
|
|
|
|
opendkim_record_file = os.path.join(env['STORAGE_ROOT'], 'mail/dkim/mail.txt')
|
|
|
|
|
with open(opendkim_record_file) as orf:
|
|
|
|
|
m = re.match(r'(\S+)\s+IN\s+TXT\s+\( ((?:"[^"]+"\s+)+)\)', orf.read(), re.S)
|
|
|
|
|
val = "".join(re.findall(r'"([^"]+)"', m.group(2)))
|
|
|
|
|
if not has_rec(m.group(1), "TXT", prefix="v=DKIM1; "):
|
|
|
|
|
records.append((m.group(1), "TXT", val, "Recommended. Provides a way for recipients to verify that this machine sent @%s mail." % domain))
|
|
|
|
|
|
|
|
|
|
# Append a DMARC record.
|
|
|
|
|
# Skip if the user has set a DMARC record already.
|
|
|
|
|
if not has_rec("_dmarc", "TXT", prefix="v=DMARC1; "):
|
|
|
|
|
records.append(("_dmarc", "TXT", 'v=DMARC1; p=quarantine', "Recommended. Specifies that mail that does not originate from the box but claims to be from @%s or which does not have a valid DKIM signature is suspect and should be quarantined by the recipient's mail system." % domain))
|
|
|
|
|
# Append a DMARC record.
|
|
|
|
|
# Skip if the user has set a DMARC record already.
|
|
|
|
|
if not has_rec("_dmarc", "TXT", prefix="v=DMARC1; "):
|
|
|
|
|
records.append(("_dmarc", "TXT", 'v=DMARC1; p=quarantine', "Recommended. Specifies that mail that does not originate from the box but claims to be from @%s or which does not have a valid DKIM signature is suspect and should be quarantined by the recipient's mail system." % domain))
|
|
|
|
|
|
|
|
|
|
# For any subdomain with an A record but no SPF or DMARC record, add strict policy records.
|
|
|
|
|
all_resolvable_qnames = set(r[0] for r in records if r[1] in ("A", "AAAA"))
|
|
|
|
|
for qname in all_resolvable_qnames:
|
|
|
|
|
if not has_rec(qname, "TXT", prefix="v=spf1 "):
|
|
|
|
|
records.append((qname, "TXT", 'v=spf1 -all', "Recommended. Prevents use of this domain name for outbound mail by specifying that no servers are valid sources for mail from @%s. If you do send email from this domain name you should either override this record such that the SPF rule does allow the originating server, or, take the recommended approach and have the box handle mail for this domain (simply add any receiving alias at this domain name to make this machine treat the domain name as one of its mail domains)." % (qname + "." + domain)))
|
|
|
|
|
dmarc_qname = "_dmarc" + ("" if qname is None else "." + qname)
|
|
|
|
|
if not has_rec(dmarc_qname, "TXT", prefix="v=DMARC1; "):
|
|
|
|
|
records.append((dmarc_qname, "TXT", 'v=DMARC1; p=reject', "Recommended. Prevents use of this domain name for outbound mail by specifying that the SPF rule should be honoured for mail from @%s." % (qname + "." + domain)))
|
|
|
|
|
|
|
|
|
|
# Add CardDAV/CalDAV SRV records on the non-primary hostname that points to the primary hostname
|
|
|
|
|
# for autoconfiguration of mail clients (so only domains hosting user accounts need it).
|
|
|
|
|
# The SRV record format is priority (0, whatever), weight (0, whatever), port, service provider hostname (w/ trailing dot).
|
|
|
|
|
if domain != env["PRIMARY_HOSTNAME"] and domain in get_mail_domains(env, users_only=True):
|
|
|
|
|
for dav in ("card", "cal"):
|
|
|
|
|
qname = "_" + dav + "davs._tcp"
|
|
|
|
|
if not has_rec(qname, "SRV"):
|
|
|
|
|
records.append((qname, "SRV", "0 0 443 " + env["PRIMARY_HOSTNAME"] + ".", "Recommended. Specifies the hostname of the server that handles CardDAV/CalDAV services for email addresses on this domain."))
|
|
|
|
|
|
|
|
|
|
# Adds autoconfiguration A records for all domains that there are user accounts at.
|
|
|
|
|
# This allows the following clients to automatically configure email addresses in the respective applications.
|
|
|
|
|
# autodiscover.* - Z-Push ActiveSync Autodiscover
|
|
|
|
|
# autoconfig.* - Thunderbird Autoconfig
|
|
|
|
|
if domain in get_mail_domains(env, users_only=True):
|
|
|
|
|
autodiscover_records = [
|
|
|
|
|
("autodiscover", "A", env["PUBLIC_IP"], "Provides email configuration autodiscovery support for Z-Push ActiveSync Autodiscover."),
|
|
|
|
|
("autodiscover", "AAAA", env["PUBLIC_IPV6"], "Provides email configuration autodiscovery support for Z-Push ActiveSync Autodiscover."),
|
|
|
|
|
("autoconfig", "A", env["PUBLIC_IP"], "Provides email configuration autodiscovery support for Thunderbird Autoconfig."),
|
|
|
|
|
("autoconfig", "AAAA", env["PUBLIC_IPV6"], "Provides email configuration autodiscovery support for Thunderbird Autoconfig.")
|
|
|
|
|
]
|
|
|
|
|
for qname, rtype, value, explanation in autodiscover_records:
|
|
|
|
|
if value is None or value.strip() == "": continue # skip IPV6 if not set
|
|
|
|
|
if not has_rec(qname, rtype):
|
|
|
|
|
records.append((qname, rtype, value, explanation))
|
|
|
|
|
if domain_properties[domain]["user"]:
|
|
|
|
|
# Add CardDAV/CalDAV SRV records on the non-primary hostname that points to the primary hostname
|
|
|
|
|
# for autoconfiguration of mail clients (so only domains hosting user accounts need it).
|
|
|
|
|
# The SRV record format is priority (0, whatever), weight (0, whatever), port, service provider hostname (w/ trailing dot).
|
|
|
|
|
if domain != env["PRIMARY_HOSTNAME"]:
|
|
|
|
|
for dav in ("card", "cal"):
|
|
|
|
|
qname = "_" + dav + "davs._tcp"
|
|
|
|
|
if not has_rec(qname, "SRV"):
|
|
|
|
|
records.append((qname, "SRV", "0 0 443 " + env["PRIMARY_HOSTNAME"] + ".", "Recommended. Specifies the hostname of the server that handles CardDAV/CalDAV services for email addresses on this domain."))
|
|
|
|
|
|
|
|
|
|
# If this is a domain name that there are email addresses configured for, i.e. "something@"
|
|
|
|
|
# this domain name, then the domain name is a MTA-STS (https://tools.ietf.org/html/rfc8461)
|
|
|
|
|
@@ -333,25 +337,12 @@ def build_zone(domain, all_domains, additional_records, www_redirect_domains, en
|
|
|
|
|
# subdomain must be valid certificate for that domain. Do not set an MTA-STS policy if either
|
|
|
|
|
# certificate in use is not valid (e.g. because it is self-signed and a valid certificate has not
|
|
|
|
|
# yet been provisioned). Since we cannot provision a certificate without A/AAAA records, we
|
|
|
|
|
# always set them --- only the TXT records depend on there being valid certificates.
|
|
|
|
|
mta_sts_enabled = False
|
|
|
|
|
mta_sts_records = [
|
|
|
|
|
("mta-sts", "A", env["PUBLIC_IP"], "Optional. MTA-STS Policy Host serving /.well-known/mta-sts.txt."),
|
|
|
|
|
("mta-sts", "AAAA", env.get('PUBLIC_IPV6'), "Optional. MTA-STS Policy Host serving /.well-known/mta-sts.txt."),
|
|
|
|
|
]
|
|
|
|
|
if domain in get_mail_domains(env):
|
|
|
|
|
# Check that PRIMARY_HOSTNAME and the mta_sts domain both have valid certificates.
|
|
|
|
|
for d in (env['PRIMARY_HOSTNAME'], "mta-sts." + domain):
|
|
|
|
|
cert = get_ssl_certificates(env).get(d)
|
|
|
|
|
if not cert:
|
|
|
|
|
break # no certificate provisioned for this domain
|
|
|
|
|
cert_status = check_certificate(d, cert['certificate'], cert['private-key'])
|
|
|
|
|
if cert_status[0] != 'OK':
|
|
|
|
|
break # certificate is not valid
|
|
|
|
|
else:
|
|
|
|
|
# 'break' was not encountered above, so both domains are good
|
|
|
|
|
mta_sts_enabled = True
|
|
|
|
|
if mta_sts_enabled:
|
|
|
|
|
# always set them (by including them in the www domains) --- only the TXT records depend on there
|
|
|
|
|
# being valid certificates.
|
|
|
|
|
mta_sts_records = [ ]
|
|
|
|
|
if domain_properties[domain]["mail"] \
|
|
|
|
|
and domain_properties[env["PRIMARY_HOSTNAME"]]["certificate-is-valid"] \
|
|
|
|
|
and is_domain_cert_signed_and_valid("mta-sts." + domain, env):
|
|
|
|
|
# Compute an up-to-32-character hash of the policy file. We'll take a SHA-1 hash of the policy
|
|
|
|
|
# file (20 bytes) and encode it as base-64 (28 bytes, using alphanumeric alternate characters
|
|
|
|
|
# instead of '+' and '/' which are not allowed in an MTA-STS policy id) but then just take its
|
|
|
|
|
@@ -368,15 +359,39 @@ def build_zone(domain, all_domains, additional_records, www_redirect_domains, en
|
|
|
|
|
if env.get("MTA_STS_TLSRPT_RUA") and not has_rec("_smtp._tls", "TXT", prefix="v=TLSRPTv1;"):
|
|
|
|
|
mta_sts_records.append(("_smtp._tls", "TXT", "v=TLSRPTv1; rua=" + env["MTA_STS_TLSRPT_RUA"], "Optional. Enables MTA-STS reporting."))
|
|
|
|
|
for qname, rtype, value, explanation in mta_sts_records:
|
|
|
|
|
if value is None or value.strip() == "": continue # skip IPV6 if not set
|
|
|
|
|
if not has_rec(qname, rtype):
|
|
|
|
|
records.append((qname, rtype, value, explanation))
|
|
|
|
|
|
|
|
|
|
# Add no-mail-here records for any qname that has an A or AAAA record
|
|
|
|
|
# but no MX record. This would include domain itself if domain is a
|
|
|
|
|
# non-mail domain and also may include qnames from custom DNS records.
|
|
|
|
|
# Do this once at the end of generating a zone.
|
|
|
|
|
if is_zone:
|
|
|
|
|
qnames_with_a = set(qname for (qname, rtype, value, explanation) in records if rtype in ("A", "AAAA"))
|
|
|
|
|
qnames_with_mx = set(qname for (qname, rtype, value, explanation) in records if rtype == "MX")
|
|
|
|
|
for qname in qnames_with_a - qnames_with_mx:
|
|
|
|
|
# Mark this domain as not sending mail with hard-fail SPF and DMARC records.
|
|
|
|
|
d = (qname+"." if qname else "") + domain
|
|
|
|
|
if not has_rec(qname, "TXT", prefix="v=spf1 "):
|
|
|
|
|
records.append((qname, "TXT", 'v=spf1 -all', "Recommended. Prevents use of this domain name for outbound mail by specifying that no servers are valid sources for mail from @%s. If you do send email from this domain name you should either override this record such that the SPF rule does allow the originating server, or, take the recommended approach and have the box handle mail for this domain (simply add any receiving alias at this domain name to make this machine treat the domain name as one of its mail domains)." % d))
|
|
|
|
|
if not has_rec("_dmarc" + ("."+qname if qname else ""), "TXT", prefix="v=DMARC1; "):
|
|
|
|
|
records.append(("_dmarc" + ("."+qname if qname else ""), "TXT", 'v=DMARC1; p=reject', "Recommended. Prevents use of this domain name for outbound mail by specifying that the SPF rule should be honoured for mail from @%s." % d))
|
|
|
|
|
|
|
|
|
|
# And with a null MX record (https://explained-from-first-principles.com/email/#null-mx-record)
|
|
|
|
|
if not has_rec(qname, "MX"):
|
|
|
|
|
records.append((qname, "MX", '0 .', "Recommended. Prevents use of this domain name for incoming mail."))
|
|
|
|
|
|
|
|
|
|
# Sort the records. The None records *must* go first in the nsd zone file. Otherwise it doesn't matter.
|
|
|
|
|
records.sort(key = lambda rec : list(reversed(rec[0].split(".")) if rec[0] is not None else ""))
|
|
|
|
|
|
|
|
|
|
return records
|
|
|
|
|
|
|
|
|
|
def is_domain_cert_signed_and_valid(domain, env):
|
|
|
|
|
cert = get_ssl_certificates(env).get(domain)
|
|
|
|
|
if not cert: return False # no certificate provisioned
|
|
|
|
|
cert_status = check_certificate(domain, cert['certificate'], cert['private-key'])
|
|
|
|
|
return cert_status[0] == 'OK'
|
|
|
|
|
|
|
|
|
|
########################################################################
|
|
|
|
|
|
|
|
|
|
def build_tlsa_record(env):
|
|
|
|
|
@@ -441,6 +456,7 @@ def build_sshfp_records():
|
|
|
|
|
# to the zone file (that trigger bumping the serial number). However,
|
|
|
|
|
# if SSH has been configured to listen on a nonstandard port, we must
|
|
|
|
|
# specify that port to sshkeyscan.
|
|
|
|
|
|
|
|
|
|
port = 22
|
|
|
|
|
with open('/etc/ssh/sshd_config', 'r') as f:
|
|
|
|
|
for line in f:
|
|
|
|
|
@@ -451,8 +467,11 @@ def build_sshfp_records():
|
|
|
|
|
except ValueError:
|
|
|
|
|
pass
|
|
|
|
|
break
|
|
|
|
|
|
|
|
|
|
keys = shell("check_output", ["ssh-keyscan", "-t", "rsa,dsa,ecdsa,ed25519", "-p", str(port), "localhost"])
|
|
|
|
|
for key in sorted(keys.split("\n")):
|
|
|
|
|
keys = sorted(keys.split("\n"))
|
|
|
|
|
|
|
|
|
|
for key in keys:
|
|
|
|
|
if key.strip() == "" or key[0] == "#": continue
|
|
|
|
|
try:
|
|
|
|
|
host, keytype, pubkey = key.split(" ")
|
|
|
|
|
@@ -472,10 +491,10 @@ def write_nsd_zone(domain, zonefile, records, env, force):
|
|
|
|
|
# On the $ORIGIN line, there's typically a ';' comment at the end explaining
|
|
|
|
|
# what the $ORIGIN line does. Any further data after the domain confuses
|
|
|
|
|
# ldns-signzone, however. It used to say '; default zone domain'.
|
|
|
|
|
|
|
|
|
|
#
|
|
|
|
|
# The SOA contact address for all of the domains on this system is hostmaster
|
|
|
|
|
# @ the PRIMARY_HOSTNAME. Hopefully that's legit.
|
|
|
|
|
|
|
|
|
|
#
|
|
|
|
|
# For the refresh through TTL fields, a good reference is:
|
|
|
|
|
# http://www.peerwisdom.org/2013/05/15/dns-understanding-the-soa-record/
|
|
|
|
|
|
|
|
|
|
@@ -493,6 +512,9 @@ def write_nsd_zone(domain, zonefile, records, env, force):
|
|
|
|
|
# - Name the secondary DNS server as primary DNS in the SOA record
|
|
|
|
|
# - Do not add NS records for the Mail-in-a-Box server
|
|
|
|
|
|
|
|
|
|
# A hash of the available DNSSEC keys are added in a comment so that when
|
|
|
|
|
# the keys change we force a re-generation of the zone which triggers
|
|
|
|
|
# re-signing it.
|
|
|
|
|
|
|
|
|
|
zone = """
|
|
|
|
|
$ORIGIN {domain}.
|
|
|
|
|
@@ -563,6 +585,9 @@ $TTL {defttl} ; default time to live
|
|
|
|
|
value = v2
|
|
|
|
|
zone += value + "\n"
|
|
|
|
|
|
|
|
|
|
# Append a stable hash of DNSSEC signing keys in a comment.
|
|
|
|
|
zone += "\n; DNSSEC signing keys hash: {}\n".format(hash_dnssec_keys(domain, env))
|
|
|
|
|
|
|
|
|
|
# DNSSEC requires re-signing a zone periodically. That requires
|
|
|
|
|
# bumping the serial number even if no other records have changed.
|
|
|
|
|
# We don't see the DNSSEC records yet, so we have to figure out
|
|
|
|
|
@@ -673,53 +698,77 @@ zone:
|
|
|
|
|
|
|
|
|
|
########################################################################
|
|
|
|
|
|
|
|
|
|
def dnssec_choose_algo(domain, env):
|
|
|
|
|
if '.' in domain and domain.rsplit('.')[-1] in \
|
|
|
|
|
("email", "guide", "fund", "be", "lv"):
|
|
|
|
|
# At GoDaddy, RSASHA256 is the only algorithm supported
|
|
|
|
|
# for .email and .guide.
|
|
|
|
|
# A variety of algorithms are supported for .fund. This
|
|
|
|
|
# is preferred.
|
|
|
|
|
# Gandi tells me that .be does not support RSASHA1-NSEC3-SHA1
|
|
|
|
|
# Nic.lv does not support RSASHA1-NSEC3-SHA1 for .lv tld's
|
|
|
|
|
return "RSASHA256"
|
|
|
|
|
def find_dnssec_signing_keys(domain, env):
|
|
|
|
|
# For key that we generated (one per algorithm)...
|
|
|
|
|
d = os.path.join(env['STORAGE_ROOT'], 'dns/dnssec')
|
|
|
|
|
keyconfs = [f for f in os.listdir(d) if f.endswith(".conf")]
|
|
|
|
|
for keyconf in keyconfs:
|
|
|
|
|
# Load the file holding the KSK and ZSK key filenames.
|
|
|
|
|
keyconf_fn = os.path.join(d, keyconf)
|
|
|
|
|
keyinfo = load_env_vars_from_file(keyconf_fn)
|
|
|
|
|
|
|
|
|
|
# For any domain we were able to sign before, don't change the algorithm
|
|
|
|
|
# on existing users. We'll probably want to migrate to SHA256 later.
|
|
|
|
|
return "RSASHA1-NSEC3-SHA1"
|
|
|
|
|
# Skip this key if the conf file has a setting named DOMAINS,
|
|
|
|
|
# holding a comma-separated list of domain names, and if this
|
|
|
|
|
# domain is not in the list. This allows easily disabling a
|
|
|
|
|
# key by setting "DOMAINS=" or "DOMAINS=none", other than
|
|
|
|
|
# deleting the key's .conf file, which might result in the key
|
|
|
|
|
# being regenerated next upgrade. Keys should be disabled if
|
|
|
|
|
# they are not needed to reduce the DNSSEC query response size.
|
|
|
|
|
if "DOMAINS" in keyinfo and domain not in [dd.strip() for dd in keyinfo["DOMAINS"].split(",")]:
|
|
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
for keytype in ("KSK", "ZSK"):
|
|
|
|
|
yield keytype, keyinfo[keytype]
|
|
|
|
|
|
|
|
|
|
def hash_dnssec_keys(domain, env):
|
|
|
|
|
# Create a stable (by sorting the items) hash of all of the private keys
|
|
|
|
|
# that will be used to sign this domain.
|
|
|
|
|
keydata = []
|
|
|
|
|
for keytype, keyfn in sorted(find_dnssec_signing_keys(domain, env)):
|
|
|
|
|
oldkeyfn = os.path.join(env['STORAGE_ROOT'], 'dns/dnssec', keyfn + ".private")
|
|
|
|
|
keydata.append(keytype)
|
|
|
|
|
keydata.append(keyfn)
|
|
|
|
|
with open(oldkeyfn, "r") as fr:
|
|
|
|
|
keydata.append( fr.read() )
|
|
|
|
|
keydata = "".join(keydata).encode("utf8")
|
|
|
|
|
return hashlib.sha1(keydata).hexdigest()
|
|
|
|
|
|
|
|
|
|
def sign_zone(domain, zonefile, env):
|
|
|
|
|
algo = dnssec_choose_algo(domain, env)
|
|
|
|
|
dnssec_keys = load_env_vars_from_file(os.path.join(env['STORAGE_ROOT'], 'dns/dnssec/%s.conf' % algo))
|
|
|
|
|
# Sign the zone with all of the keys that were generated during
|
|
|
|
|
# setup so that the user can choose which to use in their DS record at
|
|
|
|
|
# their registrar, and also to support migration to newer algorithms.
|
|
|
|
|
|
|
|
|
|
# In order to use the same keys for all domains, we have to generate
|
|
|
|
|
# a new .key file with a DNSSEC record for the specific domain. We
|
|
|
|
|
# can reuse the same key, but it won't validate without a DNSSEC
|
|
|
|
|
# record specifically for the domain.
|
|
|
|
|
# In order to use the key files generated at setup which are for
|
|
|
|
|
# the domain _domain_, we have to re-write the files and place
|
|
|
|
|
# the actual domain name in it, so that ldns-signzone works.
|
|
|
|
|
#
|
|
|
|
|
# Copy the .key and .private files to /tmp to patch them up.
|
|
|
|
|
#
|
|
|
|
|
# Use os.umask and open().write() to securely create a copy that only
|
|
|
|
|
# we (root) can read.
|
|
|
|
|
files_to_kill = []
|
|
|
|
|
for key in ("KSK", "ZSK"):
|
|
|
|
|
if dnssec_keys.get(key, "").strip() == "": raise Exception("DNSSEC is not properly set up.")
|
|
|
|
|
oldkeyfn = os.path.join(env['STORAGE_ROOT'], 'dns/dnssec/' + dnssec_keys[key])
|
|
|
|
|
newkeyfn = '/tmp/' + dnssec_keys[key].replace("_domain_", domain)
|
|
|
|
|
dnssec_keys[key] = newkeyfn
|
|
|
|
|
# Patch each key, storing the patched version in /tmp for now.
|
|
|
|
|
# Each key has a .key and .private file. Collect a list of filenames
|
|
|
|
|
# for all of the keys (and separately just the key-signing keys).
|
|
|
|
|
all_keys = []
|
|
|
|
|
ksk_keys = []
|
|
|
|
|
for keytype, keyfn in find_dnssec_signing_keys(domain, env):
|
|
|
|
|
newkeyfn = '/tmp/' + keyfn.replace("_domain_", domain)
|
|
|
|
|
|
|
|
|
|
for ext in (".private", ".key"):
|
|
|
|
|
if not os.path.exists(oldkeyfn + ext): raise Exception("DNSSEC is not properly set up.")
|
|
|
|
|
with open(oldkeyfn + ext, "r") as fr:
|
|
|
|
|
# Copy the .key and .private files to /tmp to patch them up.
|
|
|
|
|
#
|
|
|
|
|
# Use os.umask and open().write() to securely create a copy that only
|
|
|
|
|
# we (root) can read.
|
|
|
|
|
oldkeyfn = os.path.join(env['STORAGE_ROOT'], 'dns/dnssec', keyfn + ext)
|
|
|
|
|
with open(oldkeyfn, "r") as fr:
|
|
|
|
|
keydata = fr.read()
|
|
|
|
|
keydata = keydata.replace("_domain_", domain) # trick ldns-signkey into letting our generic key be used by this zone
|
|
|
|
|
fn = newkeyfn + ext
|
|
|
|
|
keydata = keydata.replace("_domain_", domain)
|
|
|
|
|
prev_umask = os.umask(0o77) # ensure written file is not world-readable
|
|
|
|
|
try:
|
|
|
|
|
with open(fn, "w") as fw:
|
|
|
|
|
with open(newkeyfn + ext, "w") as fw:
|
|
|
|
|
fw.write(keydata)
|
|
|
|
|
finally:
|
|
|
|
|
os.umask(prev_umask) # other files we write should be world-readable
|
|
|
|
|
files_to_kill.append(fn)
|
|
|
|
|
|
|
|
|
|
# Put the patched key filename base (without extension) into the list of keys we'll sign with.
|
|
|
|
|
all_keys.append(newkeyfn)
|
|
|
|
|
if keytype == "KSK": ksk_keys.append(newkeyfn)
|
|
|
|
|
|
|
|
|
|
# Do the signing.
|
|
|
|
|
expiry_date = (datetime.datetime.now() + datetime.timedelta(days=30)).strftime("%Y%m%d")
|
|
|
|
|
@@ -732,32 +781,34 @@ def sign_zone(domain, zonefile, env):
|
|
|
|
|
|
|
|
|
|
# zonefile to sign
|
|
|
|
|
"/etc/nsd/zones/" + zonefile,
|
|
|
|
|
|
|
|
|
|
]
|
|
|
|
|
# keys to sign with (order doesn't matter -- it'll figure it out)
|
|
|
|
|
dnssec_keys["KSK"],
|
|
|
|
|
dnssec_keys["ZSK"],
|
|
|
|
|
])
|
|
|
|
|
+ all_keys
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
# Create a DS record based on the patched-up key files. The DS record is specific to the
|
|
|
|
|
# zone being signed, so we can't use the .ds files generated when we created the keys.
|
|
|
|
|
# The DS record points to the KSK only. Write this next to the zone file so we can
|
|
|
|
|
# get it later to give to the user with instructions on what to do with it.
|
|
|
|
|
#
|
|
|
|
|
# We want to be able to validate DS records too, but multiple forms may be valid depending
|
|
|
|
|
# on the digest type. So we'll write all (both) valid records. Only one DS record should
|
|
|
|
|
# actually be deployed. Preferebly the first.
|
|
|
|
|
# Generate a DS record for each key. There are also several possible hash algorithms that may
|
|
|
|
|
# be used, so we'll pre-generate all for each key. One DS record per line. Only one
|
|
|
|
|
# needs to actually be deployed at the registrar. We'll select the preferred one
|
|
|
|
|
# in the status checks.
|
|
|
|
|
with open("/etc/nsd/zones/" + zonefile + ".ds", "w") as f:
|
|
|
|
|
for digest_type in ('2', '1'):
|
|
|
|
|
rr_ds = shell('check_output', ["/usr/bin/ldns-key2ds",
|
|
|
|
|
"-n", # output to stdout
|
|
|
|
|
"-" + digest_type, # 1=SHA1, 2=SHA256
|
|
|
|
|
dnssec_keys["KSK"] + ".key"
|
|
|
|
|
])
|
|
|
|
|
f.write(rr_ds)
|
|
|
|
|
for key in ksk_keys:
|
|
|
|
|
for digest_type in ('1', '2', '4'):
|
|
|
|
|
rr_ds = shell('check_output', ["/usr/bin/ldns-key2ds",
|
|
|
|
|
"-n", # output to stdout
|
|
|
|
|
"-" + digest_type, # 1=SHA1, 2=SHA256, 4=SHA384
|
|
|
|
|
key + ".key"
|
|
|
|
|
])
|
|
|
|
|
f.write(rr_ds)
|
|
|
|
|
|
|
|
|
|
# Remove our temporary file.
|
|
|
|
|
for fn in files_to_kill:
|
|
|
|
|
os.unlink(fn)
|
|
|
|
|
# Remove the temporary patched key files.
|
|
|
|
|
for fn in all_keys:
|
|
|
|
|
os.unlink(fn + ".private")
|
|
|
|
|
os.unlink(fn + ".key")
|
|
|
|
|
|
|
|
|
|
########################################################################
|
|
|
|
|
|
|
|
|
|
|