diff --git a/CHANGELOG.md b/CHANGELOG.md index 80988981..aef6cf95 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,63 @@ CHANGELOG In Development -------------- -* Migrate to the ECDSAP256SHA256 DNSSEC algorithm. 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. +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 Release Candidate. + +Firewall: + +* Fail2ban's IPv6 support is enabled. + +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: + +* 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 2813ed73..473dc1a9 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,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). @@ -58,7 +60,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 v0.54 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 8490ee44..e8e679e4 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 @@ -724,30 +766,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,22 +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. - env["-primary-hostname-certificate-is-valid"] = is_domain_cert_signed_and_valid(env["PRIMARY_HOSTNAME"], env) + 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. @@ -149,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"]] @@ -162,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.")) @@ -188,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): @@ -224,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 @@ -252,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) @@ -325,12 +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_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) and env["-primary-hostname-certificate-is-valid"] and is_domain_cert_signed_and_valid("mta-sts." + domain, env): + # 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 @@ -347,10 +347,28 @@ 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 "")) @@ -360,7 +378,6 @@ 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']) - print(domain, cert_status) return cert_status[0] == 'OK' ######################################################################## @@ -587,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. 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 47faad5f..2fcb9703 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 @@ -186,9 +186,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 @@ -208,7 +208,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 # }, # ... # ] @@ -216,12 +216,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: @@ -234,7 +235,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. @@ -242,7 +243,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): @@ -261,11 +262,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, env): @@ -512,6 +514,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'] @@ -555,39 +564,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 607fd578..1e7223a5 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, }, @@ -611,14 +612,16 @@ def check_dnssec(domain, env, output, dns_zonefiles, is_checking_primary=False): # # 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' }: # all are alg 13 + 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 '13' in set(r[1] for r in matched_ds): # some but not all are alg 13 - output.print_ok("DNSSEC 'DS' record is set correctly at registrar. (Records using algorithm other than ECDSAP256SHA256 should be removed.)") + 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 (see below).") + 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) @@ -629,7 +632,8 @@ def check_dnssec(domain, env, output, dns_zonefiles, is_checking_primary=False): 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, 1), (7, 2), (8, 4), (13, 4), (8, 1), (8, 2), (13, 1), (13, 2)] # low to high + 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: @@ -637,11 +641,12 @@ def check_dnssec(domain, env, output, dns_zonefiles, is_checking_primary=False): 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("Option " + str(i+1) + ":") output.print_line("----------") output.print_line("Key Tag: " + ds_suggestion['keytag']) - output.print_line("Key Flags: KSK") + 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']) @@ -664,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. 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/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" %} +
+