diff --git a/CHANGELOG.md b/CHANGELOG.md index a75a9a43..67fcdd94 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,64 @@ CHANGELOG ========= +Version 55 (October 18, 2021) +----------------------------- + +Mail: + +* "SMTPUTF8" is now disabled in Postfix. Because Dovecot still does not support SMTPUTF8, incoming mail to internationalized addresses was bouncing. This fixes incoming mail to internationalized domains (which was probably working prior to v0.40), but it will prevent sending outbound mail to addresses with internationalized local-parts. +* Upgraded to Roundcube 1.5. + +Control panel: + +* The control panel menus are now hidden before login, but now non-admins can log in to access the mail and contacts/calendar instruction pages. +* The login form now disables browser autocomplete in the two-factor authentication code field. +* After logging in, the default page is now a fast-loading welcome page rather than the slow-loading system status checks page. +* The backup retention period option now displays for B2 backup targets. +* The DNSSEC DS record recommendations are cleaned up and now recommend changing records that use SHA1. +* The Munin monitoring pages no longer require a separate HTTP basic authentication login and can be used if two-factor authentication is turned on. +* Control panel logins are now tied to a session backend that allows true logouts (rather than an encrypted cookie). +* Failed logins no longer directly reveal whether the email address corresponds to a user account. +* Browser dark mode now inverts the color scheme. + +Other: + +* Fail2ban's IPv6 support is enabled. +* The mail log tool now doesn't crash if there are email addresess in log messages with invalid UTF-8 characters. +* Additional nsd.conf files can be placed in /etc/nsd.conf.d. + +v0.54 (June 20, 2021) +--------------------- + +Mail: + +* Forwarded mail using mail filter rules (in Roundcube; "sieve" rules) stopped re-writing the envelope address at some point, causing forwarded mail to often be marked as spam by the final recipient. These forwards will now re-write the envelope as the Mail-in-a-Box user receiving the mail to comply with SPF/DMARC rules. +* Sending mail is now possible on port 465 with the "SSL" or "TLS" option in mail clients, and this is now the recommended setting. Port 587 with STARTTLS remains available but should be avoided when configuring new mail clients. +* Roundcube's login cookie is updated to use a new encryption algorithm (AES-256-CBC instead of DES-EDE-CBC). + +DNS: + +* The ECDSAP256SHA256 DNSSEC algorithm is now available. If a DS record is set for any of your domain names that have DNS hosted on your box, you will be prompted by status checks to update the DS record at your convenience. +* Null MX records are added for domains that do not serve mail. + +Contacts/calendar: + +* Updated Nextcloud to 20.0.8, contacts to 3.5.1, calendar to 2.2.0 (#1960). + +Control panel: + +* Fixed a crash in the status checks. +* Small wording improvements. + +Setup: + +* Minor improvements to the setup scripts. + +v0.53a (May 8, 2021) +-------------------- + +The download URL for Z-Push has been revised becaue the old URL stopped working. + v0.53 (April 12, 2021) ---------------------- diff --git a/README.md b/README.md index 53d9fa03..317fb60e 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,10 @@ Issues Changes ------- +### v0.55-quota-0.22-beta + +* Update to v55 of Mail-in-a-Box + ### v0.53-quota-0.22-beta * Update to v0.53 of Mail-in-a-Box @@ -240,6 +244,8 @@ It also includes system management tools: * A control panel for adding/removing mail users, aliases, custom DNS records, configuring backups, etc. * An API for all of the actions on the control panel +Internationalized domain names are supported and configured easily (but SMTPUTF8 is not supported, unfortunately). + It also supports static website hosting since the box is serving HTTPS anyway. (To serve a website for your domains elsewhere, just add a custom DNS "A" record in you Mail-in-a-Box's control panel to point domains to another server.) For more information on how Mail-in-a-Box handles your privacy, see the [security details page](security.md). @@ -256,7 +262,7 @@ Clone this repository and checkout the tag corresponding to the most recent rele $ git clone https://github.com/mail-in-a-box/mailinabox $ cd mailinabox - $ git checkout v0.53 + $ git checkout v55 Begin the installation. diff --git a/api/mailinabox.yml b/api/mailinabox.yml index 14cf54de..bd4b203b 100644 --- a/api/mailinabox.yml +++ b/api/mailinabox.yml @@ -54,24 +54,24 @@ tags: System operations, which include system status checks, new version checks and reboot status. paths: - /me: - get: + /login: + post: tags: - User - summary: Get user information + summary: Exchange a username and password for a session API key. description: | - Returns user information. Used for user authentication. + Returns user information and a session API key. Authenticate a user by supplying the auth token as a base64 encoded string in format `email:password` using basic authentication headers. If successful, a long-lived `api_key` is returned which can be used for subsequent - requests to the API. - operationId: getMe + requests to the API in place of the password. + operationId: login x-codeSamples: - lang: curl source: | - curl -X GET "https://{host}/admin/me" \ + curl -X GET "https://{host}/admin/login" \ -u ":" responses: 200: @@ -92,6 +92,24 @@ paths: privileges: - admin status: ok + /logout: + post: + tags: + - User + summary: Invalidates a session API key. + description: | + Invalidates a session API key so that it cannot be used after this API call. + operationId: logout + x-codeSamples: + - lang: curl + source: | + curl -X GET "https://{host}/admin/logout" \ + -u ":" + responses: + 200: + description: Successful operation + content: + application/json: /system/status: post: tags: @@ -1803,7 +1821,7 @@ components: The `access-token` is comprised of the Base64 encoding of `username:password`. The `username` is the mail user's email address, and `password` can either be the mail user's - password, or the `api_key` returned from the `getMe` operation. + password, or the `api_key` returned from the `login` operation. When using `curl`, you can supply user credentials using the `-u` or `--user` parameter. requestBodies: diff --git a/conf/fail2ban/jails.conf b/conf/fail2ban/jails.conf index 5de4fd48..ce957f41 100644 --- a/conf/fail2ban/jails.conf +++ b/conf/fail2ban/jails.conf @@ -38,6 +38,14 @@ logpath = STORAGE_ROOT/owncloud/nextcloud.log maxretry = 20 findtime = 120 +[miab-postfix465] +enabled = true +port = 465 +filter = miab-postfix-submission +logpath = /var/log/mail.log +maxretry = 20 +findtime = 30 + [miab-postfix587] enabled = true port = 587 diff --git a/conf/ios-profile.xml b/conf/ios-profile.xml index f2011a4e..273c0bf6 100644 --- a/conf/ios-profile.xml +++ b/conf/ios-profile.xml @@ -53,7 +53,7 @@ OutgoingMailServerHostName PRIMARY_HOSTNAME OutgoingMailServerPortNumber - 587 + 465 OutgoingMailServerUseSSL OutgoingPasswordSameAsIncomingPassword diff --git a/conf/mozilla-autoconfig.xml b/conf/mozilla-autoconfig.xml index 22834622..df9cce61 100644 --- a/conf/mozilla-autoconfig.xml +++ b/conf/mozilla-autoconfig.xml @@ -16,8 +16,8 @@ PRIMARY_HOSTNAME - 587 - STARTTLS + 465 + SSL %EMAILADDRESS% password-cleartext true diff --git a/conf/zpush/backend_imap.php b/conf/zpush/backend_imap.php index a0c12335..da80c89a 100644 --- a/conf/zpush/backend_imap.php +++ b/conf/zpush/backend_imap.php @@ -49,7 +49,7 @@ define('IMAP_FROM_LDAP_FULLNAME', '#givenname #sn'); define('IMAP_SMTP_METHOD', 'sendmail'); global $imap_smtp_params; -$imap_smtp_params = array('host' => 'ssl://127.0.0.1', 'port' => 587, 'auth' => true, 'username' => 'imap_username', 'password' => 'imap_password'); +$imap_smtp_params = array('host' => 'ssl://127.0.0.1', 'port' => 465, 'auth' => true, 'username' => 'imap_username', 'password' => 'imap_password'); define('MAIL_MIMEPART_CRLF', "\r\n"); define('IMAP_MEETING_USE_CALDAV', true); diff --git a/management/auth.py b/management/auth.py index fd143c76..0a88c457 100644 --- a/management/auth.py +++ b/management/auth.py @@ -1,6 +1,7 @@ -import base64, os, os.path, hmac, json +import base64, os, os.path, hmac, json, secrets +from datetime import timedelta -from flask import make_response +from expiringdict import ExpiringDict import utils from mailconfig import get_mail_password, get_mail_user_privileges @@ -9,25 +10,18 @@ from mfa import get_hash_mfa_state, validate_auth_mfa DEFAULT_KEY_PATH = '/var/lib/mailinabox/api.key' DEFAULT_AUTH_REALM = 'Mail-in-a-Box Management Server' -class KeyAuthService: - """Generate an API key for authenticating clients - - Clients must read the key from the key file and send the key with all HTTP - requests. The key is passed as the username field in the standard HTTP - Basic Auth header. - """ +class AuthService: def __init__(self): self.auth_realm = DEFAULT_AUTH_REALM - self.key = self._generate_key() self.key_path = DEFAULT_KEY_PATH + self.max_session_duration = timedelta(days=2) - def write_key(self): - """Write key to file so authorized clients can get the key + self.init_system_api_key() + self.sessions = ExpiringDict(max_len=64, max_age_seconds=self.max_session_duration.total_seconds()) + + def init_system_api_key(self): + """Write an API key to a local file so local processes can use the API""" - The key file is created with mode 0640 so that additional users can be - authorized to access the API by granting group/ACL read permissions on - the key file. - """ def create_file_with_mode(path, mode): # Based on answer by A-B-B: http://stackoverflow.com/a/15015748 old_umask = os.umask(0) @@ -36,123 +30,137 @@ class KeyAuthService: finally: os.umask(old_umask) + self.key = secrets.token_hex(32) + os.makedirs(os.path.dirname(self.key_path), exist_ok=True) with create_file_with_mode(self.key_path, 0o640) as key_file: key_file.write(self.key + '\n') - def authenticate(self, request, env): - """Test if the client key passed in HTTP Authorization header matches the service key - or if the or username/password passed in the header matches an administrator user. + def authenticate(self, request, env, login_only=False, logout=False): + """Test if the HTTP Authorization header's username matches the system key, a session key, + or if the username/password passed in the header matches a local user. Returns a tuple of the user's email address and list of user privileges (e.g. ('my@email', []) or ('my@email', ['admin']); raises a ValueError on login failure. - If the user used an API key, the user's email is returned as None.""" + If the user used the system API key, the user's email is returned as None since + this key is not associated with a user.""" - def decode(s): - return base64.b64decode(s.encode('ascii')).decode('ascii') - - def parse_basic_auth(header): + def parse_http_authorization_basic(header): + def decode(s): + return base64.b64decode(s.encode('ascii')).decode('ascii') if " " not in header: return None, None scheme, credentials = header.split(maxsplit=1) if scheme != 'Basic': return None, None - credentials = decode(credentials) if ":" not in credentials: return None, None username, password = credentials.split(':', maxsplit=1) return username, password - header = request.headers.get('Authorization') - if not header: - raise ValueError("No authorization header provided.") - - username, password = parse_basic_auth(header) - + username, password = parse_http_authorization_basic(request.headers.get('Authorization', '')) if username in (None, ""): raise ValueError("Authorization header invalid.") - elif username == self.key: - # The user passed the master API key which grants administrative privs. + + if username.strip() == "" and password.strip() == "": + raise ValueError("No email address, password, session key, or API key provided.") + + # If user passed the system API key, grant administrative privs. This key + # is not associated with a user. + if username == self.key and not login_only: return (None, ["admin"]) + + # If the password corresponds with a session token for the user, grant access for that user. + if self.get_session(username, password, "login", env) and not login_only: + sessionid = password + session = self.sessions[sessionid] + if logout: + # Clear the session. + del self.sessions[sessionid] + else: + # Re-up the session so that it does not expire. + self.sessions[sessionid] = session + + # If no password was given, but a username was given, we're missing some information. + elif password.strip() == "": + raise ValueError("Enter a password.") + else: - # The user is trying to log in with a username and either a password - # (and possibly a MFA token) or a user-specific API key. - return (username, self.check_user_auth(username, password, request, env)) + # The user is trying to log in with a username and a password + # (and possibly a MFA token). On failure, an exception is raised. + self.check_user_auth(username, password, request, env) + + # Get privileges for authorization. This call should never fail because by this + # point we know the email address is a valid user --- unless the user has been + # deleted after the session was granted. On error the call will return a tuple + # of an error message and an HTTP status code. + privs = get_mail_user_privileges(username, env) + if isinstance(privs, tuple): raise ValueError(privs[0]) + + # Return the authorization information. + return (username, privs) def check_user_auth(self, email, pw, request, env): # Validate a user's login email address and password. If MFA is enabled, # check the MFA token in the X-Auth-Token header. # - # On success returns a list of privileges (e.g. [] or ['admin']). On login - # failure, raises a ValueError with a login error message. + # On login failure, raises a ValueError with a login error message. On + # success, nothing is returned. - # Sanity check. - if email == "" or pw == "": - raise ValueError("Enter an email address and password.") - - # The password might be a user-specific API key. create_user_key raises - # a ValueError if the user does not exist. - if hmac.compare_digest(self.create_user_key(email, env), pw): - # OK. - pass - else: + # Authenticate. + try: # Get the hashed password of the user. Raise a ValueError if the - # email address does not correspond to a user. + # email address does not correspond to a user. But wrap it in the + # same exception as if a password fails so we don't easily reveal + # if an email address is valid. pw_hash = get_mail_password(email, env) - # Authenticate. - try: - # Use 'doveadm pw' to check credentials. doveadm will return - # a non-zero exit status if the credentials are no good, - # and check_call will raise an exception in that case. - utils.shell('check_call', [ - "/usr/bin/doveadm", "pw", - "-p", pw, - "-t", pw_hash, - ]) - except: - # Login failed. - raise ValueError("Invalid password.") + # Use 'doveadm pw' to check credentials. doveadm will return + # a non-zero exit status if the credentials are no good, + # and check_call will raise an exception in that case. + utils.shell('check_call', [ + "/usr/bin/doveadm", "pw", + "-p", pw, + "-t", pw_hash, + ]) + except: + # Login failed. + raise ValueError("Incorrect email address or password.") - # If MFA is enabled, check that MFA passes. - status, hints = validate_auth_mfa(email, request, env) - if not status: - # Login valid. Hints may have more info. - raise ValueError(",".join(hints)) + # If MFA is enabled, check that MFA passes. + status, hints = validate_auth_mfa(email, request, env) + if not status: + # Login valid. Hints may have more info. + raise ValueError(",".join(hints)) - # Get privileges for authorization. This call should never fail because by this - # point we know the email address is a valid user. But on error the call will - # return a tuple of an error message and an HTTP status code. - privs = get_mail_user_privileges(email, env) - if isinstance(privs, tuple): raise ValueError(privs[0]) - - # Return a list of privileges. - return privs - - def create_user_key(self, email, env): - # Create a user API key, which is a shared secret that we can re-generate from - # static information in our database. The shared secret contains the user's - # email address, current hashed password, and current MFA state, so that the - # key becomes invalid if any of that information changes. - # - # Use an HMAC to generate the API key using our master API key as a key, - # which also means that the API key becomes invalid when our master API key - # changes --- i.e. when this process is restarted. - # - # Raises ValueError via get_mail_password if the user doesn't exist. - - # Construct the HMAC message from the user's email address and current password. - msg = b"AUTH:" + email.encode("utf8") + b" " + get_mail_password(email, env).encode("utf8") + def create_user_password_state_token(self, email, env): + # Create a token that changes if the user's password or MFA options change + # so that sessions become invalid if any of that information changes. + msg = get_mail_password(email, env).encode("utf8") # Add to the message the current MFA state, which is a list of MFA information. # Turn it into a string stably. msg += b" " + json.dumps(get_hash_mfa_state(email, env), sort_keys=True).encode("utf8") - # Make the HMAC. + # Make a HMAC using the system API key as a hash key. hash_key = self.key.encode('ascii') return hmac.new(hash_key, msg, digestmod="sha256").hexdigest() - def _generate_key(self): - raw_key = os.urandom(32) - return base64.b64encode(raw_key).decode('ascii') + def create_session_key(self, username, env, type=None): + # Create a new session. + token = secrets.token_hex(32) + self.sessions[token] = { + "email": username, + "password_token": self.create_user_password_state_token(username, env), + "type": type, + } + return token + + def get_session(self, user_email, session_key, session_type, env): + if session_key not in self.sessions: return None + session = self.sessions[session_key] + if session_type == "login" and session["email"] != user_email: return None + if session["type"] != session_type: return None + if session["password_token"] != self.create_user_password_state_token(session["email"], env): return None + return session diff --git a/management/daemon.py b/management/daemon.py index b4dbd214..88c04ffe 100755 --- a/management/daemon.py +++ b/management/daemon.py @@ -1,5 +1,8 @@ #!/usr/local/lib/mailinabox/env/bin/python3 # +# The API can be accessed on the command line, e.g. use `curl` like so: +# curl --user $(') @authorized_personnel_only -def munin(filename=""): - # Checks administrative access (@authorized_personnel_only) and then just proxies - # the request to static files. +def munin_start(): + # Munin pages, static images, and dynamically generated images are served + # outside of the AJAX API. We'll start with a 'start' API that sets a cookie + # that subsequent requests will read for authorization. (We don't use cookies + # for the API to avoid CSRF vulnerabilities.) + response = make_response("OK") + response.set_cookie("session", auth_service.create_session_key(request.user_email, env, type='cookie'), + max_age=60*30, secure=True, httponly=True, samesite="Strict") # 30 minute duration + return response + +def check_request_cookie_for_admin_access(): + session = auth_service.get_session(None, request.cookies.get("session", ""), "cookie", env) + if not session: return False + privs = get_mail_user_privileges(session["email"], env) + if not isinstance(privs, list): return False + if "admin" not in privs: return False + return True + +def authorized_personnel_only_via_cookie(f): + @wraps(f) + def g(*args, **kwargs): + if not check_request_cookie_for_admin_access(): + return Response("Unauthorized", status=403, mimetype='text/plain', headers={}) + return f(*args, **kwargs) + return g + +@app.route('/munin/') +@authorized_personnel_only_via_cookie +def munin_static_file(filename=""): + # Proxy the request to static files. if filename == "": filename = "index.html" return send_from_directory("/var/cache/munin/www", filename) @app.route('/munin/cgi-graph/') -@authorized_personnel_only +@authorized_personnel_only_via_cookie def munin_cgi(filename): """ Relay munin cgi dynazoom requests /usr/lib/munin/cgi/munin-cgi-graph is a perl cgi script in the munin package @@ -771,30 +813,10 @@ if __name__ == '__main__': # Turn on Flask debugging. app.debug = True - # Use a stable-ish master API key so that login sessions don't restart on each run. - # Use /etc/machine-id to seed the key with a stable secret, but add something - # and hash it to prevent possibly exposing the machine id, using the time so that - # the key is not valid indefinitely. - import hashlib - with open("/etc/machine-id") as f: - api_key = f.read() - api_key += "|" + str(int(time.time() / (60*60*2))) - hasher = hashlib.sha1() - hasher.update(api_key.encode("ascii")) - auth_service.key = hasher.hexdigest() - - if "APIKEY" in os.environ: auth_service.key = os.environ["APIKEY"] - if not app.debug: app.logger.addHandler(utils.create_syslog_handler()) - # For testing on the command line, you can use `curl` like so: - # curl --user $( 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. @@ -145,10 +178,10 @@ def build_zone(domain, all_domains, additional_records, www_redirect_domains, en # 'False' in the tuple indicates these records would not be used if the zone # is managed outside of the box. if is_zone: - # Obligatory definition of ns1.PRIMARY_HOSTNAME. + # Obligatory NS record to ns1.PRIMARY_HOSTNAME. records.append((None, "NS", "ns1.%s." % env["PRIMARY_HOSTNAME"], False)) - # Define ns2.PRIMARY_HOSTNAME or whatever the user overrides. + # NS record to ns2.PRIMARY_HOSTNAME or whatever the user overrides. # User may provide one or more additional nameservers secondary_ns_list = get_secondary_dns(additional_records, mode="NS") \ or ["ns2." + env["PRIMARY_HOSTNAME"]] @@ -158,15 +191,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.")) @@ -184,16 +208,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): @@ -220,21 +245,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 @@ -248,63 +275,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) @@ -321,25 +325,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 @@ -356,15 +347,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): @@ -429,6 +444,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: @@ -439,8 +455,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(" ") @@ -460,13 +479,16 @@ 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/ - + # + # 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}. @@ -502,6 +524,9 @@ $TTL 86400 ; 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 @@ -579,7 +604,7 @@ def get_dns_zonefile(zone, env): def write_nsd_conf(zonefiles, additional_records, env): # Write the list of zones to a configuration file. - nsd_conf_file = "/etc/nsd/zones.conf" + nsd_conf_file = "/etc/nsd/nsd.conf.d/zones.conf" nsdconf = "" # Append the zones. @@ -612,53 +637,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") @@ -671,32 +720,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") ######################################################################## diff --git a/management/mail_log.py b/management/mail_log.py index 1626f820..59c32c6e 100755 --- a/management/mail_log.py +++ b/management/mail_log.py @@ -586,7 +586,7 @@ def scan_postfix_submission_line(date, log, collector): def readline(filename): """ A generator that returns the lines of a file """ - with open(filename) as file: + with open(filename, errors='replace') as file: while True: line = file.readline() if not line: diff --git a/management/mailconfig.py b/management/mailconfig.py index aa992f33..8ba15adf 100755 --- a/management/mailconfig.py +++ b/management/mailconfig.py @@ -16,8 +16,8 @@ import idna def validate_email(email, mode=None): # Checks that an email address is syntactically valid. Returns True/False. - # Until Postfix supports SMTPUTF8, an email address may contain ASCII - # characters only; IDNs must be IDNA-encoded. + # An email address may contain ASCII characters only because Dovecot's + # authentication mechanism gets confused with other character encodings. # # When mode=="user", we're checking that this can be a user account name. # Dovecot has tighter restrictions - letters, numbers, underscore, and @@ -235,9 +235,9 @@ def get_admins(env): return users def get_mail_aliases(env): - # Returns a sorted list of tuples of (address, forward-tos, permitted-senders). + # Returns a sorted list of tuples of (address, forward-tos, permitted-senders, auto). c = open_database(env) - c.execute('SELECT source, destination, permitted_senders FROM aliases') + c.execute('SELECT source, destination, permitted_senders, 0 as auto FROM aliases UNION SELECT source, destination, permitted_senders, 1 as auto FROM auto_aliases') aliases = { row[0]: row for row in c.fetchall() } # make dict # put in a canonical order: sort by domain, then by email address lexicographically @@ -257,7 +257,7 @@ def get_mail_aliases_ex(env): # address_display: "name@domain.tld", # full Unicode # forwards_to: ["user1@domain.com", "receiver-only1@domain.com", ...], # permitted_senders: ["user1@domain.com", "sender-only1@domain.com", ...] OR null, - # required: True|False + # auto: True|False # }, # ... # ] @@ -265,12 +265,13 @@ def get_mail_aliases_ex(env): # ... # ] - required_aliases = get_required_aliases(env) domains = {} - for address, forwards_to, permitted_senders in get_mail_aliases(env): + for address, forwards_to, permitted_senders, auto in get_mail_aliases(env): + # skip auto domain maps since these are not informative in the control panel's aliases list + if auto and address.startswith("@"): continue + # get alias info domain = get_domain(address) - required = (address in required_aliases) # add to list if not domain in domains: @@ -283,7 +284,7 @@ def get_mail_aliases_ex(env): "address_display": prettify_idn_email_address(address), "forwards_to": [prettify_idn_email_address(r.strip()) for r in forwards_to.split(",")], "permitted_senders": [prettify_idn_email_address(s.strip()) for s in permitted_senders.split(",")] if permitted_senders is not None else None, - "required": required, + "auto": bool(auto), }) # Sort domains. @@ -291,7 +292,7 @@ def get_mail_aliases_ex(env): # Sort aliases within each domain first by required-ness then lexicographically by address. for domain in domains: - domain["aliases"].sort(key = lambda alias : (alias["required"], alias["address"])) + domain["aliases"].sort(key = lambda alias : (alias["auto"], alias["address"])) return domains def get_domain(emailaddr, as_unicode=True): @@ -310,11 +311,12 @@ def get_domain(emailaddr, as_unicode=True): def get_mail_domains(env, filter_aliases=lambda alias : True, users_only=False): # Returns the domain names (IDNA-encoded) of all of the email addresses # configured on the system. If users_only is True, only return domains - # with email addresses that correspond to user accounts. + # with email addresses that correspond to user accounts. Exclude Unicode + # forms of domain names listed in the automatic aliases table. domains = [] domains.extend([get_domain(login, as_unicode=False) for login in get_mail_users(env)]) if not users_only: - domains.extend([get_domain(address, as_unicode=False) for address, *_ in get_mail_aliases(env) if filter_aliases(address) ]) + domains.extend([get_domain(address, as_unicode=False) for address, _, _, auto in get_mail_aliases(env) if filter_aliases(address) and not auto ]) return set(domains) def add_mail_user(email, pw, privs, quota, env): @@ -624,6 +626,13 @@ def remove_mail_alias(address, env, do_kick=True): # Update things in case any domains are removed. return kick(env, "alias removed") +def add_auto_aliases(aliases, env): + conn, c = open_database(env, with_connection=True) + c.execute("DELETE FROM auto_aliases"); + for source, destination in aliases.items(): + c.execute("INSERT INTO auto_aliases (source, destination) VALUES (?, ?)", (source, destination)) + conn.commit() + def get_system_administrator(env): return "administrator@" + env['PRIMARY_HOSTNAME'] @@ -667,39 +676,34 @@ def kick(env, mail_result=None): if mail_result is not None: results.append(mail_result + "\n") - # Ensure every required alias exists. + auto_aliases = { } - existing_users = get_mail_users(env) - existing_alias_records = get_mail_aliases(env) - existing_aliases = set(a for a, *_ in existing_alias_records) # just first entry in tuple + # Mape required aliases to the administrator alias (which should be created manually). + administrator = get_system_administrator(env) required_aliases = get_required_aliases(env) + for alias in required_aliases: + if alias == administrator: continue # don't make an alias from the administrator to itself --- this alias must be created manually + auto_aliases[alias] = administrator - def ensure_admin_alias_exists(address): - # If a user account exists with that address, we're good. - if address in existing_users: - return + # Add domain maps from Unicode forms of IDNA domains to the ASCII forms stored in the alias table. + for domain in get_mail_domains(env): + try: + domain_unicode = idna.decode(domain.encode("ascii")) + if domain == domain_unicode: continue # not an IDNA/Unicode domain + auto_aliases["@" + domain_unicode] = "@" + domain + except (ValueError, UnicodeError, idna.IDNAError): + continue - # If the alias already exists, we're good. - if address in existing_aliases: - return + add_auto_aliases(auto_aliases, env) - # Doesn't exist. - administrator = get_system_administrator(env) - if address == administrator: return # don't make an alias from the administrator to itself --- this alias must be created manually - add_mail_alias(address, administrator, "", env, do_kick=False) - if administrator not in existing_aliases: return # don't report the alias in output if the administrator alias isn't in yet -- this is a hack to supress confusing output on initial setup - results.append("added alias %s (=> %s)\n" % (address, administrator)) - - for address in required_aliases: - ensure_admin_alias_exists(address) - - # Remove auto-generated postmaster/admin on domains we no - # longer have any other email addresses for. - for address, forwards_to, *_ in existing_alias_records: + # Remove auto-generated postmaster/admin/abuse alises from the main aliases table. + # They are now stored in the auto_aliases table. + for address, forwards_to, permitted_senders, auto in get_mail_aliases(env): user, domain = address.split("@") if user in ("postmaster", "admin", "abuse") \ and address not in required_aliases \ - and forwards_to == get_system_administrator(env): + and forwards_to == get_system_administrator(env) \ + and not auto: remove_mail_alias(address, env, do_kick=False) results.append("removed alias %s (was to %s; domain no longer used for email)\n" % (address, forwards_to)) diff --git a/management/status_checks.py b/management/status_checks.py index 490c5615..c67850f4 100755 --- a/management/status_checks.py +++ b/management/status_checks.py @@ -34,6 +34,7 @@ def get_services(): { "name": "SSH Login (ssh)", "port": get_ssh_port(), "public": True, }, { "name": "Public DNS (nsd4)", "port": 53, "public": True, }, { "name": "Incoming Mail (SMTP/postfix)", "port": 25, "public": True, }, + { "name": "Outgoing Mail (SMTP 465/postfix)", "port": 465, "public": True, }, { "name": "Outgoing Mail (SMTP 587/postfix)", "port": 587, "public": True, }, #{ "name": "Postfix/master", "port": 10587, "public": True, }, { "name": "IMAPS (dovecot)", "port": 993, "public": True, }, @@ -42,7 +43,7 @@ def get_services(): { "name": "HTTPS Web (nginx)", "port": 443, "public": True, }, ] -def run_checks(rounded_values, env, output, pool): +def run_checks(rounded_values, env, output, pool, domains_to_check=None): # run systems checks output.add_heading("System") @@ -63,7 +64,7 @@ def run_checks(rounded_values, env, output, pool): # perform other checks asynchronously run_network_checks(env, output) - run_domain_checks(rounded_values, env, output, pool) + run_domain_checks(rounded_values, env, output, pool, domains_to_check=domains_to_check) def get_ssh_port(): # Returns ssh port @@ -300,7 +301,7 @@ def run_network_checks(env, output): which may prevent recipients from receiving your email. See http://www.spamhaus.org/query/ip/%s.""" % (env['PUBLIC_IP'], zen, env['PUBLIC_IP'])) -def run_domain_checks(rounded_time, env, output, pool): +def run_domain_checks(rounded_time, env, output, pool, domains_to_check=None): # Get the list of domains we handle mail for. mail_domains = get_mail_domains(env) @@ -311,7 +312,8 @@ def run_domain_checks(rounded_time, env, output, pool): # Get the list of domains we serve HTTPS for. web_domains = set(get_web_domains(env)) - domains_to_check = mail_domains | dns_domains | web_domains + if domains_to_check is None: + domains_to_check = mail_domains | dns_domains | web_domains # Remove "www", "autoconfig", "autodiscover", and "mta-sts" subdomains, which we group with their parent, # if their parent is in the domains to check list. @@ -557,61 +559,107 @@ def check_dns_zone_suggestions(domain, env, output, dns_zonefiles, domains_with_ def check_dnssec(domain, env, output, dns_zonefiles, is_checking_primary=False): - # See if the domain has a DS record set at the registrar. The DS record may have - # several forms. We have to be prepared to check for any valid record. We've - # pre-generated all of the valid digests --- read them in. + # See if the domain has a DS record set at the registrar. The DS record must + # match one of the keys that we've used to sign the zone. It may use one of + # several hashing algorithms. We've pre-generated all possible valid DS + # records, although some will be preferred. + + alg_name_map = { '7': 'RSASHA1-NSEC3-SHA1', '8': 'RSASHA256', '13': 'ECDSAP256SHA256' } + digalg_name_map = { '1': 'SHA-1', '2': 'SHA-256', '4': 'SHA-384' } + + # Read in the pre-generated DS records + expected_ds_records = { } ds_file = '/etc/nsd/zones/' + dns_zonefiles[domain] + '.ds' if not os.path.exists(ds_file): return # Domain is in our database but DNS has not yet been updated. - ds_correct = open(ds_file).read().strip().split("\n") - digests = { } - for rr_ds in ds_correct: - ds_keytag, ds_alg, ds_digalg, ds_digest = rr_ds.split("\t")[4].split(" ") - digests[ds_digalg] = ds_digest + with open(ds_file) as f: + for rr_ds in f: + rr_ds = rr_ds.rstrip() + ds_keytag, ds_alg, ds_digalg, ds_digest = rr_ds.split("\t")[4].split(" ") - # Some registrars may want the public key so they can compute the digest. The DS - # record that we suggest using is for the KSK (and that's how the DS records were generated). - alg_name_map = { '7': 'RSASHA1-NSEC3-SHA1', '8': 'RSASHA256' } - dnssec_keys = load_env_vars_from_file(os.path.join(env['STORAGE_ROOT'], 'dns/dnssec/%s.conf' % alg_name_map[ds_alg])) - dnsssec_pubkey = open(os.path.join(env['STORAGE_ROOT'], 'dns/dnssec/' + dnssec_keys['KSK'] + '.key')).read().split("\t")[3].split(" ")[3] + # Some registrars may want the public key so they can compute the digest. The DS + # record that we suggest using is for the KSK (and that's how the DS records were generated). + # We'll also give the nice name for the key algorithm. + dnssec_keys = load_env_vars_from_file(os.path.join(env['STORAGE_ROOT'], 'dns/dnssec/%s.conf' % alg_name_map[ds_alg])) + dnsssec_pubkey = open(os.path.join(env['STORAGE_ROOT'], 'dns/dnssec/' + dnssec_keys['KSK'] + '.key')).read().split("\t")[3].split(" ")[3] + + expected_ds_records[ (ds_keytag, ds_alg, ds_digalg, ds_digest) ] = { + "record": rr_ds, + "keytag": ds_keytag, + "alg": ds_alg, + "alg_name": alg_name_map[ds_alg], + "digalg": ds_digalg, + "digalg_name": digalg_name_map[ds_digalg], + "digest": ds_digest, + "pubkey": dnsssec_pubkey, + } # Query public DNS for the DS record at the registrar. - ds = query_dns(domain, "DS", nxdomain=None) - ds_looks_valid = ds and len(ds.split(" ")) == 4 - if ds_looks_valid: ds = ds.split(" ") - if ds_looks_valid and ds[0] == ds_keytag and ds[1] == ds_alg and ds[3] == digests.get(ds[2]): - if is_checking_primary: return - output.print_ok("DNSSEC 'DS' record is set correctly at registrar.") + ds = query_dns(domain, "DS", nxdomain=None, as_list=True) + if ds is None or isinstance(ds, str): ds = [] + + # There may be more that one record, so we get the result as a list. + # Filter out records that don't look valid, just in case, and split + # each record on spaces. + ds = [tuple(str(rr).split(" ")) for rr in ds if len(str(rr).split(" ")) == 4] + + if len(ds) == 0: + output.print_warning("""This domain's DNSSEC DS record is not set. The DS record is optional. The DS record activates DNSSEC. See below for instructions.""") else: - if ds == None: - if is_checking_primary: return - output.print_warning("""This domain's DNSSEC DS record is not set. The DS record is optional. The DS record activates DNSSEC. - To set a DS record, you must follow the instructions provided by your domain name registrar and provide to them this information:""") + matched_ds = set(ds) & set(expected_ds_records) + if matched_ds: + # At least one DS record matches one that corresponds with one of the ways we signed + # the zone, so it is valid. + # + # But it may not be preferred. Only algorithm 13 is preferred. Warn if any of the + # matched zones uses a different algorithm. + if set(r[1] for r in matched_ds) == { '13' } and set(r[2] for r in matched_ds) <= { '2', '4' }: # all are alg 13 and digest type 2 or 4 + output.print_ok("DNSSEC 'DS' record is set correctly at registrar.") + return + elif len([r for r in matched_ds if r[1] == '13' and r[2] in ( '2', '4' )]) > 0: # some but not all are alg 13 + output.print_ok("DNSSEC 'DS' record is set correctly at registrar. (Records using algorithm other than ECDSAP256SHA256 and digest types other than SHA-256/384 should be removed.)") + return + else: # no record uses alg 13 + output.print_warning("""DNSSEC 'DS' record set at registrar is valid but should be updated to ECDSAP256SHA256 and SHA-256 (see below). + IMPORTANT: Do not delete existing DNSSEC 'DS' records for this domain until confirmation that the new DNSSEC 'DS' record + for this domain is valid.""") else: if is_checking_primary: output.print_error("""The DNSSEC 'DS' record for %s is incorrect. See further details below.""" % domain) return output.print_error("""This domain's DNSSEC DS record is incorrect. The chain of trust is broken between the public DNS system and this machine's DNS server. It may take several hours for public DNS to update after a change. If you did not recently - make a change, you must resolve this immediately by following the instructions provided by your domain name registrar and - provide to them this information:""") + make a change, you must resolve this immediately (see below).""") + + output.print_line("""Follow the instructions provided by your domain name registrar to set a DS record. + Registrars support different sorts of DS records. Use the first option that works:""") + preferred_ds_order = [(7, 2), (8, 4), (13, 4), (8, 2), (13, 2)] # low to high, see https://github.com/mail-in-a-box/mailinabox/issues/1998 + + def preferred_ds_order_func(ds_suggestion): + k = (int(ds_suggestion['alg']), int(ds_suggestion['digalg'])) + if k in preferred_ds_order: + return preferred_ds_order.index(k) + return -1 # index before first item + output.print_line("") + for i, ds_suggestion in enumerate(sorted(expected_ds_records.values(), key=preferred_ds_order_func, reverse=True)): + if preferred_ds_order_func(ds_suggestion) == -1: continue # don't offer record types that the RFC says we must not offer output.print_line("") - output.print_line("Key Tag: " + ds_keytag + ("" if not ds_looks_valid or ds[0] == ds_keytag else " (Got '%s')" % ds[0])) - output.print_line("Key Flags: KSK") - output.print_line( - ("Algorithm: %s / %s" % (ds_alg, alg_name_map[ds_alg])) - + ("" if not ds_looks_valid or ds[1] == ds_alg else " (Got '%s')" % ds[1])) - # see http://www.iana.org/assignments/dns-sec-alg-numbers/dns-sec-alg-numbers.xhtml - output.print_line("Digest Type: 2 / SHA-256") - # http://www.ietf.org/assignments/ds-rr-types/ds-rr-types.xml - output.print_line("Digest: " + digests['2']) - if ds_looks_valid and ds[3] != digests.get(ds[2]): - output.print_line("(Got digest type %s and digest %s which do not match.)" % (ds[2], ds[3])) + output.print_line("Option " + str(i+1) + ":") + output.print_line("----------") + output.print_line("Key Tag: " + ds_suggestion['keytag']) + output.print_line("Key Flags: KSK (256)") + output.print_line("Algorithm: %s / %s" % (ds_suggestion['alg'], ds_suggestion['alg_name'])) + output.print_line("Digest Type: %s / %s" % (ds_suggestion['digalg'], ds_suggestion['digalg_name'])) + output.print_line("Digest: " + ds_suggestion['digest']) output.print_line("Public Key: ") - output.print_line(dnsssec_pubkey, monospace=True) + output.print_line(ds_suggestion['pubkey'], monospace=True) output.print_line("") output.print_line("Bulk/Record Format:") - output.print_line("" + ds_correct[0]) + output.print_line(ds_suggestion['record'], monospace=True) + if len(ds) > 0: output.print_line("") + output.print_line("The DS record is currently set to:") + for rr in ds: + output.print_line("Key Tag: {0}, Algorithm: {1}, Digest Type: {2}, Digest: {3}".format(*rr)) def check_mail_domain(domain, env, output): # Check the MX record. @@ -621,6 +669,8 @@ def check_mail_domain(domain, env, output): if mx is None: mxhost = None + elif mx == "[timeout]": + mxhost = None else: # query_dns returns a semicolon-delimited list # of priority-host pairs. @@ -713,7 +763,7 @@ def check_web_domain(domain, rounded_time, ssl_certificates, env, output): # website for also needs a signed certificate. check_ssl_cert(domain, rounded_time, ssl_certificates, env, output) -def query_dns(qname, rtype, nxdomain='[Not Set]', at=None): +def query_dns(qname, rtype, nxdomain='[Not Set]', at=None, as_list=False): # Make the qname absolute by appending a period. Without this, dns.resolver.query # will fall back a failed lookup to a second query with this machine's hostname # appended. This has been causing some false-positive Spamhaus reports. The @@ -750,6 +800,9 @@ def query_dns(qname, rtype, nxdomain='[Not Set]', at=None): if rtype in ("A", "AAAA"): response = [normalize_ip(str(r)) for r in response] + if as_list: + return response + # There may be multiple answers; concatenate the response. Remove trailing # periods from responses since that's how qnames are encoded in DNS but is # confusing for us. The order of the answers doesn't matter, so sort so we @@ -1050,3 +1103,7 @@ if __name__ == "__main__": elif sys.argv[1] == "--version": print(what_version_is_this(env)) + + elif sys.argv[1] == "--only": + with multiprocessing.pool.Pool(processes=10) as pool: + run_checks(False, env, ConsoleOutput(), pool, domains_to_check=sys.argv[2:]) diff --git a/management/templates/aliases.html b/management/templates/aliases.html index 3d37c4fd..c2a141f7 100644 --- a/management/templates/aliases.html +++ b/management/templates/aliases.html @@ -1,6 +1,6 @@

Aliases

@@ -163,7 +163,7 @@ function show_aliases() { var n = $("#alias-template").clone(); n.attr('id', ''); - if (alias.required) n.addClass('alias-required'); + if (alias.auto) n.addClass('alias-auto'); n.attr('data-address', alias.address_display); // this is decoded from IDNA, but will get re-coded to IDNA on the backend n.find('td.address').text(alias.address_display) for (var j = 0; j < alias.forwards_to.length; j++) diff --git a/management/templates/external-dns.html b/management/templates/external-dns.html index 0634ec82..4532c3f5 100644 --- a/management/templates/external-dns.html +++ b/management/templates/external-dns.html @@ -38,7 +38,7 @@ diff --git a/management/templates/index.html b/management/templates/index.html index 12f6ad8e..f9c87f2c 100644 --- a/management/templates/index.html +++ b/management/templates/index.html @@ -62,6 +62,37 @@ ol li { margin-bottom: 1em; } + + .if-logged-in { display: none; } + .if-logged-in-admin { display: none; } + + /* The below only gets used if it is supported */ + @media (prefers-color-scheme: dark) { + /* Invert invert lightness but not hue */ + html { + filter: invert(100%) hue-rotate(180deg); + } + + /* Set explicit background color (necessary for Firefox) */ + html { + background-color: #111; + } + + /* Override Boostrap theme here to give more contrast. The black turns to white by the filter. */ + .form-control { + color: black !important; + } + + /* Revert the invert for the navbar */ + button, div.navbar { + filter: invert(100%) hue-rotate(180deg); + } + + /* Revert the revert for the dropdowns */ + ul.dropdown-menu { + filter: invert(100%) hue-rotate(180deg); + } + } @@ -83,7 +114,7 @@
+
+ {% include "welcome.html" %} +
+
{% include "system-status.html" %}
@@ -166,6 +202,10 @@ {% include "ssl.html" %}
+
+ {% include "munin.html" %} +
+