Compare commits

..

6 commits

Author SHA1 Message Date
David Duque
6848e0056d
php-fpm: Guarantee that file namespaces differ 2021-11-17 22:05:31 +00:00
David Duque
ab31dc9011
Missed a semicolon 2021-11-17 21:12:30 +00:00
David Duque
ee2428742b
Clarify the names already used in .upstream.conf (2) 2021-11-17 20:12:27 +00:00
David Duque
84bfa84ff8
Clarify the names already used in .upstream.conf 2021-11-17 20:11:56 +00:00
David Duque
205b6784a1
Create two isolated php sockets. Leave the second one for user applications. 2021-11-17 20:08:30 +00:00
David Duque
24264ff852
Add .upstream.conf file if it doesn't exist 2021-11-17 19:44:06 +00:00
69 changed files with 5153 additions and 7551 deletions

View file

@ -4,23 +4,30 @@
root = true
[Vagrantfile]
[*]
indent_style = space
indent_size = 2
[*.rb]
indent_style = space
indent_size = 2
[**.html]
indent_style = tab
[**.py]
indent_style = tab
[**]
indent_style = tab
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.html]
indent_style = tab
[Makefile]
indent_style = tab
indent_size = 4
[Vagrantfile]
indent_size = 2
[*.rb]
indent_size = 2
[*.py]
indent_style = tab
[*.js]
indent_size = 2

5
.gitattributes vendored
View file

@ -1,5 +0,0 @@
# All text should use Unix-style Line-endings
* text eol=lf
# Except mta-sts.txt (RFC 8461)
mta-sts.txt text eol=crlf

1
.github/FUNDING.yml vendored
View file

@ -1 +0,0 @@
ko_fi: davness

View file

@ -1,3 +0,0 @@
[style]
based_on_style = pep8
use_tabs = True

View file

@ -1,86 +1,6 @@
CHANGELOG
=========
Version 60.1 (October 30, 2022)
-------------------------------
* A setup issue where the DNS server nsd isn't running at the end of setup is (hopefully) fixed.
* Nextcloud is updated to 23.0.10 (contacts to 4.2.2, calendar to 3.5.1).
Version 60 (October 11, 2022)
-----------------------------
This is the first release for Ubuntu 22.04.
**Before upgrading**, you must **first upgrade your existing Ubuntu 18.04 box to Mail-in-a-Box v0.51 or later**, if you haven't already done so. That may not be possible after Ubuntu 18.04 reaches its end of life in April 2023, so please complete the upgrade well before then. (If you are not using Nextcloud's contacts or calendar, you can migrate to the latest version of Mail-in-a-Box from any previous version.)
For complete upgrade instructions, see:
https://discourse.mailinabox.email/t/version-60-for-ubuntu-22-04-is-about-to-be-released/9558
No major features of Mail-in-a-Box have changed in this release, although some minor fixes were made.
With the newer version of Ubuntu the following software packages we use are updated:
* dovecot is upgraded to 2.3.16, postfix to 3.6.4, opendmark to 1.4 (which adds ARC-Authentication-Results headers), and spampd to 2.53 (alleviating a mail delivery rate limiting bug).
* Nextcloud is upgraded to 23.0.4 (contacts to 4.2.0, calendar to 3.5.0).
* Roundcube is upgraded to 1.6.0.
* certbot is upgraded to 1.21 (via the Ubuntu repository instead of a PPA).
* fail2ban is upgraded to 0.11.2.
* nginx is upgraded to 1.18.
* PHP is upgraded from 7.2 to 8.0.
Also:
* Roundcube's login session cookie was tightened. Existing sessions may require a manual logout.
* Moved Postgrey's database under $STORAGE_ROOT.
Version 57a (June 19, 2022)
---------------------------
* The Backblaze backups fix posted in Version 57 was incomplete. It's now fixed.
Version 57 (June 12, 2022)
--------------------------
Setup:
* Fixed issue upgrading from Mail-in-a-Box v0.40-v0.50 because of a changed URL that Nextcloud is downloaded from.
Backups:
* Fixed S3 backups which broke with duplicity 0.8.23.
* Fixed Backblaze backups which broke with latest b2sdk package by rolling back its version.
Control panel:
* Fixed spurious changes in system status checks messages by sorting DNSSEC DS records.
* Fixed fail2ban lockout over IPv6 from excessive loads of the system status checks.
* Fixed an incorrect IPv6 system status check message.
Version 56 (January 19, 2022)
-----------------------------
Software updates:
* Roundcube updated to 1.5.2 (from 1.5.0), and the persistent_login and CardDAV (to 4.3.0 from 3.0.3) plugins are updated.
* Nextcloud updated to 20.0.14 (from 20.0.8), contacts to 4.0.7 (from 3.5.1), and calendar to 3.0.4 (from 2.2.0).
Setup:
* Fixed failed setup if a previous attempt failed while updating Nextcloud.
Control panel:
* Fixed a crash if a custom DNS entry is not under a zone managed by the box.
* Fix DNSSEC instructions typo.
Other:
* Set systemd journald log retention to 10 days (from no limit) to reduce disk usage.
* Fixed log processing for submission lines that have a sasl_sender or other extra information.
* Fix DNS secondary nameserver refesh failure retry period.
Version 55 (October 18, 2021)
-----------------------------

View file

@ -20,9 +20,9 @@ _If you're seeing an error message about your *IP address being listed in the Sp
### Modifying your `hosts` file
After a while, Mail-in-a-Box will be available at `192.168.56.4` (unless you changed that in your `Vagrantfile`). To be able to use the web-based bits, we recommend to add a hostname to your `hosts` file:
After a while, Mail-in-a-Box will be available at `192.168.50.4` (unless you changed that in your `Vagrantfile`). To be able to use the web-based bits, we recommend to add a hostname to your `hosts` file:
$ echo "192.168.56.4 mailinabox.lan" | sudo tee -a /etc/hosts
$ echo "192.168.50.4 mailinabox.lan" | sudo tee -a /etc/hosts
You should now be able to navigate to https://mailinabox.lan/admin using your browser. There should be an initial admin user with the name `me@mailinabox.lan` and the password `12345678`.

View file

@ -1,8 +1,5 @@
# Power Mail-in-a-Box
## **[Installation](#installation)** (current version: v60.5)
## **[Upgrading Quick Start](#upgrading)**
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/davness)
**[Installation](#installation)** (current version: v55.0)
Power Mail-in-a-Box (a fork of [Mail-in-a-Box](https://mailinabox.email/)) is a complete pre-configured mail appliance, quickly deployable in a matter of minutes.
@ -20,7 +17,7 @@ It's main difference to the main project is focused on ad-hoc, advanced features
## Goals
- **Easy of use** - deployment shouldn't take too many technical details to understand. Power Mail-in-a-Box already comes with default configurations which should be good for most users.
- **Privacy, security and independence** - keeping your mail and data safe from advertisers and prying eyes.
- **Privacy, security and independence** - keeping your mail safe from the big companies.
- **Accessible customizability** - bring the features closer to the people instead of tucking them away in configuration files.
- **Customizability potential** - allow for deep customization by power users.
- **Concentration** - all the services you need in just one box.
@ -39,13 +36,10 @@ The machine this appliance will be installed on needs to have the following spec
- 512MB of RAM (**at least 1GB** is recommended);
- 10GB of disk;
- **One of the following operating systems:**
- - Debian GNU/Linux 11 (Bullseye)
- - Debian GNU/Linux 10 (buster)
- - Debian GNU/Linux 11 (bullseye)
- - Ubuntu LTS 20.04 (Focal Fossa)
- - Ubuntu LTS 22.04 (Jammy Jellyfish)
## Legacy Support
The following distributions are no longer supported for the latest version, but they used to be supported at a earlier time:
- **Debian 10 (Buster)** <= **v56.5**
- - <small> Ubuntu LTS 18.04 (Bionic Beaver) is not supported</small>
<small>_These network requirements are usually not provided by residential ISP's. They are not **strictly required** for Power Mail-in-a-Box to install, but it will take more work to get it running as intended._</small>
- Static, public IPv4 (most residential connections **do not** provide static addresses);
@ -79,23 +73,5 @@ sudo dpkg-reconfigure locales
3. Run the following command, and then follow the instructions that appear on the screen:
```
curl -L https://power-mailinabox.net/setup.sh | sudo bash
curl https://raw.githubusercontent.com/ddavness/power-mailinabox/master/setup/bootstrap.sh | sudo bash
```
# Upgrading
To upgrade an existing box to the latest version, run the same command as you do to perform a new installation:
```
curl -L https://power-mailinabox.net/setup.sh | sudo bash
```
## Installing or upgrading to a different version
If for some reason you wish to install a different version (for example, an older version for a workaround, or a beta/release candidate version for testing), you can use the following command.
```
curl -L https://power-mailinabox.net/<VERSION>/setup.sh | sudo bash
```
Where `<VERSION>` is the version you want to install. (**Example:** `v60.0`).
> ⚠️ **Downgrading might not always be possible and is not supported!** Make sure you know what you're doing before doing so.

19
Vagrantfile vendored
View file

@ -15,31 +15,27 @@ machines = [
{
'iso' => "debian/bullseye64",
'host' => "bullseye"
},
{
'iso' => "generic/ubuntu2204",
'host' => "jammy"
},
}
]
Vagrant.configure("2") do |config|
config.vm.provider :virtualbox do |vb|
vb.customize ["modifyvm", :id, "--cpus", 1, "--memory", 768]
vb.customize ["modifyvm", :id, "--cpus", 1, "--memory", 512]
end
config.vm.provider :libvirt do |v|
v.memory = 768
v.memory = 512
v.cpus = 1
v.nested = true
end
config.vm.provider :kvm do |kvm|
kvm.memory_size = '768m'
kvm.memory_size = '512m'
end
# Network config: Since it's a mail server, the machine must be connected
# to the public web. However, we currently don't want to expose SSH since
# the machine's box will let anyone log into it. So instead we'll put the
# machine on a private network.
config.vm.synced_folder ".", "/vagrant", nfs_version: "4"
config.vm.synced_folder ".", "/vagrant", nfs_version: "3"
(0..(machines.size - 1)).each do |n|
node = machines[n]
@ -49,8 +45,9 @@ Vagrant.configure("2") do |config|
m.vm.network "private_network", ip: "192.168.168.#{ip+n}"
m.vm.provision "shell", :inline => <<-SH
git config --global --add safe.directory /vagrant
# Make sure we have IPv6 loopback (::1)
sysctl -w net.ipv6.conf.lo.disable_ipv6=0
echo -e "fs.inotify.max_user_instances=1024\nnet.ipv6.conf.lo.disable_ipv6=0" > /etc/sysctl.conf
# Set environment variables so that the setup script does
# not ask any questions during provisioning. We'll let the
# machine figure out its own public IP.

View file

@ -15,7 +15,7 @@ info:
license:
name: CC0 1.0 Universal
url: https://creativecommons.org/publicdomain/zero/1.0/legalcode
version: 60.5
version: 55.0
x-logo:
url: https://mailinabox.email/static/logo.png
altText: Mail-in-a-Box logo
@ -77,7 +77,7 @@ paths:
x-codeSamples:
- lang: curl
source: |
curl -X POST "https://{host}/admin/login" \
curl -X GET "https://{host}/admin/login" \
-u "<email>:<password>"
responses:
200:
@ -109,15 +109,13 @@ paths:
x-codeSamples:
- lang: curl
source: |
curl -X POST "https://{host}/admin/logout" \
curl -X GET "https://{host}/admin/logout" \
-u "<email>:<session_key>"
responses:
200:
description: Successful operation
content:
application/json:
schema:
$ref: '#/components/schemas/LogoutResponse'
/system/status:
post:
tags:
@ -3417,8 +3415,3 @@ components:
nullable: true
MfaDisableSuccessResponse:
type: string
LogoutResponse:
type: object
properties:
status:
type: string

View file

@ -5,7 +5,7 @@
# Whitelist our own IP addresses. 127.0.0.1/8 is the default. But our status checks
# ping services over the public interface so we should whitelist that address of
# ours too. The string is substituted during installation.
ignoreip = 127.0.0.1/8 PUBLIC_IP ::1 PUBLIC_IPV6
ignoreip = 127.0.0.1/8 PUBLIC_IP
[dovecot]
enabled = true

View file

@ -4,7 +4,6 @@ After=multi-user.target
[Service]
Type=idle
IgnoreSIGPIPE=False
ExecStart=/usr/local/lib/mailinabox/start
[Install]

View file

@ -90,7 +90,7 @@
<br><br>
<h2 align=center>Oh and by the way: thank you for sticking by!</h2>
<p align=center>This project is maintained <a href="https://power-mailinabox.net">on GitHub</a>.
<p align=center>This project is maintained <a href="https://github.com/ddavness/power-mailinabox">on GitHub</a>.
Feel free to take a peek and maybe leave a star. It is very much appreciated! ❤</p>
<p align=center>Also feel free report any issues you may find, or leave your ideas.</p>
</div>

View file

@ -1,9 +1,4 @@
import base64
import os
import os.path
import hmac
import json
import secrets
import base64, os, os.path, hmac, json, secrets
from datetime import timedelta
from expiringdict import ExpiringDict
@ -15,24 +10,32 @@ 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 AuthService:
def __init__(self):
self.auth_realm = DEFAULT_AUTH_REALM
self.key_path = DEFAULT_KEY_PATH
self.max_session_duration = timedelta(days=2)
self.init_system_api_key()
self.sessions = ExpiringDict(
max_len=64,
max_age_seconds=self.max_session_duration.total_seconds())
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"""
with open(self.key_path, 'r') as file:
self.key = file.read()
def create_file_with_mode(path, mode):
# Based on answer by A-B-B: http://stackoverflow.com/a/15015748
old_umask = os.umask(0)
try:
return os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT, mode), 'w')
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, login_only=False, logout=False):
"""Test if the HTTP Authorization header's username matches the system key, a session key,
@ -43,10 +46,8 @@ class AuthService:
this key is not associated with a user."""
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)
@ -58,15 +59,12 @@ class AuthService:
username, password = credentials.split(':', maxsplit=1)
return username, password
username, password = parse_http_authorization_basic(
request.headers.get('Authorization', ''))
username, password = parse_http_authorization_basic(request.headers.get('Authorization', ''))
if username in (None, ""):
raise ValueError("Authorization header invalid.")
if username.strip() == "" and password.strip() == "":
raise ValueError(
"No email address, password, session key, or API key provided."
)
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.
@ -74,8 +72,7 @@ class AuthService:
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:
if self.get_session(username, password, "login", env) and not login_only:
sessionid = password
session = self.sessions[sessionid]
if logout:
@ -99,8 +96,7 @@ class AuthService:
# 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])
if isinstance(privs, tuple): raise ValueError(privs[0])
# Return the authorization information.
return (username, privs)
@ -124,12 +120,9 @@ class AuthService:
# 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,
"/usr/bin/doveadm", "pw",
"-p", pw,
"-t", pw_hash,
])
except:
# Login failed.
@ -148,8 +141,7 @@ class AuthService:
# 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")
msg += b" " + json.dumps(get_hash_mfa_state(email, env), sort_keys=True).encode("utf8")
# Make a HMAC using the system API key as a hash key.
hash_key = self.key.encode('ascii')
@ -160,21 +152,15 @@ class AuthService:
token = secrets.token_hex(32)
self.sessions[token] = {
"email": username,
"password_token":
self.create_user_password_state_token(username, env),
"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
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
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

View file

@ -7,20 +7,27 @@
# 4) The stopped services are restarted.
# 5) STORAGE_ROOT/backup/after-backup is executed if it exists.
import os
import os.path
import shutil
import glob
import re
import datetime
import sys
import dateutil.parser
import dateutil.relativedelta
import dateutil.tz
import os, os.path, shutil, glob, re, datetime, sys
import dateutil.parser, dateutil.relativedelta, dateutil.tz
import rtyaml
from exclusiveprocess import Lock, CannotAcquireLock
from utils import load_environment, shell, wait_for_service, get_php_version
from utils import load_environment, shell, wait_for_service, fix_boto, get_php_version, get_os_code
def rsync_ssh_options(port = 22, direct = False):
# Just in case we pass a string
try:
port = int(port)
except Exception:
port = 22
if direct:
return f"/usr/bin/ssh -oStrictHostKeyChecking=no -oBatchMode=yes -p {port} -i /root/.ssh/id_rsa_miab"
else:
return [
f"--ssh-options= -i /root/.ssh/id_rsa_miab -p {port}",
f"--rsync-options= -e \"/usr/bin/ssh -oStrictHostKeyChecking=no -oBatchMode=yes -p {port} -i /root/.ssh/id_rsa_miab\"",
]
def backup_status(env):
# If backups are disabled, return no status.
@ -37,23 +44,15 @@ def backup_status(env):
backup_cache_dir = os.path.join(backup_root, 'cache')
def reldate(date, ref, clip):
if ref < date:
return clip
if ref < date: return clip
rd = dateutil.relativedelta.relativedelta(ref, date)
if rd.years > 1:
return "%d years, %d months" % (rd.years, rd.months)
if rd.years == 1:
return "%d year, %d months" % (rd.years, rd.months)
if rd.months > 1:
return "%d months, %d days" % (rd.months, rd.days)
if rd.months == 1:
return "%d month, %d days" % (rd.months, rd.days)
if rd.days >= 7:
return "%d days" % rd.days
if rd.days > 1:
return "%d days, %d hours" % (rd.days, rd.hours)
if rd.days == 1:
return "%d day, %d hours" % (rd.days, rd.hours)
if rd.years > 1: return "%d years, %d months" % (rd.years, rd.months)
if rd.years == 1: return "%d year, %d months" % (rd.years, rd.months)
if rd.months > 1: return "%d months, %d days" % (rd.months, rd.days)
if rd.months == 1: return "%d month, %d days" % (rd.months, rd.days)
if rd.days >= 7: return "%d days" % rd.days
if rd.days > 1: return "%d days, %d hours" % (rd.days, rd.hours)
if rd.days == 1: return "%d day, %d hours" % (rd.days, rd.hours)
return "%d hours, %d minutes" % (rd.hours, rd.minutes)
# Get duplicity collection status and parse for a list of backups.
@ -66,25 +65,23 @@ def backup_status(env):
"date_delta": reldate(date, now, "the future?"),
"full": keys[0] == "full",
"size": 0, # collection-status doesn't give us the size
# number of archive volumes for this backup (not really helpful)
"volumes": int(keys[2]),
"volumes": int(keys[2]), # number of archive volumes for this backup (not really helpful)
}
code, collection_status = shell('check_output', [
"/usr/local/bin/duplicity",
"/usr/bin/duplicity",
"collection-status",
"--archive-dir", backup_cache_dir,
"--gpg-options", "--cipher-algo=AES256",
"--log-fd", "1",
get_duplicity_target_url(config),
] + get_duplicity_additional_args(env),
get_duplicity_env_vars(env),
config["target"],
] + rsync_ssh_options(port = config["target_rsync_port"]),
get_env(env),
trap=True)
if code != 0:
# Command failed. This is likely due to an improperly configured remote
# destination for the backups or the last backup job terminated unexpectedly.
raise Exception("Something is wrong with the backup: " +
collection_status)
raise Exception("Something is wrong with the backup: " + collection_status)
for line in collection_status.split('\n'):
if line.startswith(" full") or line.startswith(" inc"):
backup = parse_line(line)
@ -97,11 +94,8 @@ def backup_status(env):
# space is used for those.
unmatched_file_size = 0
for fn, size in list_target_files(config):
m = re.match(
r"duplicity-(full|full-signatures|(inc|new-signatures)\.(?P<incbase>\d+T\d+Z)\.to)\.(?P<date>\d+T\d+Z)\.",
fn)
if not m:
continue # not a part of a current backup chain
m = re.match(r"duplicity-(full|full-signatures|(inc|new-signatures)\.(?P<incbase>\d+T\d+Z)\.to)\.(?P<date>\d+T\d+Z)\.", fn)
if not m: continue # not a part of a current backup chain
key = m.group("date")
if key in backups:
backups[key]["size"] += size
@ -139,23 +133,16 @@ def backup_status(env):
if incremental_count > 0 and incremental_size > 0 and first_full_size is not None:
# How many days until the next incremental backup? First, the part of
# the algorithm based on increment sizes:
est_days_to_next_full = (.5 * first_full_size - incremental_size) / (
incremental_size / incremental_count)
est_time_of_next_full = first_date + \
datetime.timedelta(days=est_days_to_next_full)
est_days_to_next_full = (.5 * first_full_size - incremental_size) / (incremental_size/incremental_count)
est_time_of_next_full = first_date + datetime.timedelta(days=est_days_to_next_full)
# ...And then the part of the algorithm based on full backup age:
est_time_of_next_full = min(
est_time_of_next_full, first_full_date +
datetime.timedelta(days=config["min_age_in_days"] * 10 + 1))
est_time_of_next_full = min(est_time_of_next_full, first_full_date + datetime.timedelta(days=config["min_age_in_days"]*10+1))
# It still can't be deleted until it's old enough.
est_deleted_on = max(
est_time_of_next_full,
first_date + datetime.timedelta(days=config["min_age_in_days"]))
est_deleted_on = max(est_time_of_next_full, first_date + datetime.timedelta(days=config["min_age_in_days"]))
deleted_in = "approx. %d days" % round(
(est_deleted_on - now).total_seconds() / 60 / 60 / 24 + .5)
deleted_in = "approx. %d days" % round((est_deleted_on-now).total_seconds()/60/60/24 + .5)
# When will a backup be deleted? Set the deleted_in field of each backup.
saw_full = False
@ -171,11 +158,7 @@ def backup_status(env):
elif saw_full and not deleted_in:
# We're now on backups prior to the most recent full backup. These are
# free to be deleted as soon as they are min_age_in_days old.
deleted_in = reldate(
now,
dateutil.parser.parse(bak["date"]) +
datetime.timedelta(days=config["min_age_in_days"]),
"on next daily backup")
deleted_in = reldate(now, dateutil.parser.parse(bak["date"]) + datetime.timedelta(days=config["min_age_in_days"]), "on next daily backup")
bak["deleted_in"] = deleted_in
return {
@ -183,7 +166,6 @@ def backup_status(env):
"unmatched_file_size": unmatched_file_size,
}
def should_force_full(config, env):
# Force a full backup when the total size of the increments
# since the last full backup is greater than half the size
@ -201,9 +183,7 @@ def should_force_full(config, env):
# backup, as well as the age of the full backup.
if inc_size > .5*bak["size"]:
return True
if dateutil.parser.parse(bak["date"]) + datetime.timedelta(
days=config["min_age_in_days"] * 10 +
1) < datetime.datetime.now(dateutil.tz.tzlocal()):
if dateutil.parser.parse(bak["date"]) + datetime.timedelta(days=config["min_age_in_days"]*10+1) < datetime.datetime.now(dateutil.tz.tzlocal()):
return True
return False
else:
@ -211,7 +191,6 @@ def should_force_full(config, env):
# (I love for/else blocks. Here it's just to show off.)
return True
def get_passphrase(env):
# Get the encryption passphrase. secret_key.txt is 2048 random
# bits base64-encoded and with line breaks every 65 characters.
@ -222,56 +201,11 @@ def get_passphrase(env):
backup_root = os.path.join(env["STORAGE_ROOT"], 'backup')
with open(os.path.join(backup_root, 'secret_key.txt')) as f:
passphrase = f.readline().strip()
if len(passphrase) < 43:
raise Exception("secret_key.txt's first line is too short!")
if len(passphrase) < 43: raise Exception("secret_key.txt's first line is too short!")
return passphrase
def get_duplicity_target_url(config):
target = config["target"]
if get_target_type(config) == "s3":
from urllib.parse import urlsplit, urlunsplit
target = list(urlsplit(target))
# Although we store the S3 hostname in the target URL,
# duplicity no longer accepts it in the target URL. The hostname in
# the target URL must be the bucket name. The hostname is passed
# via get_duplicity_additional_args. Move the first part of the
# path (the bucket name) into the hostname URL component, and leave
# the rest for the path.
target_bucket = target[2].lstrip('/').split('/', 1)
target[1] = target_bucket[0]
target[2] = target_bucket[1] if len(target_bucket) > 1 else ''
target = urlunsplit(target)
return target
def get_duplicity_additional_args(env):
config = get_backup_config(env)
port = 0
try:
port = int(config["target_rsync_port"])
except Exception:
port = 22
if get_target_type(config) == 'rsync':
return [
f"--ssh-options= -i /root/.ssh/id_rsa_miab -p {port}",
f"--rsync-options= -e \"/usr/bin/ssh -oStrictHostKeyChecking=no -oBatchMode=yes -p {port} -i /root/.ssh/id_rsa_miab\"",
]
elif get_target_type(config) == 's3':
# See note about hostname in get_duplicity_target_url.
from urllib.parse import urlsplit, urlunsplit
target = urlsplit(config["target"])
endpoint_url = urlunsplit(("https", target.netloc, '', '', ''))
return ["--s3-endpoint-url", endpoint_url]
return []
def get_duplicity_env_vars(env):
def get_env(env):
config = get_backup_config(env)
env = { "PASSPHRASE" : get_passphrase(env) }
@ -282,12 +216,10 @@ def get_duplicity_env_vars(env):
return env
def get_target_type(config):
protocol = config["target"].split(":")[0]
return protocol
def perform_backup(full_backup, user_initiated=False):
env = load_environment()
php_fpm = f"php{get_php_version()}-fpm"
@ -328,10 +260,7 @@ def perform_backup(full_backup, user_initiated=False):
# Stop services.
def service_command(service, command, quit=None):
# Execute silently, but if there is an error then display the output & exit.
code, ret = shell('check_output',
["/usr/sbin/service", service, command],
capture_stderr=True,
trap=True)
code, ret = shell('check_output', ["/usr/sbin/service", service, command], capture_stderr=True, trap=True)
if code != 0:
print(ret)
if quit:
@ -340,7 +269,6 @@ def perform_backup(full_backup, user_initiated=False):
service_command(php_fpm, "stop", quit=True)
service_command("postfix", "stop", quit=True)
service_command("dovecot", "stop", quit=True)
service_command("postgrey", "stop", quit=True)
# Execute a pre-backup script that copies files outside the homedir.
# Run as the STORAGE_USER user, not as root. Pass our settings in
@ -356,7 +284,7 @@ def perform_backup(full_backup, user_initiated=False):
# after the first backup. See #396.
try:
shell('check_call', [
"/usr/local/bin/duplicity",
"/usr/bin/duplicity",
"full" if full_backup else "incr",
"--verbosity", "warning", "--no-print-statistics",
"--archive-dir", backup_cache_dir,
@ -364,13 +292,12 @@ def perform_backup(full_backup, user_initiated=False):
"--volsize", "250",
"--gpg-options", "--cipher-algo=AES256",
env["STORAGE_ROOT"],
get_duplicity_target_url(config),
config["target"],
"--allow-source-mismatch"
] + get_duplicity_additional_args(env),
get_duplicity_env_vars(env))
] + rsync_ssh_options(port = config["target_rsync_port"]),
get_env(env))
finally:
# Start services again.
service_command("postgrey", "start", quit=False)
service_command("dovecot", "start", quit=False)
service_command("postfix", "start", quit=False)
service_command(php_fpm, "start", quit=False)
@ -378,15 +305,15 @@ def perform_backup(full_backup, user_initiated=False):
# Remove old backups. This deletes all backup data no longer needed
# from more than 3 days ago.
shell('check_call', [
"/usr/local/bin/duplicity",
"/usr/bin/duplicity",
"remove-older-than",
"%dD" % config["min_age_in_days"],
"--verbosity", "error",
"--archive-dir", backup_cache_dir,
"--force",
get_duplicity_target_url(config)
] + get_duplicity_additional_args(env),
get_duplicity_env_vars(env))
config["target"]
] + rsync_ssh_options(port = config["target_rsync_port"]),
get_env(env))
# From duplicity's manual:
# "This should only be necessary after a duplicity session fails or is
@ -394,20 +321,19 @@ def perform_backup(full_backup, user_initiated=False):
# That may be unlikely here but we may as well ensure we tidy up if
# that does happen - it might just have been a poorly timed reboot.
shell('check_call', [
"/usr/local/bin/duplicity",
"/usr/bin/duplicity",
"cleanup",
"--verbosity", "error",
"--archive-dir", backup_cache_dir,
"--force",
get_duplicity_target_url(config)
] + get_duplicity_additional_args(env),
get_duplicity_env_vars(env))
config["target"]
] + rsync_ssh_options(port = config["target_rsync_port"]),
get_env(env))
# Change ownership of backups to the user-data user, so that the after-bcakup
# script can access them.
if get_target_type(config) == 'file':
shell('check_call',
["/bin/chown", "-R", env["STORAGE_USER"], backup_dir])
shell('check_call', ["/bin/chown", "-R", env["STORAGE_USER"], backup_dir])
# Execute a post-backup script that does the copying to a remote server.
# Run as the STORAGE_USER user, not as root. Pass our settings in
@ -430,7 +356,6 @@ def perform_backup(full_backup, user_initiated=False):
wait_for_service(25, True, env, 10)
wait_for_service(993, True, env, 10)
def run_duplicity_verification():
env = load_environment()
backup_root = os.path.join(env["STORAGE_ROOT"], 'backup')
@ -438,28 +363,27 @@ def run_duplicity_verification():
backup_cache_dir = os.path.join(backup_root, 'cache')
shell('check_call', [
"/usr/local/bin/duplicity",
"--verbosity",
"info",
"/usr/bin/duplicity",
"--verbosity", "info",
"verify",
"--compare-data",
"--archive-dir", backup_cache_dir,
"--exclude", backup_root,
get_duplicity_target_url(config),
config["target"],
env["STORAGE_ROOT"],
] + get_duplicity_additional_args(env), get_duplicity_env_vars(env))
] + rsync_ssh_options(port = config["target_rsync_port"]), get_env(env))
def run_duplicity_restore(args):
env = load_environment()
config = get_backup_config(env)
backup_cache_dir = os.path.join(env["STORAGE_ROOT"], 'backup', 'cache')
shell('check_call', [
"/usr/local/bin/duplicity",
"/usr/bin/duplicity",
"restore",
"--archive-dir", backup_cache_dir,
get_duplicity_target_url(config),
] + get_duplicity_additional_args(env) + args,
get_duplicity_env_vars(env))
config["target"],
] + rsync_ssh_options(port = config["target_rsync_port"]) + args,
get_env(env))
def list_target_files(config):
import urllib.parse
@ -469,8 +393,7 @@ def list_target_files(config):
return "invalid target"
if target.scheme == "file":
return [(fn, os.path.getsize(os.path.join(target.path, fn)))
for fn in os.listdir(target.path)]
return [(fn, os.path.getsize(os.path.join(target.path, fn))) for fn in os.listdir(target.path)]
elif target.scheme == "rsync":
rsync_fn_size_re = re.compile(r'.* ([^ ]*) [^ ]* [^ ]* (.*)')
@ -482,24 +405,23 @@ def list_target_files(config):
if target_path.startswith('/'):
target_path = target_path[1:]
rsync_command = [
'rsync', '-e',
f"/usr/bin/ssh -oStrictHostKeyChecking=no -oBatchMode=yes -p {int(config.get('target_rsync_port', 22))} -i /root/.ssh/id_rsa_miab",
'--list-only', '-r',
rsync_target.format(host=target.netloc, path=target_path)
rsync_command = [ 'rsync',
'-e',
rsync_ssh_options(config["target_rsync_port"], direct = True),
'--list-only',
'-r',
rsync_target.format(
host=target.netloc,
path=target_path)
]
code, listing = shell('check_output',
rsync_command,
trap=True,
capture_stderr=True)
code, listing = shell('check_output', rsync_command, trap=True, capture_stderr=True)
if code == 0:
ret = []
for l in listing.split('\n'):
match = rsync_fn_size_re.match(l)
if match:
ret.append((match.groups()[1],
int(match.groups()[0].replace(',', ''))))
ret.append( (match.groups()[1], int(match.groups()[0].replace(',',''))) )
return ret
else:
if 'Permission denied (publickey).' in listing:
@ -507,26 +429,36 @@ def list_target_files(config):
elif 'No such file or directory' in listing:
reason = "Provided path {} is invalid.".format(target_path)
elif 'Network is unreachable' in listing:
reason = "The IP address {} is unreachable.".format(
target.hostname)
reason = "The IP address {} is unreachable.".format(target.hostname)
elif 'Could not resolve hostname' in listing:
reason = "The hostname {} cannot be resolved.".format(
target.hostname)
reason = "The hostname {} cannot be resolved.".format(target.hostname)
else:
reason = "Unknown error. " \
"Please check running 'management/backup.py --verify' " \
"from mailinabox sources to debug the issue."
raise ValueError(
"Connection to rsync host failed: {}".format(reason))
raise ValueError("Connection to rsync host failed: {}".format(reason))
elif target.scheme == "s3":
import boto3.s3
from botocore.exceptions import ClientError
# match to a Region
fix_boto() # must call prior to importing boto
import boto.s3
from boto.exception import BotoServerError
custom_region = False
for region in boto.s3.regions():
if region.endpoint == target.hostname:
break
else:
# If region is not found this is a custom region
custom_region = True
# separate bucket from path in target
bucket = target.path[1:].split('/')[0]
path = '/'.join(target.path[1:].split('/')[1:]) + '/'
# Create a custom region with custom endpoint
if custom_region:
from boto.s3.connection import S3Connection
region = boto.s3.S3RegionInfo(name=bucket, endpoint=target.hostname, connection_cls=S3Connection)
# If no prefix is specified, set the path to '', otherwise boto won't list the files
if path == '/':
path = ''
@ -536,20 +468,30 @@ def list_target_files(config):
# connect to the region & bucket
try:
s3 = boto3.client('s3', \
endpoint_url=f'https://{target.hostname}', \
aws_access_key_id=config['target_user'], \
aws_secret_access_key=config['target_pass'])
bucket_objects = s3.list_objects_v2(Bucket=bucket, Prefix=path).get("Contents", [])
backup_list = [(key['Key'][len(path):], key['Size']) for key in bucket_objects]
except ClientError as e:
raise ValueError(e)
return backup_list
conn = region.connect(aws_access_key_id=config["target_user"], aws_secret_access_key=config["target_pass"])
bucket = conn.get_bucket(bucket)
except BotoServerError as e:
if e.status == 403:
raise ValueError("Invalid S3 access key or secret access key.")
elif e.status == 404:
raise ValueError("Invalid S3 bucket name.")
elif e.status == 301:
raise ValueError("Incorrect region for this bucket.")
raise ValueError(e.reason)
return [(key.name[len(path):], key.size) for key in bucket.list(prefix=path)]
elif target.scheme == 'b2':
InMemoryAccountInfo = None
B2Api = None
NonExistentBucket = None
if get_os_code() == "Debian10":
# WARNING: This is deprecated code using a legacy library.
# We need it because Debian 10 ships with an old version of Duplicity
from b2.account_info import InMemoryAccountInfo
from b2.api import B2Api
from b2.exception import NonExistentBucket
else:
from b2sdk.v1 import InMemoryAccountInfo, B2Api
from b2sdk.v1.exception import NonExistentBucket
@ -558,18 +500,14 @@ def list_target_files(config):
# Extract information from target
b2_application_keyid = target.netloc[:target.netloc.index(':')]
b2_application_key = target.netloc[target.netloc.index(':') +
1:target.netloc.index('@')]
b2_application_key = target.netloc[target.netloc.index(':')+1:target.netloc.index('@')]
b2_bucket = target.netloc[target.netloc.index('@')+1:]
try:
b2_api.authorize_account("production", b2_application_keyid,
b2_application_key)
b2_api.authorize_account("production", b2_application_keyid, b2_application_key)
bucket = b2_api.get_bucket_by_name(b2_bucket)
except NonExistentBucket as e:
raise ValueError(
"B2 Bucket does not exist. Please double check your information!"
)
raise ValueError("B2 Bucket does not exist. Please double check your information!")
return [(key.file_name, key.size) for key, _ in bucket.ls()]
else:
@ -608,19 +546,20 @@ def backup_set_custom(env, target, target_user, target_pass, target_rsync_port,
return "OK"
def get_backup_config(env, for_save=False, for_ui=False):
backup_root = os.path.join(env["STORAGE_ROOT"], 'backup')
# Defaults.
config = {"min_age_in_days": 3, "target": "local", "target_rsync_port": 22}
config = {
"min_age_in_days": 3,
"target": "local",
"target_rsync_port": 22
}
# Merge in anything written to custom.yaml.
try:
custom_config = rtyaml.load(
open(os.path.join(backup_root, 'custom.yaml')))
if not isinstance(custom_config, dict):
raise ValueError() # caught below
custom_config = rtyaml.load(open(os.path.join(backup_root, 'custom.yaml')))
if not isinstance(custom_config, dict): raise ValueError() # caught below
config.update(custom_config)
except:
pass
@ -648,13 +587,11 @@ def get_backup_config(env, for_save=False, for_ui=False):
return config
def write_backup_config(env, newconfig):
backup_root = os.path.join(env["STORAGE_ROOT"], 'backup')
with open(os.path.join(backup_root, 'custom.yaml'), "w") as f:
f.write(rtyaml.dump(newconfig))
if __name__ == "__main__":
import sys
if sys.argv[-1] == "--verify":
@ -664,8 +601,7 @@ if __name__ == "__main__":
elif sys.argv[-1] == "--list":
# List the saved backup files.
for fn, size in list_target_files(get_backup_config(
load_environment())):
for fn, size in list_target_files(get_backup_config(load_environment())):
print("{}\t{}".format(fn, size))
elif sys.argv[-1] == "--status":

View file

@ -6,14 +6,7 @@
# root API key. This file is readable only by root, so this
# tool can only be used as root.
import sys
import getpass
import urllib.request
import urllib.error
import json
import re
import csv
import sys, getpass, urllib.request, urllib.error, json, re, csv
def mgmt(cmd, data=None, is_json=False):
# The base URL for the management daemon. (Listens on IPv4 only.)
@ -21,9 +14,7 @@ def mgmt(cmd, data=None, is_json=False):
setup_key_auth(mgmt_uri)
req = urllib.request.Request(
mgmt_uri + cmd,
urllib.parse.urlencode(data).encode("utf8") if data else None)
req = urllib.request.Request(mgmt_uri + cmd, urllib.parse.urlencode(data).encode("utf8") if data else None)
try:
response = urllib.request.urlopen(req)
except urllib.error.HTTPError as e:
@ -32,20 +23,16 @@ def mgmt(cmd, data=None, is_json=False):
print(e.read().decode("utf8"))
except:
pass
print(
"The management daemon refused access. The API key file may be out of sync. Try 'service mailinabox restart'.",
file=sys.stderr)
print("The management daemon refused access. The API key file may be out of sync. Try 'service mailinabox restart'.", file=sys.stderr)
elif hasattr(e, 'read'):
print(e.read().decode('utf8'), file=sys.stderr)
else:
print(e, file=sys.stderr)
sys.exit(1)
resp = response.read().decode('utf8')
if is_json:
resp = json.loads(resp)
if is_json: resp = json.loads(resp)
return resp
def read_password():
while True:
first = getpass.getpass('password: ')
@ -59,19 +46,18 @@ def read_password():
break
return first
def setup_key_auth(mgmt_uri):
key = open('/var/lib/mailinabox/api.key').read().strip()
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(realm='Mail-in-a-Box Management Server',
auth_handler.add_password(
realm='Mail-in-a-Box Management Server',
uri=mgmt_uri,
user=key,
passwd='')
opener = urllib.request.build_opener(auth_handler)
urllib.request.install_opener(opener)
if len(sys.argv) < 2:
print("""Usage:
{cli} system default-quota [new default] (set default quota for system)
@ -91,15 +77,16 @@ if len(sys.argv) < 2:
{cli} alias remove incoming.name@domain.com
Removing a mail user does not delete their mail folders on disk. It only prevents IMAP/SMTP login.
""".format(cli="management/cli.py"))
""".format(
cli="management/cli.py"
))
elif sys.argv[1] == "user" and len(sys.argv) == 2:
# Dump a list of users, one per line. Mark admins with an asterisk.
users = mgmt("/mail/users?format=json", is_json=True)
for domain in users:
for user in domain["users"]:
if user['status'] == 'inactive':
continue
if user['status'] == 'inactive': continue
print(user['email'], end='')
if "admin" in user['privileges']:
print("*", end='')
@ -127,18 +114,12 @@ elif sys.argv[1] == "user" and sys.argv[2] in ("add", "password"):
elif sys.argv[1] == "user" and sys.argv[2] == "remove" and len(sys.argv) == 4:
print(mgmt("/mail/users/remove", { "email": sys.argv[3] }))
elif sys.argv[1] == "user" and sys.argv[2] in ("make-admin",
"remove-admin") and len(
sys.argv) == 4:
elif sys.argv[1] == "user" and sys.argv[2] in ("make-admin", "remove-admin") and len(sys.argv) == 4:
if sys.argv[2] == "make-admin":
action = "add"
else:
action = "remove"
print(
mgmt("/mail/users/privileges/" + action, {
"email": sys.argv[3],
"privilege": "admin"
}))
print(mgmt("/mail/users/privileges/" + action, { "email": sys.argv[3], "privilege": "admin" }))
elif sys.argv[1] == "user" and sys.argv[2] == "admins":
# Dump a list of admin users.
@ -154,13 +135,9 @@ elif sys.argv[1] == "user" and sys.argv[2] == "quota" and len(sys.argv) == 4:
elif sys.argv[1] == "user" and sys.argv[2] == "quota" and len(sys.argv) == 5:
# Set a user's quota
users = mgmt("/mail/users/quota", {
"email": sys.argv[3],
"quota": sys.argv[4]
})
users = mgmt("/mail/users/quota", { "email": sys.argv[3], "quota": sys.argv[4] })
elif sys.argv[1] == "user" and len(
sys.argv) == 5 and sys.argv[2:4] == ["mfa", "show"]:
elif sys.argv[1] == "user" and len(sys.argv) == 5 and sys.argv[2:4] == ["mfa", "show"]:
# Show MFA status for a user.
status = mgmt("/mfa/status", { "user": sys.argv[4] }, is_json=True)
W = csv.writer(sys.stdout)
@ -168,37 +145,26 @@ elif sys.argv[1] == "user" and len(
for mfa in status["enabled_mfa"]:
W.writerow([mfa["id"], mfa["type"], mfa["label"]])
elif sys.argv[1] == "user" and len(
sys.argv) in (5, 6) and sys.argv[2:4] == ["mfa", "disable"]:
elif sys.argv[1] == "user" and len(sys.argv) in (5, 6) and sys.argv[2:4] == ["mfa", "disable"]:
# Disable MFA (all or a particular device) for a user.
print(
mgmt(
"/mfa/disable", {
"user": sys.argv[4],
"mfa-id": sys.argv[5] if len(sys.argv) == 6 else None
}))
print(mgmt("/mfa/disable", { "user": sys.argv[4], "mfa-id": sys.argv[5] if len(sys.argv) == 6 else None }))
elif sys.argv[1] == "alias" and len(sys.argv) == 2:
print(mgmt("/mail/aliases"))
elif sys.argv[1] == "alias" and sys.argv[2] == "add" and len(sys.argv) == 5:
print(
mgmt("/mail/aliases/add", {
"address": sys.argv[3],
"forwards_to": sys.argv[4]
}))
print(mgmt("/mail/aliases/add", { "address": sys.argv[3], "forwards_to": sys.argv[4] }))
elif sys.argv[1] == "alias" and sys.argv[2] == "remove" and len(sys.argv) == 4:
print(mgmt("/mail/aliases/remove", { "address": sys.argv[3] }))
elif sys.argv[1] == "system" and sys.argv[2] == "default-quota" and len(
sys.argv) == 3:
elif sys.argv[1] == "system" and sys.argv[2] == "default-quota" and len(sys.argv) == 3:
print(mgmt("/system/default-quota?text=1"))
elif sys.argv[1] == "system" and sys.argv[2] == "default-quota" and len(
sys.argv) == 4:
elif sys.argv[1] == "system" and sys.argv[2] == "default-quota" and len(sys.argv) == 4:
print(mgmt("/system/default-quota", { "default_quota": sys.argv[3]}))
else:
print("Invalid command-line arguments.")
sys.exit(1)

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -24,18 +24,9 @@
# create the new config file in memory
import sys
import re
import sys, re
def edit_conf(filename,
settings,
delimiter_re,
delimiter,
comment_char,
folded_lines=False,
testing=False,
erase_setting=False):
def edit_conf(filename, settings, delimiter_re, delimiter, comment_char, folded_lines = False, testing = False):
found = set()
buf = ""
input_lines = list(open(filename, "r+"))
@ -51,38 +42,34 @@ def edit_conf(filename,
# See if this line is for any settings passed on the command line.
for i in range(len(settings)):
# Check whether this line contain this setting from the command-line arguments.
# Check that this line contain this setting from the command-line arguments.
name, val = settings[i].split("=", 1)
m = re.match(
"(\s*)" + "(" + re.escape(comment_char) + "\s*)?" +
re.escape(name) + delimiter_re + "(.*?)\s*$", line, re.S)
if not m:
continue
"(\s*)"
+ "(" + re.escape(comment_char) + "\s*)?"
+ re.escape(name) + delimiter_re + "(.*?)\s*$",
line, re.S)
if not m: continue
indent, is_comment, existing_val = m.groups()
# If this is already the setting, keep it in the file, except:
# * If we've already seen it before, then remove this duplicate line.
# * If val is empty and erase_setting is on, then comment it out.
if is_comment is None and existing_val == val and not (not val and erase_setting):
# If this is already the setting, do nothing.
if is_comment is None and existing_val == val:
# It may be that we've already inserted this setting higher
# in the file so check for that first.
if i in found:
break
if i in found: break
buf += line
found.add(i)
break
# comment-out the existing line (also comment any folded lines)
if is_comment is None:
buf += comment_char + line.rstrip().replace(
"\n", "\n" + comment_char) + "\n"
buf += comment_char + line.rstrip().replace("\n", "\n" + comment_char) + "\n"
else:
# the line is already commented, pass it through
buf += line
# if this option oddly appears more than once, don't add the setting again
# Or if we're clearing it, don't add it
if (i in found) or (not val and erase_setting):
if i in found:
break
# add the new setting
@ -96,11 +83,10 @@ def edit_conf(filename,
# If did not match any setting names, pass this line through.
buf += line
# Put any settings we didn't see at the end of the file, except those being erased.
# Put any settings we didn't see at the end of the file.
for i in range(len(settings)):
if i not in found:
name, val = settings[i].split("=", 1)
if not (not val and erase_setting):
buf += name + delimiter + val + "\n"
if not testing:
@ -111,14 +97,11 @@ def edit_conf(filename,
# Just print the new file to stdout.
print(buf)
# Run standalone
if __name__ == "__main__":
# sanity check
if len(sys.argv) < 3:
print(
"usage: python3 editconf.py /etc/file.conf [-s] [-w] [-c <CHARACTER>] [-t] NAME=VAL [NAME=VAL ...]"
)
print("usage: python3 editconf.py /etc/file.conf [-s] [-w] [-c <CHARACTER>] [-t] NAME=VAL [NAME=VAL ...]")
sys.exit(1)
# parse command line arguments
@ -130,16 +113,12 @@ if __name__ == "__main__":
comment_char = "#"
folded_lines = False
testing = False
erase_setting = False
while settings[0][0] == "-" and settings[0] != "--":
opt = settings.pop(0)
if opt == "-s":
# Space is the delimiter
delimiter = " "
delimiter_re = r"\s+"
elif opt == "-e":
# Erase settings that have empty values.
erase_setting = True
elif opt == "-w":
# Line folding is possible in this file.
folded_lines = True
@ -161,5 +140,4 @@ if __name__ == "__main__":
print("Invalid command line: ", subprocess.list2cmdline(sys.argv))
sys.exit(1)
edit_conf(filename, settings, delimiter_re, delimiter, comment_char,
folded_lines, testing, erase_setting)
edit_conf(filename, settings, delimiter_re, delimiter, comment_char, folded_lines, testing)

View file

@ -39,13 +39,11 @@ msg = MIMEMultipart('alternative')
noreply = "noreply-daemon@" + env['PRIMARY_HOSTNAME']
admin_addr = "administrator@" + env['PRIMARY_HOSTNAME']
msg['From'] = "\"%s\" <%s>" % ("System Management Daemon",
"noreply-daemon@" + env['PRIMARY_HOSTNAME'])
msg['From'] = "\"%s\" <%s>" % ("System Management Daemon", "noreply-daemon@" + env['PRIMARY_HOSTNAME'])
msg['To'] = "administrator@" + env['PRIMARY_HOSTNAME']
msg['Subject'] = "[%s] %s" % (env['PRIMARY_HOSTNAME'], subject)
content_html = "<html><body><pre>{}</pre></body></html>".format(
html.escape(content))
content_html = "<html><body><pre>{}</pre></body></html>".format(html.escape(content))
msg.attach(MIMEText(create_signature(content.encode()).decode(), 'plain'))
msg.attach(MIMEText(content_html, 'html'))

View file

@ -16,6 +16,7 @@ from dateutil.relativedelta import relativedelta
import utils
LOG_FILES = (
'/var/log/mail.log.6.gz',
'/var/log/mail.log.5.gz',
@ -31,7 +32,8 @@ TIME_DELTAS = OrderedDict([
('month', datetime.timedelta(weeks=4)),
('2weeks', datetime.timedelta(days=14)),
('week', datetime.timedelta(days=7)),
('2days', datetime.timedelta(days=2)), ('day', datetime.timedelta(days=1)),
('2days', datetime.timedelta(days=2)),
('day', datetime.timedelta(days=1)),
('12hours', datetime.timedelta(hours=12)),
('6hours', datetime.timedelta(hours=6)),
('hour', datetime.timedelta(hours=1)),
@ -39,8 +41,7 @@ TIME_DELTAS = OrderedDict([
('10min', datetime.timedelta(minutes=10)),
('5min', datetime.timedelta(minutes=5)),
('min', datetime.timedelta(minutes=1)),
('today', datetime.datetime.now() -
datetime.datetime.now().replace(hour=0, minute=0, second=0))
('today', datetime.datetime.now() - datetime.datetime.now().replace(hour=0, minute=0, second=0))
])
END_DATE = NOW = datetime.datetime.now()
@ -87,6 +88,7 @@ def scan_files(collector):
stop_scan = False
def scan_mail_log(env):
""" Scan the system's mail log files and collect interesting data
@ -99,8 +101,7 @@ def scan_mail_log(env):
collector = {
"scan_count": 0, # Number of lines scanned
"parse_count":
0, # Number of lines parsed (i.e. that had their contents examined)
"parse_count": 0, # Number of lines parsed (i.e. that had their contents examined)
"scan_time": time.time(), # The time in seconds the scan took
"sent_mail": OrderedDict(), # Data about email sent by users
"received_mail": OrderedDict(), # Data about email received by users
@ -113,14 +114,14 @@ def scan_mail_log(env):
try:
import mailconfig
collector["known_addresses"] = (
set(mailconfig.get_mail_users(env))
| set(alias[0] for alias in mailconfig.get_mail_aliases(env)))
collector["known_addresses"] = (set(mailconfig.get_mail_users(env)) |
set(alias[0] for alias in mailconfig.get_mail_aliases(env)))
except ImportError:
pass
print("Scanning logs from {:%Y-%m-%d %H:%M:%S} to {:%Y-%m-%d %H:%M:%S}".
format(START_DATE, END_DATE))
print("Scanning logs from {:%Y-%m-%d %H:%M:%S} to {:%Y-%m-%d %H:%M:%S}".format(
START_DATE, END_DATE)
)
# Scan the lines in the log files until the date goes out of range
scan_files(collector)
@ -131,8 +132,7 @@ def scan_mail_log(env):
collector["scan_time"] = time.time() - collector["scan_time"]
print(
"{scan_count} Log lines scanned, {parse_count} lines parsed in {scan_time:.2f} "
print("{scan_count} Log lines scanned, {parse_count} lines parsed in {scan_time:.2f} "
"seconds\n".format(**collector))
# Print Sent Mail report
@ -141,8 +141,7 @@ def scan_mail_log(env):
msg = "Sent email"
print_header(msg)
data = OrderedDict(
sorted(collector["sent_mail"].items(), key=email_sort))
data = OrderedDict(sorted(collector["sent_mail"].items(), key=email_sort))
print_user_table(
data.keys(),
@ -166,7 +165,10 @@ def scan_mail_log(env):
for h in range(24):
accum[h] = sum(d["activity-by-hour"][h] for d in data)
print_time_table(["sent"], [accum])
print_time_table(
["sent"],
[accum]
)
# Print Received Mail report
@ -174,8 +176,7 @@ def scan_mail_log(env):
msg = "Received email"
print_header(msg)
data = OrderedDict(
sorted(collector["received_mail"].items(), key=email_sort))
data = OrderedDict(sorted(collector["received_mail"].items(), key=email_sort))
print_user_table(
data.keys(),
@ -193,7 +194,10 @@ def scan_mail_log(env):
for h in range(24):
accum[h] = sum(d["activity-by-hour"][h] for d in data.values())
print_time_table(["received"], [accum])
print_time_table(
["received"],
[accum]
)
# Print login report
@ -208,34 +212,27 @@ def scan_mail_log(env):
for u in data.values():
for protocol_name, count in u["totals_by_protocol"].items():
all_protocols[protocol_name] += count
all_protocols = [
k for k, v in sorted(all_protocols.items(), key=lambda kv: -kv[1])
]
all_protocols = [k for k, v in sorted(all_protocols.items(), key=lambda kv : -kv[1])]
print_user_table(
data.keys(),
data=[
(
protocol_name,
[
round(
u["totals_by_protocol"][protocol_name] /
(u["latest"] - u["earliest"]).total_seconds() *
60 * 60, 1) if
(u["latest"] - u["earliest"]).total_seconds() > 0 else
0 # prevent division by zero
for u in data.values()
]) for protocol_name in all_protocols
(protocol_name, [
round(u["totals_by_protocol"][protocol_name] / (u["latest"]-u["earliest"]).total_seconds() * 60*60, 1)
if (u["latest"]-u["earliest"]).total_seconds() > 0
else 0 # prevent division by zero
for u in data.values()])
for protocol_name in all_protocols
],
sub_data=[("Protocol and Source", [[
sub_data=[
("Protocol and Source", [[
"{} {}: {} times".format(protocol_name, host, count)
for (protocol_name, host), count in sorted(
u["totals_by_protocol_and_host"].items(),
key=lambda kv: -kv[1])
] for u in data.values()])],
for (protocol_name, host), count
in sorted(u["totals_by_protocol_and_host"].items(), key=lambda kv:-kv[1])
] for u in data.values()])
],
activity=[
(protocol_name,
[u["activity-by-hour"][protocol_name] for u in data.values()])
(protocol_name, [u["activity-by-hour"][protocol_name] for u in data.values()])
for protocol_name in all_protocols
],
earliest=[u["earliest"] for u in data.values()],
@ -243,19 +240,15 @@ def scan_mail_log(env):
numstr=lambda n : str(round(n, 1)),
)
accum = {
protocol_name: defaultdict(int)
for protocol_name in all_protocols
}
accum = { protocol_name: defaultdict(int) for protocol_name in all_protocols }
for h in range(24):
for protocol_name in all_protocols:
accum[protocol_name][h] = sum(
d["activity-by-hour"][protocol_name][h]
for d in data.values())
accum[protocol_name][h] = sum(d["activity-by-hour"][protocol_name][h] for d in data.values())
print_time_table(
all_protocols,
[accum[protocol_name] for protocol_name in all_protocols])
[accum[protocol_name] for protocol_name in all_protocols]
)
if collector["postgrey"]:
msg = "Greylisted Email {:%Y-%m-%d %H:%M:%S} and {:%Y-%m-%d %H:%M:%S}"
@ -264,13 +257,10 @@ def scan_mail_log(env):
print(textwrap.fill(
"The following mail was greylisted, meaning the emails were temporarily rejected. "
"Legitimate senders must try again after three minutes.",
width=80,
initial_indent=" ",
subsequent_indent=" "),
end='\n\n')
width=80, initial_indent=" ", subsequent_indent=" "
), end='\n\n')
data = OrderedDict(
sorted(collector["postgrey"].items(), key=email_sort))
data = OrderedDict(sorted(collector["postgrey"].items(), key=email_sort))
users = []
received = []
senders = []
@ -278,10 +268,8 @@ def scan_mail_log(env):
delivered_dates = []
for recipient in data:
sorted_recipients = sorted(data[recipient].items(),
key=lambda kv: kv[1][0] or kv[1][1])
for (client_address,
sender), (first_date, delivered_date) in sorted_recipients:
sorted_recipients = sorted(data[recipient].items(), key=lambda kv: kv[1][0] or kv[1][1])
for (client_address, sender), (first_date, delivered_date) in sorted_recipients:
if first_date:
users.append(recipient)
received.append(first_date)
@ -291,10 +279,12 @@ def scan_mail_log(env):
print_user_table(
users,
data=[("received", received), ("sender", senders),
("delivered",
[str(d) or "no retry yet" for d in delivered_dates]),
("sending host", sender_clients)],
data=[
("received", received),
("sender", senders),
("delivered", [str(d) or "no retry yet" for d in delivered_dates]),
("sending host", sender_clients)
],
delimit=True,
)
@ -302,8 +292,7 @@ def scan_mail_log(env):
msg = "Blocked Email {:%Y-%m-%d %H:%M:%S} and {:%Y-%m-%d %H:%M:%S}"
print_header(msg.format(START_DATE, END_DATE))
data = OrderedDict(
sorted(collector["rejected"].items(), key=email_sort))
data = OrderedDict(sorted(collector["rejected"].items(), key=email_sort))
rejects = []
@ -338,8 +327,7 @@ def scan_mail_log(env):
def scan_mail_log_line(line, collector):
""" Scan a log line and extract interesting data """
m = re.match(r"(\w+[\s]+\d+ \d+:\d+:\d+) ([\w]+ )?([\w\-/]+)[^:]*: (.*)",
line)
m = re.match(r"(\w+[\s]+\d+ \d+:\d+:\d+) ([\w]+ )?([\w\-/]+)[^:]*: (.*)", line)
if not m:
return True
@ -358,8 +346,7 @@ def scan_mail_log_line(line, collector):
# strptime fails on Feb 29 with ValueError: day is out of range for month if correct year is not provided.
# See https://bugs.python.org/issue26460
date = datetime.datetime.strptime(
str(NOW.year) + ' ' + date, '%Y %b %d %H:%M:%S')
date = datetime.datetime.strptime(str(NOW.year) + ' ' + date, '%Y %b %d %H:%M:%S')
# if log date in future, step back a year
if date > NOW:
date = date.replace(year = NOW.year - 1)
@ -388,9 +375,8 @@ def scan_mail_log_line(line, collector):
elif service == "postfix/smtpd":
if SCAN_BLOCKED:
scan_postfix_smtpd_line(date, log, collector)
elif service in ("postfix/qmgr", "postfix/pickup", "postfix/cleanup",
"postfix/scache", "spampd", "postfix/anvil",
"postfix/master", "opendkim", "postfix/lmtp",
elif service in ("postfix/qmgr", "postfix/pickup", "postfix/cleanup", "postfix/scache",
"spampd", "postfix/anvil", "postfix/master", "opendkim", "postfix/lmtp",
"postfix/tlsmgr", "anvil"):
# nothing to look at
return True
@ -405,9 +391,9 @@ def scan_mail_log_line(line, collector):
def scan_postgrey_line(date, log, collector):
""" Scan a postgrey log line and extract interesting data """
m = re.match(
"action=(greylist|pass), reason=(.*?), (?:delay=\d+, )?client_name=(.*), "
"client_address=(.*), sender=(.*), recipient=(.*)", log)
m = re.match("action=(greylist|pass), reason=(.*?), (?:delay=\d+, )?client_name=(.*), "
"client_address=(.*), sender=(.*), recipient=(.*)",
log)
if m:
@ -423,8 +409,7 @@ def scan_postgrey_line(date, log, collector):
# if len(addr) > 2:
# client_name = '.'.join(addr[1:])
key = (client_address if client_name == 'unknown' else client_name,
sender)
key = (client_address if client_name == 'unknown' else client_name, sender)
rep = collector["postgrey"].setdefault(user, {})
@ -439,8 +424,7 @@ def scan_postfix_smtpd_line(date, log, collector):
# Check if the incoming mail was rejected
m = re.match(
"NOQUEUE: reject: RCPT from .*?: (.*?); from=<(.*?)> to=<(.*?)>", log)
m = re.match("NOQUEUE: reject: RCPT from .*?: (.*?); from=<(.*?)> to=<(.*?)>", log)
if m:
message, sender, user = m.groups()
@ -451,24 +435,26 @@ def scan_postfix_smtpd_line(date, log, collector):
# only log mail to known recipients
if user_match(user):
if collector["known_addresses"] is None or user in collector[
"known_addresses"]:
data = collector["rejected"].get(user, {
if collector["known_addresses"] is None or user in collector["known_addresses"]:
data = collector["rejected"].get(
user,
{
"blocked": [],
"earliest": None,
"latest": None,
})
}
)
# simplify this one
m = re.search(
r"Client host \[(.*?)\] blocked using zen.spamhaus.org; (.*)",
message)
r"Client host \[(.*?)\] blocked using zen.spamhaus.org; (.*)", message
)
if m:
message = "ip blocked: " + m.group(2)
else:
# simplify this one too
m = re.search(
r"Sender address \[.*@(.*)\] blocked using dbl.spamhaus.org; (.*)",
message)
r"Sender address \[.*@(.*)\] blocked using dbl.spamhaus.org; (.*)", message
)
if m:
message = "domain blocked: " + m.group(2)
@ -496,13 +482,15 @@ def scan_dovecot_login_line(date, log, collector, protocol_name):
def add_login(user, date, protocol_name, host, collector):
# Get the user data, or create it if the user is new
data = collector["logins"].get(
user, {
user,
{
"earliest": None,
"latest": None,
"totals_by_protocol": defaultdict(int),
"totals_by_protocol_and_host": defaultdict(int),
"activity-by-hour": defaultdict(lambda : defaultdict(int)),
})
}
)
if data["earliest"] is None:
data["earliest"] = date
@ -533,12 +521,14 @@ def scan_postfix_lmtp_line(date, log, collector):
if user_match(user):
# Get the user data, or create it if the user is new
data = collector["received_mail"].get(
user, {
user,
{
"received_count": 0,
"earliest": None,
"latest": None,
"activity-by-hour": defaultdict(int),
})
}
)
data["received_count"] += 1
data["activity-by-hour"][date.hour] += 1
@ -559,11 +549,8 @@ def scan_postfix_submission_line(date, log, collector):
"""
# Match both the 'plain' and 'login' sasl methods, since both authentication methods are
# allowed by Dovecot. Exclude trailing comma after the username when additional fields
# follow after.
m = re.match(
"([A-Z0-9]+): client=(\S+), sasl_method=(PLAIN|LOGIN), sasl_username=(\S+)(?<!,)",
log)
# allowed by Dovecot
m = re.match("([A-Z0-9]+): client=(\S+), sasl_method=(PLAIN|LOGIN), sasl_username=(\S+)", log)
if m:
_, client, method, user = m.groups()
@ -571,13 +558,15 @@ def scan_postfix_submission_line(date, log, collector):
if user_match(user):
# Get the user data, or create it if the user is new
data = collector["sent_mail"].get(
user, {
user,
{
"sent_count": 0,
"hosts": set(),
"earliest": None,
"latest": None,
"activity-by-hour": defaultdict(int),
})
}
)
data["sent_count"] += 1
data["hosts"].add(client)
@ -592,10 +581,8 @@ def scan_postfix_submission_line(date, log, collector):
# Also log this as a login.
add_login(user, date, "smtp", client, collector)
# Utility functions
def readline(filename):
""" A generator that returns the lines of a file
"""
@ -622,14 +609,12 @@ def valid_date(string):
try:
date = dateutil.parser.parse(string)
except ValueError:
raise argparse.ArgumentTypeError("Unrecognized date and/or time '%s'" %
string)
raise argparse.ArgumentTypeError("Unrecognized date and/or time '%s'" % string)
return date
# Print functions
def print_time_table(labels, data, do_print=True):
labels.insert(0, "hour")
data.insert(0, [str(h) for h in range(24)])
@ -656,14 +641,8 @@ def print_time_table(labels, data, do_print=True):
return lines
def print_user_table(users,
data=None,
sub_data=None,
activity=None,
latest=None,
earliest=None,
delimit=False,
numstr=str):
def print_user_table(users, data=None, sub_data=None, activity=None, latest=None, earliest=None,
delimit=False, numstr=str):
str_temp = "{:<32} "
lines = []
data = data or []
@ -688,8 +667,7 @@ def print_user_table(users,
for col, (l, d) in enumerate(data):
if isinstance(d[row], str):
col_str = str_temp.format(d[row][:31] +
"" if len(d[row]) > 32 else d[row])
col_str = str_temp.format(d[row][:31] + "" if len(d[row]) > 32 else d[row])
col_left[col] = True
elif isinstance(d[row], datetime.datetime):
col_str = "{:<20}".format(str(d[row]))
@ -743,10 +721,11 @@ def print_user_table(users,
lines.append("" + (max_len + 1) * "")
if activity is not None:
lines.extend(
print_time_table([label for label, _ in activity],
lines.extend(print_time_table(
[label for label, _ in activity],
[data[row] for _, data in activity],
do_print=False))
do_print=False
))
except KeyError:
pass
@ -770,8 +749,7 @@ def print_user_table(users,
if vert_pos:
t_line = t_line[:vert_pos + 1] + "" + t_line[vert_pos + 2:]
b_line = b_line[:vert_pos +
1] + ("" if VERBOSE else "") + b_line[vert_pos + 2:]
b_line = b_line[:vert_pos + 1] + ("" if VERBOSE else "") + b_line[vert_pos + 2:]
lines.insert(1, t_line)
lines.append(b_line)
@ -819,72 +797,43 @@ if __name__ == "__main__":
env_vars = {}
parser = argparse.ArgumentParser(
description=
"Scan the mail log files for interesting data. By default, this script "
description="Scan the mail log files for interesting data. By default, this script "
"shows today's incoming and outgoing mail statistics. This script was ("
"re)written for the Mail-in-a-box email server."
"https://github.com/mail-in-a-box/mailinabox",
add_help=False)
add_help=False
)
# Switches to determine what to parse and what to ignore
parser.add_argument("-r",
"--received",
help="Scan for received emails.",
parser.add_argument("-r", "--received", help="Scan for received emails.",
action="store_true")
parser.add_argument("-s",
"--sent",
help="Scan for sent emails.",
parser.add_argument("-s", "--sent", help="Scan for sent emails.",
action="store_true")
parser.add_argument("-l",
"--logins",
help="Scan for user logins to IMAP/POP3.",
parser.add_argument("-l", "--logins", help="Scan for user logins to IMAP/POP3.",
action="store_true")
parser.add_argument("-g",
"--grey",
help="Scan for greylisted emails.",
parser.add_argument("-g", "--grey", help="Scan for greylisted emails.",
action="store_true")
parser.add_argument("-b",
"--blocked",
help="Scan for blocked emails.",
parser.add_argument("-b", "--blocked", help="Scan for blocked emails.",
action="store_true")
parser.add_argument(
"-t",
"--timespan",
choices=TIME_DELTAS.keys(),
default='today',
parser.add_argument("-t", "--timespan", choices=TIME_DELTAS.keys(), default='today',
metavar='<time span>',
help="Time span to scan, going back from the end date. Possible values: "
"{}. Defaults to 'today'.".format(", ".join(list(TIME_DELTAS.keys()))))
# keep the --startdate arg for backward compatibility
parser.add_argument(
"-d",
"--enddate",
"--startdate",
action="store",
dest="enddate",
type=valid_date,
metavar='<end date>',
parser.add_argument("-d", "--enddate", "--startdate", action="store", dest="enddate",
type=valid_date, metavar='<end date>',
help="Date and time to end scanning the log file. If no date is "
"provided, scanning will end at the current date and time. "
"Alias --startdate is for compatibility.")
parser.add_argument(
"-u",
"--users",
action="store",
dest="users",
parser.add_argument("-u", "--users", action="store", dest="users",
metavar='<email1,email2,email...>',
help="Comma separated list of (partial) email addresses to filter the "
"output with.")
parser.add_argument('-h',
'--help',
action='help',
help="Print this message and exit.")
parser.add_argument("-v",
"--verbose",
help="Output extra data where available.",
parser.add_argument('-h', '--help', action='help', help="Print this message and exit.")
parser.add_argument("-v", "--verbose", help="Output extra data where available.",
action="store_true")
args = parser.parse_args()

View file

@ -9,16 +9,11 @@
# Python 3 in setup/questions.sh to validate the email
# address entered by the user.
import subprocess
import shutil
import os
import sqlite3
import re
import subprocess, shutil, os, sqlite3, re
import utils
from email_validator import validate_email as validate_email_, EmailNotValidError
import idna
def validate_email(email, mode=None):
# Checks that an email address is syntactically valid. Returns True/False.
# An email address may contain ASCII characters only because Dovecot's
@ -36,7 +31,8 @@ def validate_email(email, mode=None):
validate_email_(email,
allow_smtputf8=False,
check_deliverability=False,
allow_empty_local=(mode == "alias"))
allow_empty_local=(mode=="alias")
)
except EmailNotValidError:
return False
@ -49,15 +45,13 @@ def validate_email(email, mode=None):
# Our database is case sensitive (oops), which affects mail delivery
# (Postfix always queries in lowercase?), so also only permit lowercase
# letters.
if len(email) > 255:
return False
if len(email) > 255: return False
if re.search(r'[^\@\.a-z0-9_\-]+', email):
return False
# Everything looks good.
return True
def sanitize_idn_email_address(email):
# The user may enter Unicode in an email address. Convert the domain part
# to IDNA before going into our database. Leave the local part alone ---
@ -78,7 +72,6 @@ def sanitize_idn_email_address(email):
# validate_email.
return email
def prettify_idn_email_address(email):
# This is the opposite of sanitize_idn_email_address. We store domain
# names in IDNA in the database, but we want to show Unicode to the user.
@ -91,17 +84,13 @@ def prettify_idn_email_address(email):
# single @-sign. Should never happen.
return email
def is_dcv_address(email):
email = email.lower()
for localpart in ("admin", "administrator", "postmaster", "hostmaster",
"webmaster", "abuse"):
if email.startswith(localpart + "@") or email.startswith(localpart +
"+"):
for localpart in ("admin", "administrator", "postmaster", "hostmaster", "webmaster", "abuse"):
if email.startswith(localpart+"@") or email.startswith(localpart+"+"):
return True
return False
def open_database(env, with_connection=False):
conn = sqlite3.connect(env["STORAGE_ROOT"] + "/mail/users.sqlite")
if not with_connection:
@ -109,7 +98,6 @@ def open_database(env, with_connection=False):
else:
return conn, conn.cursor()
def get_mail_users(env):
# Returns a flat, sorted list of all user accounts.
c = open_database(env)
@ -117,7 +105,6 @@ def get_mail_users(env):
users = [ row[0] for row in c.fetchall() ]
return utils.sort_email_addresses(users, env)
def sizeof_fmt(num):
for unit in ['','K','M','G','T']:
if abs(num) < 1024.0:
@ -130,7 +117,6 @@ def sizeof_fmt(num):
return str(num)
def get_mail_users_ex(env, with_archived=False):
# Returns a complex data structure of all user accounts, optionally
# including archived (status="inactive") accounts.
@ -164,9 +150,7 @@ def get_mail_users_ex(env, with_archived=False):
box_quota = 0
percent = ''
try:
dirsize_file = os.path.join(
env['STORAGE_ROOT'],
'mail/mailboxes/%s/%s/maildirsize' % (domain, user))
dirsize_file = os.path.join(env['STORAGE_ROOT'], 'mail/mailboxes/%s/%s/maildirsize' % (domain, user))
with open(dirsize_file, 'r') as f:
box_quota = int(f.readline().split('S')[0])
for line in f.readlines():
@ -194,8 +178,7 @@ def get_mail_users_ex(env, with_archived=False):
"quota": quota,
"box_quota": box_quota,
"box_size": sizeof_fmt(box_size) if box_size != '?' else box_size,
"percent":
'%3.0f%%' % percent if type(percent) != str else percent,
"percent": '%3.0f%%' % percent if type(percent) != str else percent,
"box_count": box_count,
"status": "active",
}
@ -209,8 +192,7 @@ def get_mail_users_ex(env, with_archived=False):
for user in os.listdir(os.path.join(root, domain)):
email = user + "@" + domain
mbox = os.path.join(root, domain, user)
if email in active_accounts:
continue
if email in active_accounts: continue
user = {
"email": email,
"privileges": [],
@ -228,22 +210,21 @@ def get_mail_users_ex(env, with_archived=False):
for user in users:
domain = get_domain(user["email"])
if domain not in domains:
domains[domain] = {"domain": domain, "users": []}
domains[domain] = {
"domain": domain,
"users": []
}
domains[domain]["users"].append(user)
# Sort domains.
domains = [
domains[domain] for domain in utils.sort_domains(domains.keys(), env)
]
domains = [domains[domain] for domain in utils.sort_domains(domains.keys(), env)]
# Sort users within each domain first by status then lexicographically by email address.
for domain in domains:
domain["users"].sort(
key=lambda user: (user["status"] != "active", user["email"]))
domain["users"].sort(key = lambda user : (user["status"] != "active", user["email"]))
return domains
def get_admins(env):
# Returns a set of users with admin privileges.
users = set()
@ -253,23 +234,16 @@ def get_admins(env):
users.add(user["email"])
return users
def get_mail_aliases(env):
# Returns a sorted list of tuples of (address, forward-tos, permitted-senders, auto).
c = open_database(env)
c.execute(
'SELECT source, destination, permitted_senders, 0 as auto FROM aliases UNION SELECT source, destination, permitted_senders, 1 as auto FROM auto_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
aliases = [
aliases[address]
for address in utils.sort_email_addresses(aliases.keys(), env)
]
aliases = [ aliases[address] for address in utils.sort_email_addresses(aliases.keys(), env) ]
return aliases
def get_mail_aliases_ex(env):
# Returns a complex data structure of all mail aliases, similar
# to get_mail_users_ex.
@ -294,8 +268,7 @@ def get_mail_aliases_ex(env):
domains = {}
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
if auto and address.startswith("@"): continue
# get alias info
domain = get_domain(address)
@ -307,34 +280,21 @@ def get_mail_aliases_ex(env):
"aliases": [],
}
domains[domain]["aliases"].append({
"address":
address,
"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,
"auto":
bool(auto),
"address": address,
"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,
"auto": bool(auto),
})
# Sort domains.
domains = [
domains[domain] for domain in utils.sort_domains(domains.keys(), env)
]
domains = [domains[domain] for domain in utils.sort_domains(domains.keys(), 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["auto"], alias["address"]))
domain["aliases"].sort(key = lambda alias : (alias["auto"], alias["address"]))
return domains
def get_noreply_addresses(env):
# Returns a set of noreply addresses:
# Noreply addresses are a special type of addresses that are send-only.
@ -343,7 +303,6 @@ def get_noreply_addresses(env):
c.execute('SELECT email FROM noreply')
return set( row[0] for row in c.fetchall() )
def get_domain(emailaddr, as_unicode=True):
# Gets the domain part of an email address. Turns IDNA
# back to Unicode for display.
@ -357,7 +316,6 @@ def get_domain(emailaddr, as_unicode=True):
pass
return ret
def get_all_mail_addresses(env, no_catchalls=True):
# Gets the email addresses on literally all tables (users, aliases and noreplies)
emails = get_mail_users(env)
@ -370,28 +328,18 @@ def get_all_mail_addresses(env, no_catchalls=True):
return set(emails)
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. 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)])
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, _, _, auto in get_mail_aliases(env)
if filter_aliases(address) and not auto
])
domains.extend([
get_domain(address, as_unicode=False)
for address in get_noreply_addresses(env)
])
domains.extend([get_domain(address, as_unicode=False) for address, _, _, auto in get_mail_aliases(env) if filter_aliases(address) and not auto ])
domains.extend([get_domain(address, as_unicode=False) for address in get_noreply_addresses(env)])
return set(domains)
def add_mail_user(email, pw, privs, quota, env):
# validate email
if email.strip() == "":
@ -399,16 +347,12 @@ def add_mail_user(email, pw, privs, quota, env):
elif not validate_email(email):
return ("Invalid email address.", 400)
elif not validate_email(email, mode='user'):
return (
"User account email addresses may only use the lowercase ASCII letters a-z, the digits 0-9, underscore (_), hyphen (-), and period (.).",
400)
return ("User account email addresses may only use the lowercase ASCII letters a-z, the digits 0-9, underscore (_), hyphen (-), and period (.).", 400)
elif is_dcv_address(email) and len(get_mail_users(env)) > 0:
# Make domain control validation hijacking a little harder to mess up by preventing the usual
# addresses used for DCV from being user accounts. Except let it be the first account because
# during box setup the user won't know the rules.
return (
"You may not make a user account for that address because it is frequently used for domain control validation. Use an alias instead if necessary.",
400)
return ("You may not make a user account for that address because it is frequently used for domain control validation. Use an alias instead if necessary.", 400)
# validate password
validate_password(pw)
@ -420,8 +364,7 @@ def add_mail_user(email, pw, privs, quota, env):
privs = privs.split("\n")
for p in privs:
validation = validate_privilege(p)
if validation:
return validation
if validation: return validation
if quota is None:
quota = get_default_quota()
@ -439,8 +382,7 @@ def add_mail_user(email, pw, privs, quota, env):
# add the user to the database
try:
c.execute(
"INSERT INTO users (email, password, privileges, quota) VALUES (?, ?, ?, ?)",
c.execute("INSERT INTO users (email, password, privileges, quota) VALUES (?, ?, ?, ?)",
(email, pw, "\n".join(privs), quota))
except sqlite3.IntegrityError:
return ("User already exists.", 400)
@ -453,7 +395,6 @@ def add_mail_user(email, pw, privs, quota, env):
# Update things in case any new domains are added.
return kick(env, "mail user added")
def set_mail_password(email, pw, env):
# validate that password is acceptable
validate_password(pw)
@ -469,14 +410,11 @@ def set_mail_password(email, pw, env):
conn.commit()
return "OK"
def hash_password(pw):
# Turn the plain password into a Dovecot-format hashed password, meaning
# something like "{SCHEME}hashedpassworddata".
# http://wiki2.dovecot.org/Authentication/PasswordSchemes
return utils.shell(
'check_output',
["/usr/bin/doveadm", "pw", "-s", "SHA512-CRYPT", "-p", pw]).strip()
return utils.shell('check_output', ["/usr/bin/doveadm", "pw", "-s", "SHA512-CRYPT", "-p", pw]).strip()
def get_mail_quota(email, env):
@ -504,7 +442,6 @@ def set_mail_quota(email, quota, env):
return "OK"
def dovecot_quota_recalc(email):
# dovecot processes running for the user will not recognize the new quota setting
# a reload is necessary to reread the quota setting, but it will also shut down
@ -515,12 +452,10 @@ def dovecot_quota_recalc(email):
# force dovecot to recalculate the quota info for the user.
subprocess.call(["doveadm", "quota", "recalc", "-u", email])
def get_default_quota(env):
config = utils.load_settings(env)
return config.get("default-quota", '0')
def validate_quota(quota):
# validate quota
quota = quota.strip().upper()
@ -528,14 +463,12 @@ def validate_quota(quota):
if quota == "":
raise ValueError("No quota provided.")
if re.search(r"[\s,.]", quota):
raise ValueError(
"Quotas cannot contain spaces, commas, or decimal points.")
raise ValueError("Quotas cannot contain spaces, commas, or decimal points.")
if not re.match(r'^[\d]+[GM]?$', quota):
raise ValueError("Invalid quota.")
return quota
def get_mail_password(email, env):
# Gets the hashed password for a user. Passwords are stored in Dovecot's
# password format, with a prefixed scheme.
@ -548,7 +481,6 @@ def get_mail_password(email, env):
raise ValueError("That's not a user (%s)." % email)
return rows[0][0]
def remove_mail_user(email, env):
# remove
conn, c = open_database(env, with_connection=True)
@ -560,39 +492,32 @@ def remove_mail_user(email, env):
# Update things in case any domains are removed.
return kick(env, "mail user removed")
def parse_privs(value):
return [p for p in value.split("\n") if p.strip() != ""]
def get_mail_user_privileges(email, env, empty_on_error=False):
# get privs
c = open_database(env)
c.execute('SELECT privileges FROM users WHERE email=?', (email,))
rows = c.fetchall()
if len(rows) != 1:
if empty_on_error:
return []
if empty_on_error: return []
return ("That's not a user (%s)." % email, 400)
return parse_privs(rows[0][0])
def validate_privilege(priv):
if "\n" in priv or priv.strip() == "":
return ("That's not a valid privilege (%s)." % priv, 400)
return None
def add_remove_mail_user_privilege(email, priv, action, env):
# validate
validation = validate_privilege(priv)
if validation:
return validation
if validation: return validation
# get existing privs, but may fail
privs = get_mail_user_privileges(email, env)
if isinstance(privs, tuple):
return privs # error
if isinstance(privs, tuple): return privs # error
# update privs set
if action == "add":
@ -605,21 +530,14 @@ def add_remove_mail_user_privilege(email, priv, action, env):
# commit to database
conn, c = open_database(env, with_connection=True)
c.execute("UPDATE users SET privileges=? WHERE email=?",
("\n".join(privs), email))
c.execute("UPDATE users SET privileges=? WHERE email=?", ("\n".join(privs), email))
if c.rowcount != 1:
return ("Something went wrong.", 400)
conn.commit()
return "OK"
def add_mail_alias(address,
forwards_to,
permitted_senders,
env,
update_if_exists=False,
do_kick=True):
def add_mail_alias(address, forwards_to, permitted_senders, env, update_if_exists=False, do_kick=True):
# convert Unicode domain to IDNA
address = sanitize_idn_email_address(address)
@ -656,23 +574,17 @@ def add_mail_alias(address,
for line in forwards_to.split("\n"):
for email in line.split(","):
email = email.strip()
if email == "":
continue
if email == "": continue
email = sanitize_idn_email_address(email) # Unicode => IDNA
# Strip any +tag from email alias and check privileges
privileged_email = re.sub(r"(?=\+)[^@]*(?=@)",'',email)
if not validate_email(email):
return ("Invalid receiver email address (%s)." % email,
400)
if is_dcv_source and not is_dcv_address(
email) and "admin" not in get_mail_user_privileges(
privileged_email, env, empty_on_error=True):
return ("Invalid receiver email address (%s)." % email, 400)
if is_dcv_source and not is_dcv_address(email) and "admin" not in get_mail_user_privileges(privileged_email, env, empty_on_error=True):
# Make domain control validation hijacking a little harder to mess up by
# requiring aliases for email addresses typically used in DCV to forward
# only to accounts that are administrators on this system.
return (
"This alias can only have administrators of this system as destinations because the address is frequently used for domain control validation.",
400)
return ("This alias can only have administrators of this system as destinations because the address is frequently used for domain control validation.", 400)
validated_forwards_to.append(email)
# validate permitted_senders
@ -685,19 +597,14 @@ def add_mail_alias(address,
for line in permitted_senders.split("\n"):
for login in line.split(","):
login = login.strip()
if login == "":
continue
if login == "": continue
if login not in valid_logins:
return (
"Invalid permitted sender: %s is not a user on this system."
% login, 400)
return ("Invalid permitted sender: %s is not a user on this system." % login, 400)
validated_permitted_senders.append(login)
# Make sure the alias has either a forwards_to or a permitted_sender.
if len(validated_forwards_to) + len(validated_permitted_senders) == 0:
return (
"The alias must either forward to an address or have a permitted sender.",
400)
return ("The alias must either forward to an address or have a permitted sender.", 400)
# save to db
@ -710,17 +617,13 @@ def add_mail_alias(address,
conn, c = open_database(env, with_connection=True)
try:
c.execute(
"INSERT INTO aliases (source, destination, permitted_senders) VALUES (?, ?, ?)",
(address, forwards_to, permitted_senders))
c.execute("INSERT INTO aliases (source, destination, permitted_senders) VALUES (?, ?, ?)", (address, forwards_to, permitted_senders))
return_status = "alias added"
except sqlite3.IntegrityError:
if not update_if_exists:
return ("Alias already exists (%s)." % address, 400)
else:
c.execute(
"UPDATE aliases SET destination = ?, permitted_senders = ? WHERE source = ?",
(forwards_to, permitted_senders, address))
c.execute("UPDATE aliases SET destination = ?, permitted_senders = ? WHERE source = ?", (forwards_to, permitted_senders, address))
return_status = "alias updated"
conn.commit()
@ -729,7 +632,6 @@ def add_mail_alias(address,
# Update things in case any new domains are added.
return kick(env, return_status)
def remove_mail_alias(address, env, do_kick=True):
# convert Unicode domain to IDNA
address = sanitize_idn_email_address(address)
@ -745,21 +647,16 @@ 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")
c.execute("DELETE FROM auto_aliases");
for source, destination in aliases.items():
c.execute(
"INSERT INTO auto_aliases (source, destination) VALUES (?, ?)",
(source, destination))
c.execute("INSERT INTO auto_aliases (source, destination) VALUES (?, ?)", (source, destination))
conn.commit()
def get_system_administrator(env):
return "administrator@" + env['PRIMARY_HOSTNAME']
def get_required_aliases(env):
# These are the aliases that must exist.
aliases = set()
@ -772,11 +669,13 @@ def get_required_aliases(env):
# Get a list of domains we serve mail for, except ones for which the only
# email on that domain are the required aliases or a catch-all/domain-forwarder.
real_mail_domains = get_mail_domains(
env,
filter_aliases=lambda alias: not alias.startswith("postmaster@") and
not alias.startswith("admin@") and not alias.startswith(
"abuse@") and not alias.startswith("@"))
real_mail_domains = get_mail_domains(env,
filter_aliases = lambda alias :
not alias.startswith("postmaster@")
and not alias.startswith("admin@")
and not alias.startswith("abuse@")
and not alias.startswith("@")
)
# Create postmaster@, admin@ and abuse@ for all domains we serve
# mail on. postmaster@ is assumed to exist by our Postfix configuration.
@ -790,7 +689,6 @@ def get_required_aliases(env):
return aliases
def add_noreply_address(env, address, do_kick=True):
email = sanitize_idn_email_address(address)
# validate email
@ -821,7 +719,6 @@ def add_noreply_address(env, address, do_kick=True):
conn.commit()
return ret
def remove_noreply_address(env, address, do_kick=True):
email = sanitize_idn_email_address(address)
@ -836,11 +733,9 @@ def remove_noreply_address(env, address, do_kick=True):
# Update things in case any domains are removed.
return kick(env, "No-reply address removed")
def get_required_noreply_addresses(env):
return { "noreply-daemon@" + env['PRIMARY_HOSTNAME'] }
def kick(env, mail_result=None):
results = []
@ -857,16 +752,14 @@ def kick(env, mail_result=None):
required_noreply = get_required_noreply_addresses(env)
existing_noreply = get_noreply_addresses(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
if alias == administrator: continue # don't make an alias from the administrator to itself --- this alias must be created manually
auto_aliases[alias] = administrator
# 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
if domain == domain_unicode: continue # not an IDNA/Unicode domain
auto_aliases["@" + domain_unicode] = "@" + domain
except (ValueError, UnicodeError, idna.IDNAError):
continue
@ -885,9 +778,7 @@ def kick(env, mail_result=None):
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))
results.append("removed alias %s (was to %s; domain no longer used for email)\n" % (address, forwards_to))
# Update DNS and nginx in case any domains are added/removed.
@ -899,7 +790,6 @@ def kick(env, mail_result=None):
return "".join(s for s in results if s != "")
def validate_password(pw):
# validate password
if pw.strip() == "":
@ -907,7 +797,6 @@ def validate_password(pw):
if len(pw) < 8:
raise ValueError("Passwords must be at least eight characters.")
if __name__ == "__main__":
import sys
if len(sys.argv) > 2 and sys.argv[1] == "validate-email":

View file

@ -7,46 +7,33 @@ import qrcode
from mailconfig import open_database
def get_user_id(email, c):
c.execute('SELECT id FROM users WHERE email=?', (email,))
r = c.fetchone()
if not r:
raise ValueError("User does not exist.")
if not r: raise ValueError("User does not exist.")
return r[0]
def get_mfa_state(email, env):
c = open_database(env)
c.execute(
'SELECT id, type, secret, mru_token, label FROM mfa WHERE user_id=?',
(get_user_id(email, c), ))
return [{
"id": r[0],
"type": r[1],
"secret": r[2],
"mru_token": r[3],
"label": r[4]
} for r in c.fetchall()]
c.execute('SELECT id, type, secret, mru_token, label FROM mfa WHERE user_id=?', (get_user_id(email, c),))
return [
{ "id": r[0], "type": r[1], "secret": r[2], "mru_token": r[3], "label": r[4] }
for r in c.fetchall()
]
def get_public_mfa_state(email, env):
mfa_state = get_mfa_state(email, env)
return [{
"id": s["id"],
"type": s["type"],
"label": s["label"]
} for s in mfa_state]
return [
{ "id": s["id"], "type": s["type"], "label": s["label"] }
for s in mfa_state
]
def get_hash_mfa_state(email, env):
mfa_state = get_mfa_state(email, env)
return [{
"id": s["id"],
"type": s["type"],
"secret": s["secret"]
} for s in mfa_state]
return [
{ "id": s["id"], "type": s["type"], "secret": s["secret"] }
for s in mfa_state
]
def enable_mfa(email, type, secret, token, label, env):
if type == "totp":
@ -59,19 +46,14 @@ def enable_mfa(email, type, secret, token, label, env):
raise ValueError("Invalid MFA type.")
conn, c = open_database(env, with_connection=True)
c.execute(
'INSERT INTO mfa (user_id, type, secret, label) VALUES (?, ?, ?, ?)',
(get_user_id(email, c), type, secret, label))
c.execute('INSERT INTO mfa (user_id, type, secret, label) VALUES (?, ?, ?, ?)', (get_user_id(email, c), type, secret, label))
conn.commit()
def set_mru_token(email, mfa_id, token, env):
conn, c = open_database(env, with_connection=True)
c.execute('UPDATE mfa SET mru_token=? WHERE user_id=? AND id=?',
(token, get_user_id(email, c), mfa_id))
c.execute('UPDATE mfa SET mru_token=? WHERE user_id=? AND id=?', (token, get_user_id(email, c), mfa_id))
conn.commit()
def disable_mfa(email, mfa_id, env):
conn, c = open_database(env, with_connection=True)
if mfa_id is None:
@ -79,19 +61,16 @@ def disable_mfa(email, mfa_id, env):
c.execute('DELETE FROM mfa WHERE user_id=?', (get_user_id(email, c),))
else:
# Disable a particular MFA mode for a user.
c.execute('DELETE FROM mfa WHERE user_id=? AND id=?',
(get_user_id(email, c), mfa_id))
c.execute('DELETE FROM mfa WHERE user_id=? AND id=?', (get_user_id(email, c), mfa_id))
conn.commit()
return c.rowcount > 0
def validate_totp_secret(secret):
if type(secret) != str or secret.strip() == "":
raise ValueError("No secret provided.")
if len(secret) != 32:
raise ValueError("Secret should be a 32 characters base32 string")
def provision_totp(email, env):
# Make a new secret.
secret = base64.b32encode(os.urandom(20)).decode('utf-8')
@ -100,7 +79,8 @@ def provision_totp(email, env):
# Make a URI that we encode within a QR code.
uri = pyotp.TOTP(secret).provisioning_uri(
name=email,
issuer_name=env["PRIMARY_HOSTNAME"] + " Mail-in-a-Box Control Panel")
issuer_name=env["PRIMARY_HOSTNAME"] + " Mail-in-a-Box Control Panel"
)
# Generate a QR code as a base64-encode PNG image.
qr = qrcode.make(uri)
@ -108,8 +88,11 @@ def provision_totp(email, env):
qr.save(byte_arr, format='PNG')
png_b64 = base64.b64encode(byte_arr.getvalue()).decode('utf-8')
return {"type": "totp", "secret": secret, "qr_code_base64": png_b64}
return {
"type": "totp",
"secret": secret,
"qr_code_base64": png_b64
}
def validate_auth_mfa(email, request, env):
# Validates that a login request satisfies any MFA modes

View file

@ -1,11 +1,7 @@
#!/usr/local/lib/mailinabox/env/bin/python
# Tools to manipulate PGP keys
import gpg
import utils
import datetime
import shutil
import tempfile
import gpg, utils, datetime, shutil, tempfile
env = utils.load_environment()
@ -15,8 +11,6 @@ daemon_key_fpr = env['PGPKEY']
default_context = gpg.Context(armor=True, home_dir=gpghome)
# Auxiliary function to process the key in order to be read more conveniently
def key_representation(key):
if key is None:
return None
@ -30,42 +24,25 @@ def key_representation(key):
now = datetime.datetime.utcnow()
key_rep["ids"] = [ id.uid for id in key.uids ]
# No duplicate email addresses in this list
key_rep["ids_emails"] = list({id.email for id in key.uids})
key_rep["ids_emails"] = list({ id.email for id in key.uids }) # No duplicate email addresses in this list
key_rep["subkeys"] = [{
"master":
skey.fpr == key.fpr,
"sign":
skey.can_sign == 1,
"cert":
skey.can_certify == 1,
"encr":
skey.can_encrypt == 1,
"auth":
skey.can_authenticate == 1,
"fpr":
skey.fpr,
"expires":
skey.expires if skey.expires != 0 else None,
"expires_date":
datetime.datetime.utcfromtimestamp(skey.expires).date().isoformat()
if skey.expires != 0 else None,
"expires_days": (datetime.datetime.utcfromtimestamp(skey.expires) -
now).days if skey.expires != 0 else None,
"expired":
skey.expired == 1,
"algorithm":
gpg.core.pubkey_algo_name(skey.pubkey_algo),
"bits":
skey.length
"master": skey.fpr == key.fpr,
"sign": skey.can_sign == 1,
"cert": skey.can_certify == 1,
"encr": skey.can_encrypt == 1,
"auth": skey.can_authenticate == 1,
"fpr": skey.fpr,
"expires": skey.expires if skey.expires != 0 else None,
"expires_date": datetime.datetime.utcfromtimestamp(skey.expires).date().isoformat() if skey.expires != 0 else None,
"expires_days": (datetime.datetime.utcfromtimestamp(skey.expires) - now).days if skey.expires != 0 else None,
"expired": skey.expired == 1,
"algorithm": gpg.core.pubkey_algo_name(skey.pubkey_algo),
"bits": skey.length
} for skey in key.subkeys ]
return key_rep
# Tests an import as for whether we have any sort of private key material in our import
def contains_private_keys(imports):
with tempfile.TemporaryDirectory() as tmpdir:
with gpg.Context(home_dir=tmpdir, armor=True) as tmp:
@ -75,13 +52,9 @@ def contains_private_keys(imports):
except AttributeError:
raise ValueError("Import is not a valid PGP key block!")
# Decorator: Copies the homedir of a context onto a temporary directory and returns a context operating over that tmpdir
def fork_context(f, context = default_context):
from os.path import isdir, isfile
def dirs_files_only(current_dir, files):
ignore = []
for f in files:
@ -92,11 +65,8 @@ def fork_context(f, context=default_context):
def wrapped(*args, **kwargs):
with tempfile.TemporaryDirectory() as tmpdir:
shutil.copytree(context.home_dir,
f"{tmpdir}/gnupg",
ignore=dirs_files_only)
kwargs["context"] = gpg.Context(armor=context.armor,
home_dir=f"{tmpdir}/gnupg")
shutil.copytree(context.home_dir, f"{tmpdir}/gnupg", ignore=dirs_files_only)
kwargs["context"] = gpg.Context(armor=context.armor, home_dir=f"{tmpdir}/gnupg")
kwargs["buffer"] = gpg.Data()
return f(*args, **kwargs)
@ -111,19 +81,19 @@ def get_key(fingerprint, context=default_context):
except gpg.errors.GPGMEError:
return None
def get_daemon_key(context = default_context):
if daemon_key_fpr is None or daemon_key_fpr == "":
return None
return context.get_key(daemon_key_fpr, secret=True)
def get_imported_keys(context = default_context):
# All the keys in the keyring, except for the daemon's key
return list(
filter(lambda k: k.fpr != daemon_key_fpr,
context.keylist(secret=False)))
filter(
lambda k: k.fpr != daemon_key_fpr,
context.keylist(secret=False)
)
)
def import_key(key, context = default_context):
data = str.encode(key)
@ -131,13 +101,10 @@ def import_key(key, context=default_context):
raise ValueError("Import cannot contain private keys!")
return context.key_import(data)
def export_key(fingerprint, context = default_context):
if get_key(fingerprint) is None:
return None
# Key does exist, export it!
return context.key_export(pattern=fingerprint)
return context.key_export(pattern=fingerprint) # Key does exist, export it!
def delete_key(fingerprint, context = default_context):
key = get_key(fingerprint)
@ -145,26 +112,18 @@ def delete_key(fingerprint, context=default_context):
raise ValueError("You cannot delete the daemon's key!")
elif key is None:
return None
context.op_delete_ext(
key, gpg.constants.DELETE_ALLOW_SECRET | gpg.constants.DELETE_FORCE)
context.op_delete_ext(key, gpg.constants.DELETE_ALLOW_SECRET | gpg.constants.DELETE_FORCE)
return True
# Key usage
# Uses the daemon key to sign the provided message. If 'detached' is True, only the signature will be returned
def create_signature(data, detached=False, context = default_context):
signed_data, _ = context.sign(data,
mode=gpg.constants.sig.mode.DETACH if
detached else gpg.constants.sig.mode.CLEAR)
signed_data, _ = context.sign(data, mode=gpg.constants.sig.mode.DETACH if detached else gpg.constants.sig.mode.CLEAR)
return signed_data
if __name__ == "__main__":
import sys
import utils
import sys, utils
# Check if we should renew the key
daemon_key = get_daemon_key()

View file

@ -1,19 +1,13 @@
#!/usr/local/lib/mailinabox/env/bin/python
# Utilities for installing and selecting SSL certificates.
import os
import os.path
import re
import shutil
import subprocess
import tempfile
import os, os.path, re, shutil, subprocess, tempfile
from utils import shell, safe_domain_name, sort_domains
import idna
# SELECTING SSL CERTIFICATES FOR USE IN WEB
def get_ssl_certificates(env):
# Scan all of the installed SSL certificates and map every domain
# that the certificates are good for to the best certificate for
@ -64,33 +58,36 @@ def get_ssl_certificates(env):
# Not a valid PEM format for a PEM type we care about.
continue
# Remember where we got this object.
pem._filename = fn
# Is it a private key?
if isinstance(pem, RSAPrivateKey):
private_keys[pem.public_key().public_numbers()] = { "filename": fn, "key": pem }
private_keys[pem.public_key().public_numbers()] = pem
# Is it a certificate?
if isinstance(pem, Certificate):
certificates.append({ "filename": fn, "cert": pem })
certificates.append(pem)
# Process the certificates.
domains = { }
for cert in certificates:
# What domains is this certificate good for?
cert_domains, primary_domain = get_certificate_domains(cert["cert"])
cert["primary_domain"] = primary_domain
cert_domains, primary_domain = get_certificate_domains(cert)
cert._primary_domain = primary_domain
# Is there a private key file for this certificate?
private_key = private_keys.get(cert["cert"].public_key().public_numbers())
private_key = private_keys.get(cert.public_key().public_numbers())
if not private_key:
continue
cert["private_key"] = private_key
cert._private_key = private_key
# Add this cert to the list of certs usable for the domains.
for domain in cert_domains:
# The primary hostname can only use a certificate mapped
# to the system private key.
if domain == env['PRIMARY_HOSTNAME']:
if cert["private_key"]["filename"] != os.path.join(env['STORAGE_ROOT'], 'ssl', 'ssl_private_key.pem'):
if cert._private_key._filename != os.path.join(env['STORAGE_ROOT'], 'ssl', 'ssl_private_key.pem'):
continue
domains.setdefault(domain, []).append(cert)
@ -103,10 +100,10 @@ def get_ssl_certificates(env):
#for c in cert_list: print(domain, c.not_valid_before, c.not_valid_after, "("+str(now)+")", c.issuer, c.subject, c._filename)
cert_list.sort(key = lambda cert : (
# must be valid NOW
cert["cert"].not_valid_before <= now <= cert["cert"].not_valid_after,
cert.not_valid_before <= now <= cert.not_valid_after,
# prefer one that is not self-signed
cert["cert"].issuer != cert["cert"].subject,
cert.issuer != cert.subject,
###########################################################
# The above lines ensure that valid certificates are chosen
@ -116,7 +113,7 @@ def get_ssl_certificates(env):
# prefer one with the expiration furthest into the future so
# that we can easily rotate to new certs as we get them
cert["cert"].not_valid_after,
cert.not_valid_after,
###########################################################
# We always choose the certificate that is good for the
@ -131,37 +128,29 @@ def get_ssl_certificates(env):
# in case a certificate is installed in multiple paths,
# prefer the... lexicographically last one?
cert["filename"],
cert._filename,
), reverse=True)
cert = cert_list.pop(0)
ret[domain] = {
"private-key": cert["private_key"]["filename"],
"certificate": cert["filename"],
"primary-domain": cert["primary_domain"],
"certificate_object": cert["cert"],
"private-key": cert._private_key._filename,
"certificate": cert._filename,
"primary-domain": cert._primary_domain,
"certificate_object": cert,
}
return ret
def get_domain_ssl_files(domain,
ssl_certificates,
env,
allow_missing_cert=False,
use_main_cert=True):
def get_domain_ssl_files(domain, ssl_certificates, env, allow_missing_cert=False, use_main_cert=True):
if use_main_cert or not allow_missing_cert:
# Get the system certificate info.
ssl_private_key = os.path.join(
os.path.join(env["STORAGE_ROOT"], 'ssl', 'ssl_private_key.pem'))
ssl_certificate = os.path.join(
os.path.join(env["STORAGE_ROOT"], 'ssl', 'ssl_certificate.pem'))
ssl_private_key = os.path.join(os.path.join(env["STORAGE_ROOT"], 'ssl', 'ssl_private_key.pem'))
ssl_certificate = os.path.join(os.path.join(env["STORAGE_ROOT"], 'ssl', 'ssl_certificate.pem'))
system_certificate = {
"private-key": ssl_private_key,
"certificate": ssl_certificate,
"primary-domain": env['PRIMARY_HOSTNAME'],
"certificate_object":
load_pem(load_cert_chain(ssl_certificate)[0]),
"certificate_object": load_pem(load_cert_chain(ssl_certificate)[0]),
}
if use_main_cert:
@ -185,10 +174,7 @@ def get_domain_ssl_files(domain,
# PROVISIONING CERTIFICATES FROM LETSENCRYPT
def get_certificates_to_provision(env,
limit_domains=None,
show_valid_certs=True):
def get_certificates_to_provision(env, limit_domains=None, show_valid_certs=True):
# Get a set of domain names that we can provision certificates for
# using certbot. We start with domains that the box is serving web
# for and subtract:
@ -215,8 +201,7 @@ def get_certificates_to_provision(env,
# Check that there isn't an explicit A/AAAA record.
if domain not in actual_web_domains:
domains_cant_provision[
domain] = "The domain has a custom DNS A/AAAA record that points the domain elsewhere, so there is no point to installing a TLS certificate here and we could not automatically provision one anyway because provisioning requires access to the website (which isn't here)."
domains_cant_provision[domain] = "The domain has a custom DNS A/AAAA record that points the domain elsewhere, so there is no point to installing a TLS certificate here and we could not automatically provision one anyway because provisioning requires access to the website (which isn't here)."
# Check that the DNS resolves to here.
else:
@ -226,10 +211,8 @@ def get_certificates_to_provision(env,
# make sure both IPv4 and IPv6 are correct because we don't know
# how Let's Encrypt will connect.
bad_dns = []
for rtype, value in [("A", env["PUBLIC_IP"]),
("AAAA", env.get("PUBLIC_IPV6"))]:
if not value:
continue # IPv6 is not configured
for rtype, value in [("A", env["PUBLIC_IP"]), ("AAAA", env.get("PUBLIC_IPV6"))]:
if not value: continue # IPv6 is not configured
response = query_dns(domain, rtype)
if response != normalize_ip(value):
bad_dns.append("%s (%s)" % (response, rtype))
@ -243,21 +226,13 @@ def get_certificates_to_provision(env,
# DNS is all good.
# Check for a good existing cert.
existing_cert = get_domain_ssl_files(domain,
existing_certs,
env,
use_main_cert=False,
allow_missing_cert=True)
existing_cert = get_domain_ssl_files(domain, existing_certs, env, use_main_cert=False, allow_missing_cert=True)
if existing_cert:
existing_cert_check = check_certificate(
domain,
existing_cert['certificate'],
existing_cert['private-key'],
existing_cert_check = check_certificate(domain, existing_cert['certificate'], existing_cert['private-key'],
warn_if_expiring_soon=14)
if existing_cert_check[0] == "OK":
if show_valid_certs:
domains_cant_provision[
domain] = "The domain has a valid certificate already. ({} Certificate: {}, private key {})".format(
domains_cant_provision[domain] = "The domain has a valid certificate already. ({} Certificate: {}, private key {})".format(
existing_cert_check[1],
existing_cert['certificate'],
existing_cert['private-key'])
@ -267,12 +242,10 @@ def get_certificates_to_provision(env,
return (domains_to_provision, domains_cant_provision)
def provision_certificates(env, limit_domains):
# What domains should we provision certificates for? And what
# errors prevent provisioning for other domains.
domains, domains_cant_provision = get_certificates_to_provision(
env, limit_domains=limit_domains)
domains, domains_cant_provision = get_certificates_to_provision(env, limit_domains=limit_domains)
# Build a list of what happened on each domain or domain-set.
ret = []
@ -335,8 +308,7 @@ def provision_certificates(env, limit_domains):
try:
# Create a CSR file for our master private key so that certbot
# uses our private key.
key_file = os.path.join(env['STORAGE_ROOT'], 'ssl',
'ssl_private_key.pem')
key_file = os.path.join(env['STORAGE_ROOT'], 'ssl', 'ssl_private_key.pem')
with tempfile.NamedTemporaryFile() as csr_file:
# We could use openssl, but certbot requires
# that the CN domain and SAN domains match
@ -354,18 +326,12 @@ def provision_certificates(env, limit_domains):
from cryptography.hazmat.primitives import hashes
from cryptography.x509.oid import NameOID
builder = x509.CertificateSigningRequestBuilder()
builder = builder.subject_name(
x509.Name([
x509.NameAttribute(NameOID.COMMON_NAME, domain_list[0])
]))
builder = builder.add_extension(x509.BasicConstraints(
ca=False, path_length=None),
critical=True)
builder = builder.subject_name(x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, domain_list[0]) ]))
builder = builder.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
builder = builder.add_extension(x509.SubjectAlternativeName(
[x509.DNSName(d) for d in domain_list]),
critical=False)
request = builder.sign(load_pem(load_cert_chain(key_file)[0]),
hashes.SHA256(), default_backend())
[x509.DNSName(d) for d in domain_list]
), critical=False)
request = builder.sign(load_pem(load_cert_chain(key_file)[0]), hashes.SHA256(), default_backend())
with open(csr_file.name, "wb") as f:
f.write(request.public_bytes(Encoding.PEM))
@ -374,10 +340,8 @@ def provision_certificates(env, limit_domains):
os.makedirs(webroot, exist_ok=True)
with tempfile.TemporaryDirectory() as d:
cert_file = os.path.join(d, 'cert_and_chain.pem')
print("Provisioning TLS certificates for " +
", ".join(domain_list) + ".")
certbotret = subprocess.check_output(
[
print("Provisioning TLS certificates for " + ", ".join(domain_list) + ".")
certbotret = subprocess.check_output([
"certbot",
"certonly",
#"-v", # just enough to see ACME errors
@ -385,29 +349,18 @@ def provision_certificates(env, limit_domains):
"--agree-tos", # Automatically agrees to Let's Encrypt TOS
"--register-unsafely-without-email", # The daemon takes care of renewals
# first will be main domain
"-d",
",".join(domain_list),
"-d", ",".join(domain_list), # first will be main domain
# use our private key; unfortunately this doesn't work with auto-renew so we need to save cert manually
"--csr",
csr_file.name,
# we only use the full chain
"--cert-path",
os.path.join(d, 'cert'),
# we only use the full chain
"--chain-path",
os.path.join(d, 'chain'),
"--fullchain-path",
cert_file,
"--webroot",
"--webroot-path",
webroot,
"--config-dir",
account_path,
"--csr", csr_file.name, # use our private key; unfortunately this doesn't work with auto-renew so we need to save cert manually
"--cert-path", os.path.join(d, 'cert'), # we only use the full chain
"--chain-path", os.path.join(d, 'chain'), # we only use the full chain
"--fullchain-path", cert_file,
"--webroot", "--webroot-path", webroot,
"--config-dir", account_path,
#"--staging",
],
stderr=subprocess.STDOUT).decode("utf8")
], stderr=subprocess.STDOUT).decode("utf8")
install_cert_copy_file(cert_file, env)
ret[-1]["log"].append(certbotret)
@ -425,7 +378,6 @@ def provision_certificates(env, limit_domains):
# Return what happened with each certificate request.
return ret
def provision_certificates_cmdline():
import sys
from exclusiveprocess import Lock
@ -462,13 +414,12 @@ def provision_certificates_cmdline():
# INSTALLING A NEW CERTIFICATE FROM THE CONTROL PANEL
def create_csr(domain, ssl_key, country_code, env):
return shell("check_output", [
"openssl", "req", "-new", "-key", ssl_key, "-sha256", "-subj",
"/C=%s/CN=%s" % (country_code, domain)
])
"openssl", "req", "-new",
"-key", ssl_key,
"-sha256",
"-subj", "/C=%s/CN=%s" % (country_code, domain)])
def install_cert(domain, ssl_cert, ssl_chain, env, raw=False):
# Write the combined cert+chain to a temporary path and validate that it is OK.
@ -479,10 +430,8 @@ def install_cert(domain, ssl_cert, ssl_chain, env, raw=False):
os.close(fd)
# Do validation on the certificate before installing it.
ssl_private_key = os.path.join(
os.path.join(env["STORAGE_ROOT"], 'ssl', 'ssl_private_key.pem'))
cert_status, cert_status_details = check_certificate(
domain, fn, ssl_private_key)
ssl_private_key = os.path.join(os.path.join(env["STORAGE_ROOT"], 'ssl', 'ssl_private_key.pem'))
cert_status, cert_status_details = check_certificate(domain, fn, ssl_private_key)
if cert_status != "OK":
if cert_status == "SELF-SIGNED":
cert_status = "This is a self-signed certificate. I can't install that."
@ -496,8 +445,7 @@ def install_cert(domain, ssl_cert, ssl_chain, env, raw=False):
# Run post-install steps.
ret = post_install_func(env)
if raw:
return ret
if raw: return ret
return "\n".join(ret)
@ -509,15 +457,11 @@ def install_cert_copy_file(fn, env):
cert = load_pem(load_cert_chain(fn)[0])
all_domains, cn = get_certificate_domains(cert)
path = "%s-%s-%s.pem" % (
# common name, which should be filename safe because it is IDNA-encoded, but in case of a malformed cert make sure it's ok to use as a filename
safe_domain_name(cn),
cert.not_valid_after.date().isoformat().replace("-",
""), # expiration date
hexlify(cert.fingerprint(
hashes.SHA256())).decode("ascii")[0:8], # fingerprint prefix
safe_domain_name(cn), # common name, which should be filename safe because it is IDNA-encoded, but in case of a malformed cert make sure it's ok to use as a filename
cert.not_valid_after.date().isoformat().replace("-", ""), # expiration date
hexlify(cert.fingerprint(hashes.SHA256())).decode("ascii")[0:8], # fingerprint prefix
)
ssl_certificate = os.path.join(
os.path.join(env["STORAGE_ROOT"], 'ssl', path))
ssl_certificate = os.path.join(os.path.join(env["STORAGE_ROOT"], 'ssl', path))
# Install the certificate.
os.makedirs(os.path.dirname(ssl_certificate), exist_ok=True)
@ -529,21 +473,16 @@ def post_install_func(env):
# Get the certificate to use for PRIMARY_HOSTNAME.
ssl_certificates = get_ssl_certificates(env)
cert = get_domain_ssl_files(env['PRIMARY_HOSTNAME'],
ssl_certificates,
env,
use_main_cert=False)
cert = get_domain_ssl_files(env['PRIMARY_HOSTNAME'], ssl_certificates, env, use_main_cert=False)
if not cert:
# Ruh-row, we don't have any certificate usable
# for the primary hostname.
ret.append("there is no valid certificate for " +
env['PRIMARY_HOSTNAME'])
ret.append("there is no valid certificate for " + env['PRIMARY_HOSTNAME'])
# Symlink the best cert for PRIMARY_HOSTNAME to the system
# certificate path, which is hard-coded for various purposes, and then
# restart postfix and dovecot.
system_ssl_certificate = os.path.join(
os.path.join(env["STORAGE_ROOT"], 'ssl', 'ssl_certificate.pem'))
system_ssl_certificate = os.path.join(os.path.join(env["STORAGE_ROOT"], 'ssl', 'ssl_certificate.pem'))
if cert and os.readlink(system_ssl_certificate) != cert['certificate']:
# Update symlink.
ret.append("updating primary certificate")
@ -566,16 +505,9 @@ def post_install_func(env):
return ret
# VALIDATION OF CERTIFICATES
def check_certificate(domain,
ssl_certificate,
ssl_private_key,
warn_if_expiring_soon=10,
rounded_time=False,
just_check_domain=False):
def check_certificate(domain, ssl_certificate, ssl_private_key, warn_if_expiring_soon=10, rounded_time=False, just_check_domain=False):
# Check that the ssl_certificate & ssl_private_key files are good
# for the provided domain.
@ -588,11 +520,9 @@ def check_certificate(domain,
try:
ssl_cert_chain = load_cert_chain(ssl_certificate)
cert = load_pem(ssl_cert_chain[0])
if not isinstance(cert, Certificate):
raise ValueError("This is not a certificate file.")
if not isinstance(cert, Certificate): raise ValueError("This is not a certificate file.")
except ValueError as e:
return ("There is a problem with the certificate file: %s" % str(e),
None)
return ("There is a problem with the certificate file: %s" % str(e), None)
# First check that the domain name is one of the names allowed by
# the certificate.
@ -604,27 +534,21 @@ def check_certificate(domain,
# should work in normal cases).
wildcard_domain = re.sub("^[^\.]+", "*", domain)
if domain not in certificate_names and wildcard_domain not in certificate_names:
return (
"The certificate is for the wrong domain name. It is for %s." %
", ".join(sorted(certificate_names)), None)
return ("The certificate is for the wrong domain name. It is for %s."
% ", ".join(sorted(certificate_names)), None)
# Second, check that the certificate matches the private key.
if ssl_private_key is not None:
try:
priv_key = load_pem(open(ssl_private_key, 'rb').read())
except ValueError as e:
return ("The private key file %s is not a private key file: %s" %
(ssl_private_key, str(e)), None)
return ("The private key file %s is not a private key file: %s" % (ssl_private_key, str(e)), None)
if not isinstance(priv_key, RSAPrivateKey):
return ("The private key file %s is not a private key file." %
ssl_private_key, None)
return ("The private key file %s is not a private key file." % ssl_private_key, None)
if priv_key.public_key().public_numbers() != cert.public_key(
).public_numbers():
return (
"The certificate does not correspond to the private key at %s."
% ssl_private_key, None)
if priv_key.public_key().public_numbers() != cert.public_key().public_numbers():
return ("The certificate does not correspond to the private key at %s." % ssl_private_key, None)
# We could also use the openssl command line tool to get the modulus
# listed in each file. The output of each command below looks like "Modulus=XXXXX".
@ -646,9 +570,7 @@ def check_certificate(domain,
import datetime
now = datetime.datetime.utcnow()
if not(cert.not_valid_before <= now <= cert.not_valid_after):
return (
"The certificate has expired or is not yet valid. It is valid from %s to %s."
% (cert.not_valid_before, cert.not_valid_after), None)
return ("The certificate has expired or is not yet valid. It is valid from %s to %s." % (cert.not_valid_before, cert.not_valid_after), None)
# Next validate that the certificate is valid. This checks whether the certificate
# is self-signed, that the chain of trust makes sense, that it is signed by a CA
@ -657,17 +579,11 @@ def check_certificate(domain,
# The certificate chain has to be passed separately and is given via STDIN.
# This command returns a non-zero exit status in most cases, so trap errors.
retcode, verifyoutput = shell(
'check_output',
[
retcode, verifyoutput = shell('check_output', [
"openssl",
"verify",
"-verbose",
"-purpose",
"sslserver",
"-policy_check",
] +
([] if len(ssl_cert_chain) == 1 else ["-untrusted", "/proc/self/fd/0"])
"verify", "-verbose",
"-purpose", "sslserver", "-policy_check",]
+ ([] if len(ssl_cert_chain) == 1 else ["-untrusted", "/proc/self/fd/0"])
+ [ssl_certificate],
input=b"\n\n".join(ssl_cert_chain[1:]),
trap=True)
@ -678,13 +594,10 @@ def check_certificate(domain,
elif retcode != 0:
if "unable to get local issuer certificate" in verifyoutput:
return (
"The certificate is missing an intermediate chain or the intermediate chain is incorrect or incomplete. (%s)"
% verifyoutput, None)
return ("The certificate is missing an intermediate chain or the intermediate chain is incorrect or incomplete. (%s)" % verifyoutput, None)
# There is some unknown problem. Return the `openssl verify` raw output.
return ("There is a problem with the certificate.",
verifyoutput.strip())
return ("There is a problem with the certificate.", verifyoutput.strip())
else:
# `openssl verify` returned a zero exit status so the cert is currently
@ -695,12 +608,10 @@ def check_certificate(domain,
ndays = (cert_expiration_date-now).days
if not rounded_time or ndays <= 10:
# Yikes better renew soon!
expiry_info = "The certificate expires in %d days on %s." % (
ndays, cert_expiration_date.date().isoformat())
expiry_info = "The certificate expires in %d days on %s." % (ndays, cert_expiration_date.date().isoformat())
else:
# We'll renew it with Lets Encrypt.
expiry_info = "The certificate expires on %s." % cert_expiration_date.date(
).isoformat()
expiry_info = "The certificate expires on %s." % cert_expiration_date.date().isoformat()
if warn_if_expiring_soon and ndays <= warn_if_expiring_soon:
# Warn on day 10 to give 4 days for us to automatically renew the
@ -710,7 +621,6 @@ def check_certificate(domain,
# Return the special OK code.
return ("OK", expiry_info)
def load_cert_chain(pemfile):
# A certificate .pem file may contain a chain of certificates.
# Load the file and split them apart.
@ -722,7 +632,6 @@ def load_cert_chain(pemfile):
raise ValueError("File does not contain valid PEM data.")
return pemblocks
def load_pem(pem):
# Parse a "---BEGIN .... END---" PEM string and return a Python object for it
# using classes from the cryptography package.
@ -734,14 +643,10 @@ def load_pem(pem):
raise ValueError("File is not a valid PEM-formatted file.")
pem_type = pem_type.group(1)
if pem_type in (b"RSA PRIVATE KEY", b"PRIVATE KEY"):
return serialization.load_pem_private_key(pem,
password=None,
backend=default_backend())
return serialization.load_pem_private_key(pem, password=None, backend=default_backend())
if pem_type == b"CERTIFICATE":
return load_pem_x509_certificate(pem, default_backend())
raise ValueError("Unsupported PEM object type: " +
pem_type.decode("ascii", "replace"))
raise ValueError("Unsupported PEM object type: " + pem_type.decode("ascii", "replace"))
def get_certificate_domains(cert):
from cryptography.x509 import DNSName, ExtensionNotFound, OID_COMMON_NAME, OID_SUBJECT_ALTERNATIVE_NAME
@ -770,8 +675,7 @@ def get_certificate_domains(cert):
return idna.encode(dns_name).decode('ascii')
try:
sans = cert.extensions.get_extension_for_oid(
OID_SUBJECT_ALTERNATIVE_NAME).value.get_values_for_type(DNSName)
sans = cert.extensions.get_extension_for_oid(OID_SUBJECT_ALTERNATIVE_NAME).value.get_values_for_type(DNSName)
for san in sans:
names.add(idna_decode_dns_name(san))
except ExtensionNotFound:
@ -779,7 +683,6 @@ def get_certificate_domains(cert):
return names, cn
if __name__ == "__main__":
# Provision certificates.
provision_certificates_cmdline()

File diff suppressed because it is too large Load diff

View file

@ -1,110 +1,80 @@
<style>
#alias_table .alias-auto .actions>* {
display: none
}
#addalias-form .hidden {
display: none;
}
.btn.btn-xs {
padding: .1rem .3rem;
font-size: .75rem;
border-radius: .2rem;
}
#alias_table .actions > * { padding-right: 3px; }
#alias_table .alias-auto .actions > * { display: none }
</style>
<h2>Aliases</h2>
<h3>Add a mail alias</h3>
<p>Aliases are email forwarders. An alias can forward email to a <a href="#" onclick="return show_panel('users')">mail
user</a> or to any email address.</p>
<p>Aliases are email forwarders. An alias can forward email to a <a href="#" onclick="return show_panel('users')">mail user</a> or to any email address.</p>
<p>To use an alias or any address besides your own login username in outbound mail, the sending user must be included as
a permitted sender for the alias.</p>
<p>To use an alias or any address besides your own login username in outbound mail, the sending user must be included as a permitted sender for the alias.</p>
<form id="addalias-form" class="form-horizontal" role="form" onsubmit="do_add_alias(); return false;">
<div class="mb-3">
<div class="form-group">
<div class="col-sm-offset-1 col-sm-11">
<div id="alias_type_buttons" class="btn-group btn-group-xs">
<button type="button" class="btn btn-secondary" data-mode="regular">Regular</button>
<button type="button" class="btn btn-secondary" data-mode="catchall">Catch-All</button>
<button type="button" class="btn btn-secondary" data-mode="domainalias">Domain Alias</button>
<button type="button" class="btn btn-default" data-mode="regular">Regular</button>
<button type="button" class="btn btn-default" data-mode="catchall">Catch-All</button>
<button type="button" class="btn btn-default" data-mode="domainalias">Domain Alias</button>
</div>
<div id="alias_mode_info" class="text-info small" style="display: none; margin: .5em 0 0 0;">
<span class="catchall hidden">A catch-all alias captures all otherwise unmatched email to a domain.</span>
<span class="domainalias hidden">A domain alias forwards all otherwise unmatched email from one domain to
another domain, preserving the part before the @-sign.</span>
<span class="domainalias hidden">A domain alias forwards all otherwise unmatched email from one domain to another domain, preserving the part before the @-sign.</span>
</div>
</div>
<div class="col-lg-9 mb-3">
<div class="input-group">
<label for="addaliasAddress" class="input-group-text">Alias</label>
</div>
<div class="form-group">
<label for="addaliasAddress" class="col-sm-1 control-label">Alias</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="addaliasAddress">
</div>
<div style="margin-top: 3px; padding-left: 3px; font-size: 90%" class="text-muted">
<span class="catchall domainalias">Enter just the part of an email address starting with the @-sign.</span>
You may use international (non-ASCII) characters for the domain part of the email address only.
</div>
</div>
<div class="col-lg-9 mb-3">
<div class="form-floating">
<textarea class="form-control" style="min-height: 8em;" id="addaliasForwardsTo"></textarea>
<label for="addaliasForwardsTo">Forwards To</label>
</div>
<div class="form-group">
<label for="addaliasForwardsTo" class="col-sm-1 control-label">Forwards To</label>
<div class="col-sm-10">
<textarea class="form-control" rows="3" id="addaliasForwardsTo"></textarea>
<div style="margin-top: 3px; padding-left: 3px; font-size: 90%">
<span class="domainalias text-muted">Enter just the part of an email address starting with the
@-sign.</span>
<span class="text-danger">Only forward mail to addresses handled by this Mail-in-a-Box, since mail forwarded
by aliases to other domains may be rejected or filtered by the receiver. To forward mail to other
domains, create a mail user and then log into webmail for the user and create a filter rule to forward
mail.</span>
<span class="domainalias text-muted">Enter just the part of an email address starting with the @-sign.</span>
<span class="text-danger">Only forward mail to addresses handled by this Mail-in-a-Box, since mail forwarded by aliases to other domains may be rejected or filtered by the receiver. To forward mail to other domains, create a mail user and then log into webmail for the user and create a filter rule to forward mail.</span>
</div>
</div>
<h4>Permitted Senders</h4>
<div class="col-lg-9 mb-3">
<div class="mb-3">
<div class="mb-3">
</div>
<div class="form-group">
<label for="addaliasSenders" class="col-sm-1 control-label">Permitted Senders</label>
<div class="col-sm-10">
<div class="radio">
<label>
<input id="addaliasForwardsToNotAdvanced" name="addaliasForwardsToDivToggle" type="radio"
checked onclick="$('#addaliasForwardsToDiv').toggle(false)">
Any mail user listed in the Forwards To box can send mail claiming to be from <span
class="regularalias">the alias address</span><span class="catchall domainalias">any address
on the alias domain</span>.
<input id="addaliasForwardsToNotAdvanced" name="addaliasForwardsToDivToggle" type="radio" checked onclick="$('#addaliasForwardsToDiv').toggle(false)">
Any mail user listed in the Forwards To box can send mail claiming to be from <span class="regularalias">the alias address</span><span class="catchall domainalias">any address on the alias domain</span>.
</label>
</div>
<div class="radio">
<label>
<input id="addaliasForwardsToAdvanced" name="addaliasForwardsToDivToggle" type="radio"
id="addaliasForwardsToDivShower" onclick="$('#addaliasForwardsToDiv').toggle(true)">
I&rsquo;ll enter the mail users that can send mail claiming to be from <span
class="regularalias">the alias address</span><span class="catchall domainalias">any address
on the alias domain</span>.
<input id="addaliasForwardsToAdvanced" name="addaliasForwardsToDivToggle" type="radio" id="addaliasForwardsToDivShower" onclick="$('#addaliasForwardsToDiv').toggle(true)">
I&rsquo;ll enter the mail users that can send mail claiming to be from <span class="regularalias">the alias address</span><span class="catchall domainalias">any address on the alias domain</span>.
</label>
</div>
</div>
<div id="addaliasForwardsToDiv" style="display: none;">
<div class="form-floating">
<textarea class="form-control" style="min-height: 8em;" id="addaliasSenders"
placeholder="one user per line or separated by commas"></textarea>
<label for="addaliasSenders">Permitted Senders</label>
</div>
<small>One user per line or separated by commas</small>
<div id="addaliasForwardsToDiv" style="margin-top: .5em; margin-left: 1.4em; display: none;">
<textarea class="form-control" rows="3" id="addaliasSenders" placeholder="one user per line or separated by commas"></textarea>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-11">
<button id="add-alias-button" type="submit" class="btn btn-primary">Add Alias</button>
<button id="alias-cancel" class="btn btn-default hidden" onclick="aliases_reset_form(); return false;">Cancel</button>
</div>
</div>
</form>
<h3>Existing mail aliases</h3>
<table id="alias_table" class="table">
<caption></caption>
<table id="alias_table" class="table" style="width: auto">
<thead>
<tr>
<th></th>
@ -117,21 +87,18 @@
</tbody>
</table>
<p style="margin-top: 1.5em"><small>hostmaster@, postmaster@, admin@ and abuse@ email addresses are required on some
domains.</small></p>
<p style="margin-top: 1.5em"><small>hostmaster@, postmaster@, admin@ and abuse@ email addresses are required on some domains.</small></p>
<div style="display: none">
<table>
<tr id="alias-template">
<td class='actions row justify-content-evenly' style="min-width: 4em; border: none;">
<button class="col-5 btn btn-xs btn-default" onclick="aliases_edit(this); scroll_top(); return false;"
class='edit' title="Edit Alias">
<span class="text-center text-primary fas fa-pen"></span>
</button>
<button class="col-5 btn btn-xs btn-default" onclick="aliases_remove(this); return false;"
class='remove' title="Remove Alias">
<span class="text-center text-danger fas fa-trash"></span>
</button>
<td class='actions'>
<a href="#" onclick="aliases_edit(this); scroll_top(); return false;" class='edit' title="Edit Alias">
<span class="fas fa-pen"></span>
</a>
<a href="#" onclick="aliases_remove(this); return false;" class='remove' title="Remove Alias">
<span class="fas fa-trash"></span>
</a>
</td>
<td class='address'> </td>
<td class='forwardsTo'> </td>
@ -142,8 +109,7 @@
<h3>Mail aliases API (advanced)</h3>
<p>Use your box&rsquo;s mail aliases API to add and remove mail aliases from the command-line or custom services you
build.</p>
<p>Use your box&rsquo;s mail aliases API to add and remove mail aliases from the command-line or custom services you build.</p>
<p>Usage:</p>
@ -156,35 +122,15 @@
<h4 style="margin-bottom: 0">Verbs</h4>
<table class="table" style="margin-top: .5em">
<caption></caption>
<thead>
<th>Verb</th>
<th>Action</th>
<th></th>
</thead>
<tr>
<td><b>GET</b></td>
<td><i>(none)</i></td>
<td>Returns a list of existing mail aliases. Adding <code>?format=json</code> to the URL will give JSON-encoded
results.</td>
</tr>
<tr>
<td><b>POST</b></td>
<td class="font-monospace">/add</td>
<td>Adds a new mail alias. Required POST-body parameters are <code>address</code> and <code>forwards_to</code>.
</td>
</tr>
<tr>
<td><b>POST</b></td>
<td class="font-monospace">/remove</td>
<td>Removes a mail alias. Required POST-body parameter is <code>address</code>.</td>
</tr>
<thead><th>Verb</th> <th>Action</th><th></th></thead>
<tr><td>GET</td><td><i>(none)</i></td> <td>Returns a list of existing mail aliases. Adding <code>?format=json</code> to the URL will give JSON-encoded results.</td></tr>
<tr><td>POST</td><td>/add</td> <td>Adds a new mail alias. Required POST-body parameters are <code>address</code> and <code>forwards_to</code>.</td></tr>
<tr><td>POST</td><td>/remove</td> <td>Removes a mail alias. Required POST-body parameter is <code>address</code>.</td></tr>
</table>
<h4>Examples:</h4>
<p>Try these examples. For simplicity the examples omit the <code>--user me@mydomain.com:yourpassword</code> command
line argument which you must fill in with your email address and password.</p>
<p>Try these examples. For simplicity the examples omit the <code>--user me@mydomain.com:yourpassword</code> command line argument which you must fill in with your email address and password.</p>
<pre># Gives a JSON-encoded list of all mail aliases
curl -X GET https://{{hostname}}/admin/mail/aliases?format=json
@ -207,7 +153,7 @@ curl -X POST -d "address=new_alias@mydomail.com" https://{{hostname}}/admin/mail
function(r) {
$('#alias_table tbody').html("");
for (var i = 0; i < r.length; i++) {
var hdr = $("<tr><th colspan='4' class='bg-light'></th></tr>");
var hdr = $("<tr><th colspan='4' style='background-color: #EEE'></th></tr>");
hdr.find('th').text(r[i].domain);
$('#alias_table tbody').append(hdr);
@ -229,31 +175,33 @@ curl -X POST -d "address=new_alias@mydomail.com" https://{{hostname}}/admin/mail
}
})
$(function() {
$('#alias_type_buttons button').off('click').click(function() {
$('#alias_type_buttons button').removeClass('active');
$(this).addClass('active');
$('#addalias-form .regularalias, #addalias-form .catchall, #addalias-form .domainalias').addClass('hidden');
if ($(this).attr('data-mode') == "regular") {
$('#addaliasAddress').attr('type', 'email');
$('#addaliasAddress').attr('placeholder', 'you@example.com (incoming email address)');
$('#addaliasAddress').attr('placeholder', 'you@yourdomain.com (incoming email address)');
$('#addaliasForwardsTo').attr('placeholder', 'one address per line or separated by commas');
$('#alias_mode_info').slideUp();
$('#addalias-form .regularalias').removeClass('hidden');
} else if ($(this).attr('data-mode') == "catchall") {
$('#addaliasAddress').attr('type', 'text');
$('#addaliasAddress').attr('placeholder', '@example.com (incoming catch-all domain)');
$('#addaliasAddress').attr('placeholder', '@yourdomain.com (incoming catch-all domain)');
$('#addaliasForwardsTo').attr('placeholder', 'one address per line or separated by commas');
$('#alias_mode_info').slideDown();
$('#addalias-form .catchall').removeClass('hidden');
} else if ($(this).attr('data-mode') == "domainalias") {
$('#addaliasAddress').attr('type', 'text');
$('#addaliasAddress').attr('placeholder', '@example.com (incoming catch-all domain)');
$('#addaliasForwardsTo').attr('placeholder', '@example.net (forward to other domain)');
$('#addaliasAddress').attr('placeholder', '@yourdomain.com (incoming catch-all domain)');
$('#addaliasForwardsTo').attr('placeholder', '@otherdomain.com (forward to other domain)');
$('#alias_mode_info').slideDown();
$('#addalias-form .domainalias').removeClass('hidden');
}
})
$('#alias_type_buttons button[data-mode="regular"]').click(); // init
})
}
var is_alias_add_update = false;

View file

@ -12,72 +12,68 @@
<h3>Set custom DNS records</h3>
<p>You can set additional DNS records, such as if you have a website running on another server, to add DKIM records for
external mail providers, or for various confirmation-of-ownership tests.</p>
<p>You can set additional DNS records, such as if you have a website running on another server, to add DKIM records for external mail providers, or for various confirmation-of-ownership tests.</p>
<form class="form-horizontal" role="form" onsubmit="do_set_custom_dns(); return false;">
<div class="col-lg-10 col-xl-7 mb-3">
<div class="input-group">
<label class="input-group-text">Name</label>
<div class="form-group">
<label for="customdnsQname" class="col-sm-1 control-label">Name</label>
<div class="col-sm-10">
<table style="max-width: 400px">
<tr><td>
<input type="text" class="form-control" id="customdnsQname" placeholder="subdomain">
<label class="input-group-text">.</label>
<select id="customdnsZone" class="form-select"></select>
</td><td style="padding: 0 1em; font-weight: bold;">.</td><td>
<select id="customdnsZone" class="form-control"> </select>
</td></tr></table>
<div class="text-info" style="margin-top: .5em">Leave the left field blank to set a record on the chosen domain name, or enter a subdomain.</div>
</div>
<small>Leave the left field blank to set a record on the chosen domain name, or enter a subdomain.</small>
</div>
<div class="col-lg-10 col-xl-7 mb-3">
<div class="input-group">
<label for="customdnsType" class="input-group-text">Type</label>
<select id="customdnsType" class="form-select" onchange="show_customdns_rtype_hint()">
<option value="A"
data-hint="Enter an IPv4 address (i.e. a dotted quad, such as 123.456.789.012). The 'local' alias sets the record to this box's public IPv4 address.">
A (IPv4 address)</option>
<option value="AAAA"
data-hint="Enter an IPv6 address. The 'local' alias sets the record to this box's public IPv6 address.">
AAAA (IPv6 address)</option>
<option value="CAA"
data-hint="Enter a CA that can issue certificates for this domain in the form of FLAG TAG VALUE. (0 issuewild &quot;letsencrypt.org&quot;)">
CAA (Certificate Authority Authorization)</option>
<option value="CNAME"
data-hint="Enter another domain name followed by a period at the end (e.g. mypage.github.io.).">
CNAME (DNS forwarding)</option>
<div class="form-group">
<label for="customdnsType" class="col-sm-1 control-label">Type</label>
<div class="col-sm-10">
<select id="customdnsType" class="form-control" style="max-width: 400px" onchange="show_customdns_rtype_hint()">
<option value="A" data-hint="Enter an IPv4 address (i.e. a dotted quad, such as 123.456.789.012). The 'local' alias sets the record to this box's public IPv4 address.">A (IPv4 address)</option>
<option value="AAAA" data-hint="Enter an IPv6 address. The 'local' alias sets the record to this box's public IPv6 address.">AAAA (IPv6 address)</option>
<option value="CAA" data-hint="Enter a CA that can issue certificates for this domain in the form of FLAG TAG VALUE. (0 issuewild &quot;letsencrypt.org&quot;)">CAA (Certificate Authority Authorization)</option>
<option value="CNAME" data-hint="Enter another domain name followed by a period at the end (e.g. mypage.github.io.).">CNAME (DNS forwarding)</option>
<option value="TXT" data-hint="Enter arbitrary text.">TXT (text record)</option>
<option value="MX"
data-hint="Enter record in the form of PRIORITY DOMAIN., including trailing period (e.g. 20 mx.example.com.).">
MX (mail exchanger)</option>
<option value="SRV"
data-hint="Enter record in the form of PRIORITY WEIGHT PORT TARGET., including trailing period (e.g. 10 10 5060 sip.example.com.).">
SRV (service record)</option>
<option value="SSHFP" data-hint="Enter record in the form of ALGORITHM TYPE FINGERPRINT.">SSHFP (SSH
fingerprint record)</option>
<option value="NS" data-hint="Enter a hostname to which this subdomain should be delegated to">NS (DNS
subdomain delegation)</option>
<option value="MX" data-hint="Enter record in the form of PRIORITY DOMAIN., including trailing period (e.g. 20 mx.example.com.).">MX (mail exchanger)</option>
<option value="SRV" data-hint="Enter record in the form of PRIORITY WEIGHT PORT TARGET., including trailing period (e.g. 10 10 5060 sip.example.com.).">SRV (service record)</option>
<option value="SSHFP" data-hint="Enter record in the form of ALGORITHM TYPE FINGERPRINT.">SSHFP (SSH fingerprint record)</option>
<option value="NS" data-hint="Enter a hostname to which this subdomain should be delegated to">NS (DNS subdomain delegation)</option>
</select>
</div>
</div>
<div class="col-lg-10 col-xl-7 mb-3">
<div class="input-group">
<label for="customdnsValue" class="input-group-text">Value</label>
<div class="form-group">
<div class="col-sm-10">
<table>
<tr style="width: 100%;">
<td style="width: 75%;">
<label for="customdnsValue" class="control-label">Value</label>
<input type="text" class="form-control" id="customdnsValue" placeholder="">
<label for="customdnsTtl" class="input-group-text">TTL</label>
<input type="number" class="form-control" id="customdnsTtl" placeholder="default">
</td>
<td style="width: 25%;">
<label for="customdnsTtl" class="col-sm-1 control-label">TTL</label>
<input type="number" class="form-control" style="margin-left: 5pt;" id="customdnsTtl" placeholder="default">
</td>
</tr>
</table>
<div id="customdnsTypeHint" class="text-info" style="margin-top: .5em"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-11">
<button type="submit" class="btn btn-primary">Set Record</button>
</div>
<small id="customdnsTypeHint" class="text-info" style="margin-top: .5em"></small>
</div>
<button type="submit" class="btn btn-primary mb-3">Set Record</button>
</form>
<div style="font-size: 90%;">
<b>Sort by:</b>
<a href="#"
onclick="window.miab_custom_dns_data_sort_order='qname'; show_current_custom_dns_update_after_sort(); return false;">Domain
name</a>
<b>|</b>
<a href="#"
onclick="window.miab_custom_dns_data_sort_order='created'; show_current_custom_dns_update_after_sort(); return false;">Created</a>
<div style="text-align: right; font-size: 90%; margin-top: 1em;">
sort by:
<a href="#" onclick="window.miab_custom_dns_data_sort_order='qname'; show_current_custom_dns_update_after_sort(); return false;">domain name</a>
|
<a href="#" onclick="window.miab_custom_dns_data_sort_order='created'; show_current_custom_dns_update_after_sort(); return false;">created</a>
</div>
<table id="custom-dns-current" class="table col-12" style="display: none; margin-top: 0;">
<caption></caption>
<table id="custom-dns-current" class="table" style="width: auto; display: none; margin-top: 0;">
<thead>
<th>Domain Name</th>
<th>Record Type</th>
@ -86,49 +82,44 @@
<th></th>
</thead>
<tbody>
<tr>
<td colspan="5">Loading...</td>
</tr>
<tr><td colspan="5">Loading...</td></tr>
</tbody>
</table>
<h3>Using a secondary nameserver</h3>
<p>If your TLD requires you to have two separate nameservers, you can either set up <a href="#"
onclick="return show_panel('external_dns')">external DNS</a> and ignore the DNS server on this box entirely, or
use the DNS server on this box but add a secondary (aka &ldquo;slave&rdquo;) nameserver.</p>
<p>If you choose to use a secondary nameserver, you must find a secondary nameserver service provider. Your domain name
registrar or virtual cloud provider may provide this service for you. Once you set up the secondary nameserver
service, enter the hostname (not the IP address) of <em>their</em> secondary nameserver in the box below.</p>
<p>If your TLD requires you to have two separate nameservers, you can either set up <a href="#" onclick="return show_panel('external_dns')">external DNS</a> and ignore the DNS server on this box entirely, or use the DNS server on this box but add a secondary (aka &ldquo;slave&rdquo;) nameserver.</p>
<p>If you choose to use a secondary nameserver, you must find a secondary nameserver service provider. Your domain name registrar or virtual cloud provider may provide this service for you. Once you set up the secondary nameserver service, enter the hostname (not the IP address) of <em>their</em> secondary nameserver in the box below.</p>
<form class="form-horizontal" role="form" onsubmit="do_set_secondary_dns(); return false;">
<div class="col-12 form-floating mb-3">
<textarea type="text" class="form-control font-monospace" id="secondarydnsHostname"
placeholder="ns1.example.com"></textarea>
<label for="secondarydnsHostname">Secondary Nameservers</label>
<div>
<div class="form-group">
<label for="secondarydnsHostname" class="col-sm-1 control-label">Hostname</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="secondarydnsHostname" placeholder="ns1.cloudprovider.com">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-11">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-11">
<p class="small">
Multiple secondary servers can be separated with commas or spaces (i.e., <span
class="font-monospace">ns2.hostingcompany.com ns3.hostingcompany.com</span>).
To enable zone transfers to additional servers without listing them as secondary nameservers, add an IP
address or subnet using <span class="font-monospace">xfr:10.20.30.40</span> or <span
class="font-monospace">xfr:10.0.0.0/8</span>.
Multiple secondary servers can be separated with commas or spaces (i.e., <code>ns2.hostingcompany.com ns3.hostingcompany.com</code>).
To enable zone transfers to additional servers without listing them as secondary nameservers, add an IP address or subnet using <code>xfr:10.20.30.40</code> or <code>xfr:10.0.0.0/8</code>.
</p>
<p id="secondarydns-clear-instructions" style="display: none" class="small">
Clear the input field above and click Update to use this machine itself as secondary DNS, which is the
default/normal setup.
Clear the input field above and click Update to use this machine itself as secondary DNS, which is the default/normal setup.
</p>
</div>
</div>
<button type="submit" class="btn btn-primary">Update</button>
</form>
<h3>Custom DNS API</h3>
<p>Use your box&rsquo;s DNS API to set custom DNS records on domains hosted here. For instance, you can create your own
dynamic DNS service.</p>
<p>Use your box&rsquo;s DNS API to set custom DNS records on domains hosted here. For instance, you can create your own dynamic DNS service.</p>
<p>Usage:</p>
@ -139,83 +130,29 @@
<h4>Verbs</h4>
<table class="table">
<caption></caption>
<thead>
<th>Verb</th>
<th>Usage</th>
</thead>
<tr>
<td class="font-monospace"><b>GET</b></td>
<td>Returns matching custom DNS records as a JSON array of objects. Each object has the keys <code>qname</code>,
<code>rtype</code>, and <code>value</code>. The optional <code>qname</code> and <code>rtype</code>
parameters in the request URL filter the records returned in the response. The request body
(<code>-d "..."</code>) must be omitted.</td>
</tr>
<tr>
<td class="font-monospace"><b>PUT</b></td>
<td>Sets a custom DNS record replacing any existing records with the same <code>qname</code> and
<code>rtype</code>. Use PUT (instead of POST) when you only have one value for a <code>qname</code> and
<code>rtype</code>, such as typical <code>A</code> records (without round-robin).</td>
</tr>
<tr>
<td class="font-monospace"><b>POST</b></td>
<td>Adds a new custom DNS record. Use POST when you have multiple <code>TXT</code> records or round-robin
<code>A</code> records. (PUT would delete previously added records.)</td>
</tr>
<tr>
<td class="font-monospace"><b>DELETE</b></td>
<td>Deletes custom DNS records. If the request body (<code>-d "..."</code>) is empty or omitted, deletes all
records matching the <code>qname</code> and <code>rtype</code>. If the request body is present, deletes only
the record matching the <code>qname</code>, <code>rtype</code> and value.</td>
</tr>
<thead><th>Verb</th> <th>Usage</th></thead>
<tr><td>GET</td> <td>Returns matching custom DNS records as a JSON array of objects. Each object has the keys <code>qname</code>, <code>rtype</code>, and <code>value</code>. The optional <code>qname</code> and <code>rtype</code> parameters in the request URL filter the records returned in the response. The request body (<code>-d "..."</code>) must be omitted.</td></tr>
<tr><td>PUT</td> <td>Sets a custom DNS record replacing any existing records with the same <code>qname</code> and <code>rtype</code>. Use PUT (instead of POST) when you only have one value for a <code>qname</code> and <code>rtype</code>, such as typical <code>A</code> records (without round-robin).</td></tr>
<tr><td>POST</td> <td>Adds a new custom DNS record. Use POST when you have multiple <code>TXT</code> records or round-robin <code>A</code> records. (PUT would delete previously added records.)</td></tr>
<tr><td>DELETE</td> <td>Deletes custom DNS records. If the request body (<code>-d "..."</code>) is empty or omitted, deletes all records matching the <code>qname</code> and <code>rtype</code>. If the request body is present, deletes only the record matching the <code>qname</code>, <code>rtype</code> and value.</td></tr>
</table>
<h4>Parameters</h4>
<table class="table">
<caption></caption>
<thead>
<th>Parameter</th>
<th>Value</th>
</thead>
<tr>
<td class="font-monospace"><b>email</b></td>
<td>The email address of any administrative user here.</td>
</tr>
<tr>
<td class="font-monospace"><b>password</b></td>
<td>That user&rsquo;s password.</td>
</tr>
<tr>
<td class="font-monospace"><b>qname</b></td>
<td>The fully qualified domain name for the record you are trying to set. It must be one of the domain names or
a subdomain of one of the domain names hosted on this box. (Add mail users or aliases to add new domains.)
</td>
</tr>
<tr>
<td class="font-monospace"><b>rtype</b></td>
<td>The resource type. Defaults to <code>A</code> if omitted. Possible values: <code>A</code> (an IPv4 address),
<code>AAAA</code> (an IPv6 address), <code>TXT</code> (a text string), <code>CNAME</code> (an alias, which
is a fully qualified domain name &mdash; don&rsquo;t forget the final period), <code>MX</code>,
<code>SRV</code>, <code>SSHFP</code>, <code>CAA</code> or <code>NS</code>.</td>
</tr>
<tr>
<td class="font-monospace"><b>value</b></td>
<td>For PUT, POST, and DELETE, the record&rsquo;s value. If the <code>rtype</code> is <code>A</code> or
<code>AAAA</code> and <code>value</code> is empty or omitted, the IPv4 or IPv6 address of the remote host is
used (be sure to use the <code>-4</code> or <code>-6</code> options to curl). This is handy for dynamic DNS!
</td>
</tr>
<thead><th>Parameter</th> <th>Value</th></thead>
<tr><td>email</td> <td>The email address of any administrative user here.</td></tr>
<tr><td>password</td> <td>That user&rsquo;s password.</td></tr>
<tr><td>qname</td> <td>The fully qualified domain name for the record you are trying to set. It must be one of the domain names or a subdomain of one of the domain names hosted on this box. (Add mail users or aliases to add new domains.)</td></tr>
<tr><td>rtype</td> <td>The resource type. Defaults to <code>A</code> if omitted. Possible values: <code>A</code> (an IPv4 address), <code>AAAA</code> (an IPv6 address), <code>TXT</code> (a text string), <code>CNAME</code> (an alias, which is a fully qualified domain name &mdash; don&rsquo;t forget the final period), <code>MX</code>, <code>SRV</code>, <code>SSHFP</code>, <code>CAA</code> or <code>NS</code>.</td></tr>
<tr><td>value</td> <td>For PUT, POST, and DELETE, the record&rsquo;s value. If the <code>rtype</code> is <code>A</code> or <code>AAAA</code> and <code>value</code> is empty or omitted, the IPv4 or IPv6 address of the remote host is used (be sure to use the <code>-4</code> or <code>-6</code> options to curl). This is handy for dynamic DNS!</td></tr>
</table>
<p>Strict <a href="http://tools.ietf.org/html/rfc4408">SPF</a> and <a
href="https://datatracker.ietf.org/doc/draft-kucherawy-dmarc-base/?include_text=1">DMARC</a> records will be
added to all custom domains unless you override them.</p>
<p>Strict <a href="http://tools.ietf.org/html/rfc4408">SPF</a> and <a href="https://datatracker.ietf.org/doc/draft-kucherawy-dmarc-base/?include_text=1">DMARC</a> records will be added to all custom domains unless you override them.</p>
<h4>Examples:</h4>
<p>Try these examples. For simplicity the examples omit the <code>--user me@mydomain.com:yourpassword</code> command
line argument which you must fill in with your email address and password.</p>
<p>Try these examples. For simplicity the examples omit the <code>--user me@mydomain.com:yourpassword</code> command line argument which you must fill in with your email address and password.</p>
<pre># sets laptop.mydomain.com to point to the IP address of the machine you are executing curl on
curl -X PUT https://{{hostname}}/admin/dns/custom/laptop.mydomain.com
@ -288,7 +225,7 @@ curl -X DELETE -d "some text here" https://{{hostname}}/admin/dns/custom/foo.myd
var last_zone = null;
for (var i = 0; i < data.length; i++) {
if (sort_key == "qname" && data[i].zone != last_zone) {
var r = $("<tr><th colspan=5 class='bg-light'></th></tr>");
var r = $("<tr><th colspan=5 style='background-color: #EEE'></th></tr>");
r.find("th").text(data[i].zone);
tbody.append(r);
last_zone = data[i].zone;
@ -301,13 +238,13 @@ curl -X DELETE -d "some text here" https://{{hostname}}/admin/dns/custom/foo.myd
tr.attr('data-value', data[i].value);
tr.append($('<td class="long"/>').text(data[i].qname));
tr.append($('<td/>').text(data[i].rtype));
tr.append($('<td class="long font-monospace" style="max-width: 40em"/>').text(data[i].value));
tr.append($('<td class="long" style="max-width: 40em"/>').text(data[i].value));
if (data[i].ttl) {
tr.append($('<td/>').text(data[i].ttl));
} else {
tr.append($('<td/>').html('<i class="">default</i>'));
}
tr.append($('<td class="col-1">[<a href="#" onclick="return delete_custom_dns_record(this)">delete</a>]</td>'));
tr.append($('<td>[<a href="#" onclick="return delete_custom_dns_record(this)">delete</a>]</td>'));
}
}

View file

@ -1,23 +1,27 @@
<style>
#external_dns_settings .domain-header {
margin-top: 0.5em;
margin-bottom: 0.5em;
#external_dns_settings .heading td {
font-weight: bold;
font-size: 120%;
padding-top: 1.5em;
}
#external_dns_settings .heading.first td {
border-top: none;
padding-top: 0;
}
#external_dns_settings .values td {
border: 0;
padding-top: .75em;
padding-bottom: 0;
}
#external_dns_settings .value {
word-break: break-all;
}
#external_dns_settings .explanation td {
border: 0;
padding-top: .5em;
padding-bottom: .75em;
font-style: italic;
font-size: 95%;
color: #777;
}
</style>
@ -26,41 +30,33 @@
<p class="text-warning">This is an advanced configuration page.</p>
<p>Although your box is configured to serve its own DNS, it is possible to host your DNS elsewhere &mdash; such as in
the DNS control panel provided by your domain name registrar or virtual cloud provider &mdash; by copying the DNS
zone information shown in the table below into your external DNS server&rsquo;s control panel.</p>
<p>Although your box is configured to serve its own DNS, it is possible to host your DNS elsewhere &mdash; such as in the DNS control panel provided by your domain name registrar or virtual cloud provider &mdash; by copying the DNS zone information shown in the table below into your external DNS server&rsquo;s control panel.</p>
<p>If you do so, you are responsible for keeping your DNS entries up to date! If you previously enabled DNSSEC on your
domain name by setting a DS record at your registrar, you will likely have to turn it off before changing
nameservers.</p>
<p>If you do so, you are responsible for keeping your DNS entries up to date! If you previously enabled DNSSEC on your domain name by setting a DS record at your registrar, you will likely have to turn it off before changing nameservers.</p>
<p class="alert" role="alert">
<span class="fas fa-info-circle"></span>
You may encounter zone file errors when attempting to create a TXT record with a long string.
<a href="https://tools.ietf.org/html/rfc4408#section-3.1.3">RFC 4408</a> states a TXT record is allowed to contain
multiple strings, and this technique can be used to construct records that would exceed the 255-byte maximum length.
You may need to adopt this technique when adding DomainKeys. Use a tool like <code>named-checkzone</code> to
validate your zone file.
<a href="https://tools.ietf.org/html/rfc4408#section-3.1.3">RFC 4408</a> states a TXT record is allowed to contain multiple strings, and this technique can be used to construct records that would exceed the 255-byte maximum length.
You may need to adopt this technique when adding DomainKeys. Use a tool like <code>named-checkzone</code> to validate your zone file.
</p>
<h3>Download zonefile</h3>
<p>You can download your zonefiles here or use the table of records below.</p>
<form class="form-inline" role="form" onsubmit="do_download_zonefile(); return false;">
<div class="col-md-10 col-xl-6 mb-3">
<div class="input-group">
<label for="downloadZonefile" class="input-group-text">Zone</label>
<select id="downloadZonefile" class="form-select"></select>
<div class="form-group">
<div class="form-group">
<label for="downloadZonefile" class="control-label sr-only">Zone</label>
<select id="downloadZonefile" class="form-control" style="width: auto"> </select>
</div>
<button type="submit" style="margin-left: 20px" class="btn btn-primary">Download</button>
</div>
<button type="submit" class="btn btn-primary">Download</button>
</form>
<h3>Records</h3>
<table id="external_dns_settings" class="table">
<caption></caption>
<thead>
<tr>
<th>QName</th>
@ -94,20 +90,20 @@
function(zones) {
$('#external_dns_settings tbody').html("");
for (var j = 0; j < zones.length; j++) {
var h = $("<tr><td colspan='3' class='bg-light'><h4 class='domain-header'/></td></tr>");
h.find("td h4").text(zones[j][0]);
var h = $("<tr class='heading'><td colspan='3'></td></tr>");
h.find("td").text(zones[j][0]);
$('#external_dns_settings tbody').append(h);
var r = zones[j][1];
for (var i = 0; i < r.length; i++) {
var n = $("<tr class='values'><td class='qname'/><td class='rtype'/><td class='value font-monospace'/></tr>");
var n = $("<tr class='values'><td class='qname'/><td class='rtype'/><td class='value'/></tr>");
n.find('.qname').text(r[i].qname);
n.find('.rtype').text(r[i].rtype);
n.find('.value').text(r[i].value);
$('#external_dns_settings tbody').append(n);
var n = $("<tr class='explanation'><td colspan='3'/><small/></tr>");
n.find('td small').text(r[i].explanation);
var n = $("<tr class='explanation'><td colspan='3'/></tr>");
n.find('td').text(r[i].explanation);
$('#external_dns_settings tbody').append(n);
}
}

View file

@ -1,6 +1,5 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta charset="utf-8">
@ -24,10 +23,7 @@
margin-bottom: 1.25em;
}
h1,
h2,
h3,
h4 {
h1, h2, h3, h4 {
font-family: sans-serif;
font-weight: bold;
}
@ -43,7 +39,6 @@
margin-bottom: 13px;
margin-top: 30px;
}
.panel-heading h3 {
border: none;
padding: 0;
@ -55,7 +50,6 @@
margin-bottom: 13px;
margin-top: 18px;
}
h4:first-child {
margin-top: 6px;
}
@ -72,103 +66,89 @@
margin-bottom: 1em;
}
.if-logged-in {
display: none;
}
.if-logged-in { display: none; }
.if-logged-in-admin { 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);
}
}*/
</style>
</head>
<body>
<body class="">
<!--[if lt IE 8]><p>Internet Explorer version 8 or any modern web browser is required to use this website, sorry.<![endif]-->
<!--[if gt IE 7]><!-->
<div class="navbar navbar-expand-lg navbar-light" role="navigation">
<div class="container bg-light pt-2 pb-2">
<div class="if-logged-in">
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent"
aria-controls="#navbarContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar navbar-inverse navbar-static-top" role="navigation">
<div class="container bg-light">
<div class="navbar-header">
<a class="navbar-brand" href="#">{{hostname}}</a>
</div>
<div class="navbar-brand ms-2">
<span class="fas fa-envelope"></span>
<b>{{hostname}}</b>
</div>
<div class="ms-2">
<span class="me-1 fas fa-sun"></span>
<span class="form-switch">
<input class="form-check-input" type="checkbox" role="switch" id="toggle-theme">
<label class="ms-1 fas fa-moon"></label>
</span>
</div>
<div class="collapse navbar-collapse" id="navbarContent">
<ul class="navbar-nav ms-auto">
<li class="nav-item me-1 me-xl-4 dropdown if-logged-in-admin">
<button class="btn dropdown-toggle" type="button" data-bs-toggle="dropdown"
aria-expanded="false">System</button>
<div class="navbar navbar-expand-lg">
<ul class="nav navbar-nav">
<li class="btn dropdown if-logged-in-admin">
<a style="color: black;" href="#" class="dropdown-toggle" data-toggle="dropdown">System <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#system_status" onclick="return show_panel(this);">Status
Checks</a></li>
<li><a class="dropdown-item" href="#tls" onclick="return show_panel(this);">TLS (SSL)
Certificates</a></li>
<li><a class="dropdown-item" href="#system_backup" onclick="return show_panel(this);">Backup
Status</a></li>
<li><a class="dropdown-item" href="#smtp_relays" onclick="return show_panel(this);">SMTP
Relays</a></li>
<li class="dropdown-item"><a href="#system_status" onclick="return show_panel(this);">Status Checks</a></li>
<li class="dropdown-item"><a href="#tls" onclick="return show_panel(this);">TLS (SSL) Certificates</a></li>
<li class="dropdown-item"><a href="#system_backup" onclick="return show_panel(this);">Backup Status</a></li>
<li class="dropdown-item"><a href="#smtp_relays" onclick="return show_panel(this);">SMTP Relays</a></li>
</ul>
</li>
<li class="nav-item me-1 me-xl-4 dropdown if-logged-in-admin">
<button class="btn dropdown-toggle" type="button" data-bs-toggle="dropdown"
aria-expanded="false">Advanced</button>
<li class="btn dropdown if-logged-in-admin">
<a style="color: black;" href="#" class="dropdown-toggle" data-toggle="dropdown">Advanced <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#custom_dns" onclick="return show_panel(this);">Custom
DNS</a></li>
<li><a class="dropdown-item" href="#external_dns"
onclick="return show_panel(this);">External DNS</a></li>
<li><a class="dropdown-item" href="#pgp_keyring" onclick="return show_panel(this);">PGP
Keyring Management</a></li>
<li><a class="dropdown-item" href="#wkd" onclick="return show_panel(this);">WKD
Management</a></li>
<li><a class="dropdown-item" href="#munin" onclick="return show_panel(this);">Munin
Monitoring</a></li>
<li class="dropdown-item"><a href="#custom_dns" onclick="return show_panel(this);">Custom DNS</a></li>
<li class="dropdown-item"><a href="#external_dns" onclick="return show_panel(this);">External DNS</a></li>
<li class="dropdown-item"><a href="#pgp_keyring" onclick="return show_panel(this);">PGP Keyring Management</a></li>
<li class="dropdown-item"><a href="#wkd" onclick="return show_panel(this);">WKD Management</a></li>
<li class="dropdown-item"><a href="#munin" onclick="return show_panel(this);">Munin Monitoring</a></li>
</ul>
</li>
<li class="nav-item me-1 me-xl-4 dropdown if-logged-in-not-admin">
<button class="btn dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">Your Account</button>
<li class="btn if-logged-in-not-admin" style="color: black;" href="#mail-guide" onclick="return show_panel(this);">Mail</li>
<li class="btn dropdown if-logged-in-admin">
<a style="color: black;" href="#" class="dropdown-toggle" data-toggle="dropdown">Mail &amp; Users <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#manage-password" onclick="return show_panel(this);">Manage Password</a></li>
<li><a class="dropdown-item" href="#mfa" onclick="return show_panel(this);">Two-Factor Authentication</a></li>
</ul>
</li>
<li class="nav-item me-1 me-xl-4 btn if-logged-in-not-admin" type="button" href="#mail-guide"
onclick="return show_panel(this);">
Mail Guide
</li>
<li class="nav-item me-1 me-xl-4 dropdown if-logged-in-admin">
<button class="btn dropdown-toggle" type="button" data-bs-toggle="dropdown"
aria-expanded="false">Mail</button>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#mail-guide" onclick="return show_panel(this);">Mail
Guide</a></li>
<li><a class="dropdown-item" href="#users" onclick="return show_panel(this);">Users</a></li>
<li><a class="dropdown-item" href="#aliases" onclick="return show_panel(this);">Aliases</a>
</li>
<li class="dropdown-item"><a href="#mail-guide" onclick="return show_panel(this);">Instructions</a></li>
<li class="dropdown-item"><a href="#users" onclick="return show_panel(this);">Users</a></li>
<li class="dropdown-item"><a href="#aliases" onclick="return show_panel(this);">Aliases</a></li>
<li class="divider"></li>
<li class="dropdown-header">Your Account</li>
<li><a class="dropdown-item" href="#mfa" onclick="return show_panel(this);">Two-Factor
Authentication</a></li>
<li class="dropdown-item"><a href="#mfa" onclick="return show_panel(this);">Two-Factor Authentication</a></li>
</ul>
</li>
<li><button class="nav-item me-1 me-xl-4 btn if-logged-in" type="button" href="#sync_guide"
onclick="return show_panel(this);">Contacts/Calendar</button></li>
<li><button class="nav-item me-1 me-xl-4 btn if-logged-in-admin" type="button" href="#web"
onclick="return show_panel(this);">Web</button></li>
<li><button class="nav-item btn btn-secondary if-logged-in" type="button"
onclick="do_logout(); return false;"><b>Logout</b></button></li>
<li class="btn if-logged-in"><a style="color: black;" href="#sync_guide" onclick="return show_panel(this);">Contacts/Calendar</a></li>
<li class="btn if-logged-in-admin"><a style="color: black;" href="#web" onclick="return show_panel(this);">Web</a></li>
</ul>
</div>
<ul class="btn nav navbar-nav navbar-right">
<li><a class="if-logged-in" href="#" onclick="do_logout(); return false;" style="color: black; font-weight: bold;">Log out</a></li>
</ul>
</div><!--/.navbar-collapse -->
</div>
</div>
@ -205,10 +185,6 @@
{% include "wkd.html" %}
</div>
<div id="panel_manage-password" class="admin_panel">
{% include "manage-password.html" %}
</div>
<div id="panel_mfa" class="admin_panel">
{% include "mfa.html" %}
</div>
@ -248,128 +224,35 @@
<hr>
<footer>
<p>This is a <a href="https://power-mailinabox.net">Power Mail-in-a-Box</a>.</p>
<p>This is a <a href="https://github.com/ddavness/power-mailinabox">Power Mail-in-a-Box</a>.</p>
</footer>
</div> <!-- /container -->
<div id="ajax_loading_indicator"
style="display: none; position: fixed; left: 0; top: 0; width: 100%; height: 100%; z-index: 100000; text-align: center; background-color: rgba(0,0,0,.8)">
<div class="justify-content-center" style="margin: 20%;">
<div class="spinner-border text-light" role="status" style="width: 4rem; height: 4rem;"></div>
<div class="text-light display-5">Loading... please wait!</div>
<div id="ajax_loading_indicator" style="display: none; position: fixed; left: 0; top: 0; width: 100%; height: 100%; z-index: 100000; text-align: center; background-color: rgba(255,255,255,.75)">
<div style="margin: 20% auto">
<div><span class="fa fa-spinner fa-pulse"></span></div>
<div>Loading...</div>
</div>
</div>
<div id="global_modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="errorModalTitle"
aria-hidden="true">
<div class="modal-dialog modal-lg">
<div id="global_modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="errorModalTitle" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="errorModalTitle"> </h4>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-hidden="true"></button>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
</div>
<div class="modal-body">
<p> </p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-bs-dismiss="modal">OK</button>
<button type="button" class="btn btn-danger" data-bs-dismiss="modal">Yes</button>
<button type="button" class="btn btn-default" data-dismiss="modal">OK</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Yes</button>
</div>
</div>
</div>
</div>
<style>
.darkmode,
.darkmode .form-control,
.darkmode .form-select {
background-color: rgb(20, 20, 20) !important;
}
.darkmode .btn-light,
.darkmode .bg-light,
.darkmode .dropdown-menu,
.darkmode .input-group-text,
.darkmode .modal-content,
.darkmode .form-control:disabled,
.darkmode .form-select:disabled {
background-color: rgb(36, 36, 36) !important;
}
.darkmode .form-control,
.darkmode .form-select,
.darkmode .btn-light,
.darkmode .input-group-text,
.darkmode .table,
.darkmode .tr,
.darkmode .thead,
.darkmode .card,
.darkmode .modal-header,
.darkmode .modal-footer {
border-color: rgb(56, 56, 56) !important;
}
.darkmode h3 {
border-color: rgb(206, 212, 218) !important;
}
.darkmode .table>:not(:first-child) {
border-top: 2px solid rgb(206, 212, 218) !important;
}
.darkmode a,
.darkmode b,
.darkmode p,
.darkmode label,
.darkmode span,
.darkmode small,
.darkmode div,
.darkmode td,
.darkmode hr,
.darkmode .form-control,
.darkmode .form-select {
color: rgb(206, 212, 218);
}
.darkmode .btn,
.darkmode h1,
.darkmode h2,
.darkmode h3,
.darkmode h4,
.darkmode h5,
.darkmode .navbar-brand,
.darkmode .dropdown-menu,
.darkmode th,
.darkmode .navbar-brand>span,
.darkmode .navbar-brand>b,
.darkmode .nav-item>*,
.darkmode .input-group-text,
.darkmode .input-group-text>* {
color: rgb(255, 255, 255) !important;
}
.darkmode .btn-close,
.darkmode .navbar-toggler {
filter: invert(97%) sepia(2%) saturate(1242%) hue-rotate(180deg) brightness(93%) contrast(82%);
}
.darkmode .status-error .status-text {
color: rgb(255, 191, 191);
}
.darkmode .status-warning .status-text {
color: rgb(255, 241, 191);
}
.darkmode .status-ok .status-text {
color: rgb(191, 255, 191);
}
.darkmode .status-na .status-text {
color: rgb(155, 155, 155);
}
</style>
<script src="/admin/assets/jquery.min.js"></script>
<script src="/admin/assets/bootstrap/js/bootstrap.bundle.min.js"></script>
@ -377,36 +260,6 @@
var global_modal_state = null;
var global_modal_funcs = null;
const toggle = document.getElementById("toggle-theme")
function set_dark_mode(isdark) {
if (isdark) {
$("body").addClass("darkmode")
} else {
$("body").removeClass("darkmode")
}
}
if (typeof localStorage != 'undefined' && localStorage.getItem("miab-theme-preference")) {
let themepref = localStorage.getItem("miab-theme-preference")
if (themepref === "dark") {
toggle.checked = true
set_dark_mode(true)
} else if (themepref === "light") {
set_dark_mode(false)
}
} else if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
// Toggle dark mode right now
toggle.checked = true
set_dark_mode(true)
}
$("#toggle-theme").change(() => {
if (typeof localStorage != 'undefined') {
localStorage.setItem("miab-theme-preference", toggle.checked ? "dark" : "light")
}
set_dark_mode(toggle.checked)
})
$(function() {
$('#global_modal').on('shown.bs.modal', function (e) {
// set focus to first input in the global modal's body
@ -430,30 +283,32 @@
})
})
const global_modal = new bootstrap.Modal($("#global_modal"))
function show_modal_error(title, message, callback) {
$('#global_modal h4').text(title);
$('#global_modal .modal-body').html("<p/>");
if (typeof question == 'string') {
$('#global_modal p').text(message);
$('#global_modal .modal-dialog').addClass("modal-sm");
} else {
$('#global_modal p').html("").append(message);
$('#global_modal .modal-dialog').removeClass("modal-sm");
}
$('#global_modal .btn-default').show().text("OK");
$('#global_modal .btn-danger').hide();
global_modal_funcs = [callback, callback];
global_modal_state = null;
global_modal.show();
$('#global_modal').modal({});
return false; // handy when called from onclick
}
function show_modal_confirm(title, question, verb, yes_callback, cancel_callback) {
$('#global_modal h4').text(title);
if (typeof question == 'string') {
$('#global_modal .modal-dialog').addClass("modal-sm");
$('#global_modal .modal-body').html("<p/>");
$('#global_modal p').text(question);
} else {
$('#global_modal .modal-dialog').removeClass("modal-sm");
$('#global_modal .modal-body').html("").append(question);
}
if (typeof verb == 'string') {
@ -465,7 +320,7 @@
}
global_modal_funcs = [yes_callback, cancel_callback];
global_modal_state = null;
global_modal.show();
$('#global_modal').modal({});
return false; // handy when called from onclick
}
@ -556,8 +411,9 @@
statusCode: {
403: function(xhr) {
// Credentials are no longer valid. Try to login again.
do_logout();
switch_back_to_panel = null;
var p = current_panel;
show_panel('login');
switch_back_to_panel = p;
}
}
})

View file

@ -1,11 +1,11 @@
<style>
.title {
margin: 0.5em;
margin: 1em;
text-align: center;
}
.subtitle {
margin: 1em;
margin: 2em;
text-align: center;
}
@ -27,8 +27,7 @@
{% if no_users_exist or no_admins_exist %}
<div class="row">
<div class="col-12">
<hr>
<div class="col-md-offset-2 col-md-8">
{% if no_users_exist %}
<p class="text-danger">There are no users on this system! To make an administrative user,
log into this machine using SSH (like when you first set it up) and run:</p>
@ -50,29 +49,37 @@ sudo management/cli.py user make-admin me@{{hostname}}</pre>
<div class="login">
<form id="loginForm" class="form-horizontal" role="form" onsubmit="do_login(); return false;" method="get">
<div class="form-floating mb-3">
<input type="email" class="form-control col-sm-12" id="loginEmail" placeholder="user@example.com">
<label for="loginEmail">Email</label>
</div>
<div class="form-floating mb-3">
<input type="password" class="form-control col-sm-12" id="loginPassword" placeholder="password">
<label for="loginPassword">Password</label>
</div>
<div class="form-floating mb-3" id="loginOtp">
<input type="text" class="form-control" id="loginOtpInput" placeholder="000000" autocomplete="off">
<label for="loginOtpInput">TOTP Code</label>
<div class="help-block" style="margin-top: 5px; font-size: 90%">Enter the six-digit code generated by your two
factor authentication app.</div>
</div>
<div class="form-group mb-3">
<div class="ms-auto">
<input type="checkbox" class="form-check-input" id="loginRemember">
<label class="form-check-label" for="loginRemember">Remember Me</label>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label">Email</label>
<div class="col-sm-12">
<input name="email" type="email" class="form-control" id="loginEmail" placeholder="Email">
</div>
</div>
<div class="form-group">
<div class="container-fluid">
<button type="submit" class="btn btn-primary col-12">Sign in</button>
<label for="inputPassword3" class="col-sm-3 control-label">Password</label>
<div class="col-sm-12">
<input name="password" type="password" class="form-control" id="loginPassword" placeholder="Password">
</div>
</div>
<div class="form-group" id="loginOtp">
<label for="loginOtpInput" class="col-sm-3 control-label">Code</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="loginOtpInput" placeholder="6-digit code" autocomplete="off">
<div class="help-block" style="margin-top: 5px; font-size: 90%">Enter the six-digit code generated by your two factor authentication app.</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-9">
<div class="checkbox">
<label>
<input name='remember' type="checkbox" id="loginRemember"> Remember me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-9">
<button type="submit" class="btn btn-default">Sign in</button>
</div>
</div>
</form>
@ -134,11 +141,9 @@ sudo management/cli.py user make-admin me@{{hostname}}</pre>
// Login succeeded.
// Save the new credentials.
api_credentials = {
username: response.email,
api_credentials = { username: response.email,
session_key: response.api_key,
privileges: response.privileges
};
privileges: response.privileges };
// Try to wipe the username/password information.
$('#loginEmail').val('');

View file

@ -1,9 +1,4 @@
<style>
#panel_mail-guide table.table {
width: auto;
margin-left: .5em;
}
</style>
<style>#panel_mail-guide table.table { width: auto; margin-left: .5em; }</style>
<div>
<h2 style="margin-bottom: 0">Checking and Sending Mail</h2>
@ -13,8 +8,7 @@
<h3>Webmail</h3>
<p>Webmail lets you check your email from any web browser. Your webmail site is:</p>
<p style="margin-left: 2em"><strong><a
href="https://{{hostname}}/mail">https://{{hostname}}/mail</a></strong></p>
<p style="margin-left: 2em"><strong><a href="https://{{hostname}}/mail">https://{{hostname}}/mail</a></strong></p>
<p>Your username is your whole email address.</p>
@ -22,83 +16,40 @@
<h4>Automatic configuration</h4>
<p>iOS and OS X only: Open <a style="font-weight: bold"
href="https://{{hostname}}/mailinabox.mobileconfig">this configuration link</a> on your iOS device
or on your Mac desktop to easily set up mail (IMAP/SMTP), Contacts, and Calendar. Your username is your
whole email address.</p>
<p>iOS and OS X only: Open <a style="font-weight: bold" href="https://{{hostname}}/mailinabox.mobileconfig">this configuration link</a> on your iOS device or on your Mac desktop to easily set up mail (IMAP/SMTP), Contacts, and Calendar. Your username is your whole email address.</p>
<h4>Manual configuration</h4>
<p>Use the following settings when you set up your email on your phone, desktop, or other device:</p>
<table class="table">
<caption></caption>
<thead>
<tr>
<th>Option</th>
<th>Value</th>
</tr>
<tr><th>Option</th> <th>Value</th></tr>
</thead>
<tr>
<th>Protocol/Method</th>
<td>IMAP</td>
</tr>
<tr>
<th>Mail server</th>
<td>{{hostname}}</td>
<tr>
<th>IMAP Port</th>
<td>993</td>
</tr>
<tr>
<th>IMAP Security</th>
<td>SSL or TLS</td>
</tr>
<tr>
<th>SMTP Port</th>
<td>465</td>
</tr>
<tr>
<th>SMTP Security</td>
<td>SSL or TLS</td>
</tr>
<tr>
<th>Username:</th>
<td>Your whole email address.</td>
</tr>
<tr>
<th>Password:</th>
<td>Your mail password.</td>
</tr>
<tr><th>Protocol/Method</th> <td>IMAP</td></tr>
<tr><th>Mail server</th> <td>{{hostname}}</td>
<tr><th>IMAP Port</th> <td>993</td></tr>
<tr><th>IMAP Security</th> <td>SSL or TLS</td></tr>
<tr><th>SMTP Port</th> <td>465</td></tr>
<tr><th>SMTP Security</td> <td>SSL or TLS</td></tr>
<tr><th>Username:</th> <td>Your whole email address.</td></tr>
<tr><th>Password:</th> <td>Your mail password.</td></tr>
</table>
<p>In addition to setting up your email, you&rsquo;ll also need to set up <a href="#sync_guide"
onclick="return show_panel(this);">contacts and calendar synchronization</a> separately.</p>
<p>In addition to setting up your email, you&rsquo;ll also need to set up <a href="#sync_guide" onclick="return show_panel(this);">contacts and calendar synchronization</a> separately.</p>
<p>As an alternative to IMAP you can also use the POP protocol: choose POP as the protocol, port 995, and
SSL or TLS security in your mail client. The SMTP settings and usernames and passwords remain the same.
However, we recommend you use IMAP instead.</p>
<p>As an alternative to IMAP you can also use the POP protocol: choose POP as the protocol, port 995, and SSL or TLS security in your mail client. The SMTP settings and usernames and passwords remain the same. However, we recommend you use IMAP instead.</p>
<h4>Exchange/ActiveSync settings</h4>
<p>On iOS devices, devices on this <a href="https://wiki.z-hub.io/display/ZP/Compatibility">compatibility
list</a>, or using Outlook 2007 or later on Windows 7 and later, you may set up your mail as an
Exchange or ActiveSync server. However, we&rsquo;ve found this to be more buggy than using IMAP as
described above. If you encounter any problems, please use the manual settings above.</p>
<p>On iOS devices, devices on this <a href="https://wiki.z-hub.io/display/ZP/Compatibility">compatibility list</a>, or using Outlook 2007 or later on Windows 7 and later, you may set up your mail as an Exchange or ActiveSync server. However, we&rsquo;ve found this to be more buggy than using IMAP as described above. If you encounter any problems, please use the manual settings above.</p>
<table class="table">
<tr>
<th>Server</th>
<td>{{hostname}}</td>
</tr>
<tr>
<th>Options</th>
<td>Secure Connection</td>
</tr>
<tr><th>Server</th> <td>{{hostname}}</td></tr>
<tr><th>Options</th> <td>Secure Connection</td></tr>
</table>
<p>Your device should also provide a contacts list and calendar that syncs to this box when you use this
method.</p>
<p>Your device should also provide a contacts list and calendar that syncs to this box when you use this method.</p>
</div>
<div class="col-sm-5">
@ -108,24 +59,13 @@
</div>
<div class="panel-body">
<h4>Greylisting</h4>
<p>Your box uses a technique called greylisting to cut down on spam. Greylisting works by initially
rejecting mail from people you haven&rsquo;t received mail from before. Legitimate mail servers
will attempt redelivery shortly afterwards, but the vast majority of spam gets tricked by this.
If you are waiting for an email from someone new, such as if you are registering on a new
website and are waiting for an email confirmation, please be aware there will be a minimum of 3
minutes delay, depending how soon the remote server attempts redelivery.</p>
<p>Your box uses a technique called greylisting to cut down on spam. Greylisting works by initially rejecting mail from people you haven&rsquo;t received mail from before. Legitimate mail servers will attempt redelivery shortly afterwards, but the vast majority of spam gets tricked by this. If you are waiting for an email from someone new, such as if you are registering on a new website and are waiting for an email confirmation, please be aware there will be a minimum of 3 minutes delay, depending how soon the remote server attempts redelivery.</p>
<h4>+tag addresses</h4>
<p>Every incoming email address also receives mail for <code>+tag</code> addresses. If your email
address is <code>you@yourdomain.com</code>, you&rsquo;ll also automatically get mail sent to
<code>you+anythinghere@yourdomain.com</code>. Use this as a fast way to segment incoming mail
for your own filtering rules without having to create aliases in this control panel.</p>
<p>Every incoming email address also receives mail for <code>+tag</code> addresses. If your email address is <code>you@yourdomain.com</code>, you&rsquo;ll also automatically get mail sent to <code>you+anythinghere@yourdomain.com</code>. Use this as a fast way to segment incoming mail for your own filtering rules without having to create aliases in this control panel.</p>
<h4>Use only this box to send as you</h4>
<p>Your box sets strict email sending policies for your domain names to make it harder for spam and
other fraudulent mail to claim to be you. Only this machine is authorized to send email on
behalf of your domain names. If you use any other service to send email as you, it will likely
get spam filtered by recipients.</p>
<p>Your box sets strict email sending policies for your domain names to make it harder for spam and other fraudulent mail to claim to be you. Only this machine is authorized to send email on behalf of your domain names. If you use any other service to send email as you, it will likely get spam filtered by recipients.</p>
</div>
</div>
</div>

View file

@ -1,57 +0,0 @@
<div>
<h2>Manage Password</h2>
<p>Here you can change your account password. The new password is then valid for both this panel and your email.</p>
<p>If you have client emails configured, you'll then need to update the configuration with the new password. See the <a href="#mail-guide" onclick="return show_panel(this);">Mail Guide</a> for more information about this.</p>
<form class="form-horizontal" role="form" onsubmit="set_password_self(); return false;">
<div class="col-lg-10 col-xl-8 mb-3">
<div class="input-group">
<label for="manage-password-new" class="input-group-text col-3">New Password</label>
<input type="password" placeholder="password" class="form-control" id="manage-password-new">
</div>
</div>
<div class="col-lg-10 col-xl-8 mb-3">
<div class="input-group">
<label for="manage-password-confirm" class="input-group-text col-3">Confirm Password</label>
<input type="password" placeholder="password" class="form-control" id="manage-password-confirm">
</div>
</div>
<div class="mt-3">
<button id="manage-password-submit" type="submit" class="btn btn-primary">Save</button>
</div>
<small>After changing your password, you'll be logged out from the account and will need to log in again.</small>
</form>
</div>
<script>
function set_password_self() {
if ($('#manage-password-new').val() !== $('#manage-password-confirm').val()) {
show_modal_error("Set Password", 'Passwords do not match!');
return;
}
let password = $('#manage-password-new').val()
api(
"/mail/users/password",
"POST",
{
email: api_credentials.username,
password: password
},
function (r) {
// Responses are multiple lines of pre-formatted text.
show_modal_error("Set Password", $("<pre/>").text(r), () => {
do_logout()
$('#manage-password-new').val("")
$('#manage-password-confirm').val("")
});
},
function (r) {
show_modal_error("Set Password", r);
}
);
}
</script>

View file

@ -36,13 +36,12 @@
<p>When two-factor authentication is enabled, you will be prompted to enter a six digit code from an
authenticator app (usually on your phone) when you log into this control panel.</p>
<div class="card mb-4">
<div class="card">
<div class="card-header text-white bg-danger">
Enabling two-factor authentication does not protect access to your email
</div>
<div class="card-body bg-light">
Enabling two-factor authentication on this page only limits access to this control panel. Remember that most
websites allow you to
Enabling two-factor authentication on this page only limits access to this control panel. Remember that most websites allow you to
reset your password by checking your email, so anyone with access to your email can typically take over
your other accounts. Additionally, if your email address or any alias that forwards to your email
address is a typical domain control validation address (e.g admin@, administrator@, postmaster@, hostmaster@,
@ -57,64 +56,54 @@
<form id="totp-setup">
<h3>Setup Instructions</h3>
<div class="row gx-5">
<div class="col-12 col-lg-6">
<p><b>1.</b> Install <a href="https://freeotp.github.io/">FreeOTP</a> or <a
href="https://www.pcworld.com/article/3225913/what-is-two-factor-authentication-and-which-2fa-apps-are-best.html">any
<div class="form-group">
<p>1. Install <a href="https://freeotp.github.io/">FreeOTP</a> or <a href="https://www.pcworld.com/article/3225913/what-is-two-factor-authentication-and-which-2fa-apps-are-best.html">any
other two-factor authentication app</a> that supports TOTP.</p>
<div class="mb-3">
<p style="margin-bottom: 0"><b>2.</b> Scan the QR code in the app or directly enter the secret into
the app:</p>
<div id="totp-setup-qr">
<img class="mt-3 mb-3 ms-auto me-auto" id="twofactor-qrimg">
<div class="input-group">
<label class="input-group-text" for="totp-setup-secret"><b>Secret</b></label>
<input type="text" class="form-control font-monospace" id="totp-setup-secret" disabled />
</div>
</div>
</div>
</div>
<div class="col-12 col-lg-6">
<div class="mb-3">
<label for="otp-label" style="font-weight: normal"><b>3.</b> Optionally, give your device a label so
that you can remember what device you set it up on:</label>
<input type="text" id="totp-setup-label" class="form-control" placeholder="my phone" />
</div>
<div class="mb-3">
<label for="otp" style="font-weight: normal"><b>4.</b> Use the app to generate your first six-digit
code and enter it here:</label>
<input type="text" id="totp-setup-token" class="form-control" placeholder="6-digit code" />
</div>
</div>
</div>
<div class="form-group">
<div>
<button id="totp-setup-submit" disabled type="submit" class="btn btn-primary">Enable Two-Factor
Authentication</button>
<p style="margin-bottom: 0">2. Scan the QR code in the app or directly enter the secret into the app:</p>
<div id="totp-setup-qr"></div>
</div>
<small>When you click Enable Two-Factor Authentication, you will be logged out of the control panel and will
have to log in
again, now using your two-factor authentication app.</small>
<div class="form-group">
<label for="otp-label" style="font-weight: normal">3. Optionally, give your device a label so that you can remember what device you set it up on:</label>
<input type="text" id="totp-setup-label" class="form-control" placeholder="my phone" />
</div>
<div class="form-group">
<label for="otp" style="font-weight: normal">4. Use the app to generate your first six-digit code and enter it here:</label>
<input type="text" id="totp-setup-token" class="form-control" placeholder="6-digit code" />
</div>
<input type="hidden" id="totp-setup-secret" />
<div class="form-group">
<p>When you click Enable Two-Factor Authentication, you will be logged out of the control panel and will have to log in
again, now using your two-factor authentication app.</p>
<button id="totp-setup-submit" disabled type="submit" class="btn btn-primary">Enable Two-Factor Authentication</button>
</div>
</form>
<form id="disable-2fa">
<div>
<p>Two-factor authentication is active for your account<span id="mfa-device-label"> on device <span
class="font-monospace"></span></span>.</p>
<div class="form-group">
<p>Two-factor authentication is active for your account<span id="mfa-device-label"></span>.</p>
<p>You will have to log into the admin panel again after disabling two-factor authentication.</p>
</div>
<div class="form-group">
<button type="submit" class="btn btn-danger">Disable Two-Factor Authentication</button>
</div>
<small>You will have to log into the admin panel again after disabling two-factor authentication.</small>
</form>
<div id="output-2fa" class="card bg-light">
<div class="card-body"></div>
</div>
</div>
<script>
var el = {
disableForm: document.getElementById('disable-2fa'),
output: document.getElementById('output-2fa'),
totpSetupForm: document.getElementById('totp-setup'),
totpSetupToken: document.getElementById('totp-setup-token'),
totpSetupSecret: document.getElementById('totp-setup-secret'),
@ -141,9 +130,14 @@
}
function render_totp_setup(provisioned_totp) {
$('#twofactor-qrimg').attr("src", "data:image/png;base64," + provisioned_totp.qr_code_base64);
var img = document.createElement('img');
img.src = "data:image/png;base64," + provisioned_totp.qr_code_base64;
el.totpSetupSecret.val = provisioned_totp.secret;
var code = document.createElement('div');
code.innerHTML = `Secret: ${provisioned_totp.secret}`;
el.totpQr.appendChild(img);
el.totpQr.appendChild(code);
el.totpSetupToken.addEventListener('input', update_setup_disabled);
el.totpSetupForm.addEventListener('submit', do_enable_totp);
@ -156,12 +150,18 @@
function render_disable(mfa) {
el.disableForm.addEventListener('submit', do_disable);
el.wrapper.classList.add('enabled');
if (mfa.label) {
$("#mfa-device-label").show()
$("#mfa-device-label .font-monospace").text(mfa.label);
} else {
$("#mfa-device-label").hide()
if (mfa.label)
$("#mfa-device-label").text(" on device '" + mfa.label + "'");
}
function hide_error() {
el.output.querySelector('.card-body').innerHTML = '';
el.output.classList.remove('visible');
}
function render_error(msg) {
el.output.querySelector('.card-body').innerHTML = msg;
el.output.classList.add('visible');
}
function reset_view() {
@ -169,6 +169,8 @@
el.disableForm.removeEventListener('submit', do_disable);
hide_error();
el.totpSetupForm.reset();
el.totpSetupForm.removeEventListener('submit', do_enable_totp);
@ -176,9 +178,7 @@
el.totpSetupToken.removeEventListener('input', update_setup_disabled);
el.totpSetupSubmit.setAttribute('disabled', '');
$('#twofactor-qrimg').attr("src", "");
$('#totp-setup-secret').attr("value", "");
el.totpQr.innerHTML = '';
}
function show_mfa() {
@ -207,6 +207,7 @@
function do_disable(evt) {
evt.preventDefault();
hide_error();
api(
'/mfa/disable',
@ -222,6 +223,7 @@
function do_enable_totp(evt) {
evt.preventDefault();
hide_error();
api(
'/mfa/totp/enable',
@ -232,7 +234,7 @@
label: $(el.totpSetupLabel).val()
},
function(res) { do_logout(); },
function (res) { show_modal_error("Two-Factor Authentication Setup", res); }
function(res) { render_error(res); }
);
return false;

View file

@ -1,10 +1,22 @@
<style>
#pgp_keyring_config .icon {
min-width: 2em;
#pgp_keyring_config .status-error {
color: rgb(140, 0, 0);
}
.inline {
display: inline;
#pgp_keyring_config .status-warning {
color: rgb(170, 120, 0);
}
#pgp_keyring_config .status-ok {
color: rgb(0, 140, 0);
}
#pgp_keyring_config .status-none {
color: rgb(190, 190, 190);
}
#pgp_keyring_config #uids {
white-space: pre-line;
}
</style>
@ -12,51 +24,47 @@
<template id="pgpkey-template">
<tr>
<td class="row p-3">
<div class="col-lg-10 col-12">
<b id="isrevoked" class="fs-4"></b>
<div id="uids" class="mb-3 font-monospace">
<div id="uid-template">
<span class="icon fas"></span><span id="id" class="status-text"></span>
</div>
</div>
<b class="fs-5">Subkeys</b>
<div id="subkeys" class="align-middle col-12">
<div class="row" id="subkey-template">
<div style="width: 2em;" id="ismaster" data-bs-toggle="tooltip" title="Master Key"></div>
<div style="width: 5em;">
<td>
<div id="trustlevel" style="font-size: 14pt;"><b>Trust Level:</b> Ultimate</div>
<code id="uids">
🤖 Power Mail-in-a-Box Management Daemon &lt;administrator@mailinabox.lan&gt;
</code>
<h3 style="font-size: 12pt;">Subkeys</h3>
<table id="subkeys">
<tr id="subkey-template">
<td id="ismaster">🔑</td>
<td>
<b>
<span class="sym" id="sign">S</span>
<span class="sym" id="cert">C</span>
<span class="sym" id="encr">E</span>
<span class="sym" id="auth">A</span>
<a id="sign">S</a>
<a id="cert">C</a>
<a id="encr">E</a>
<a id="auth">A</a>
</b>
</div>
<div class="col-md-2 col-4" id="algo">
<b class="status-text"></b>
</div>
<div class="col" id="expiration">
<span class="status-text"></span>
</div>
<div class="col-md-6 col-12" id="fpr">
<span class="status-text font-monospace"></span>
</div>
</div>
</div>
</div>
<div id="options" class="col-lg-2 col-12">
</div>
</td>
<td style="width: 120pt;">
<b id="algo">RSA, 3072 bit</b>
</td>
<td>
<pre id="fpr">1756 6B81 D8A4 24C7 0098 659E 6872 2633 F692 52C6</pre>
</td>
<td id="expiration">
12/12/20 (119 days)
</td>
</tr>
</table>
</td>
<td id="options" style="width: 140pt;">
</td>
</tr>
</template>
<div id="pgp_keyring_config">
<h3>Daemon's Private Key</h3>
<table id="privatekey" class="container">
<table id="privatekey" class="table container">
</table>
<h3>Imported Public Keys</h3>
<table id="pubkeys" class="container">
<table id="pubkeys" class="table container">
</table>
<h3>Import Key</h3>
@ -66,32 +74,28 @@
If you're using <code>gpg</code>, you can export your public key by following this example:
<pre>
# Get all the keys in the ring
$ <b>gpg --list-keys</b>
<b>$ gpg --list-keys</b>
/home/you/.gnupg/pubring.kbx
----------------------------
pub rsa4096 1970-01-01 [SC]
247C3553B4B36107BA0490C3CAFCCF3B4965761A
uid [ full ] Someone That I Used to Know &lt;someone@example.com&gt;
sub rsa2048 2020-01-01 [E] [expires: 2069-12-31]
sub rsa2048 2020-01-01 [E] [expires: 2021-01-01]
pub rsa4096 1970-01-01 [SC] [expires: 2069-12-31]
pub rsa4096 2020-05-24 [SC] [expires: 2021-02-12]
52661092E5CD9EEFD7796B19E85F540C9318B69F
uid [ultimate] Me, Myself and I &lt;me@example.net&gt;
sub rsa2048 2020-05-24 [E] [expires: 2069-12-31]
uid [ultimate] Me, Myself and I &lt;me@mydomain.com&gt;
sub rsa2048 2020-05-24 [E] [expires: 2021-02-12]
# Let's export the key "Me, Myself and I"
$ <b>gpg --export --armor 52661092E5CD9EEFD7796B19E85F540C9318B69F</b>
# Say that we want to export our own key, this is - "Me, Myself and I". That's the fingerprint "52661..."
<b>$ gpg --export --armor 52661092E5CD9EEFD7796B19E85F540C9318B69F</b> # Replace with your key's fingerprint
<b>-----BEGIN PGP PUBLIC KEY BLOCK-----
copy and paste this block in the area below
-----END PGP PUBLIC KEY BLOCK-----</b>
</pre>
</p>
<div class="form-floating col-12 col-xl-6 mb-3">
<textarea id="pgp_paste_key" class="form-control" style="font-size:80%; font-family: monospace; height: 20em"
placeholder="-----BEGIN PGP PUBLIC KEY BLOCK-----&#xA;stuff here&#xA;-----END PGP PUBLIC KEY BLOCK-----"></textarea>
<label for="pgp_paste_key">Paste your PGP public key here</label>
</div>
<p><textarea id="pgp_paste_key" class="form-control" style="max-width: 40em; height: 8em" placeholder="-----BEGIN PGP PUBLIC KEY BLOCK-----&#xA;stuff here&#xA;-----END PGP PUBLIC KEY BLOCK-----"></textarea></p>
<button class="btn btn-primary" onclick="importkey()">Import Key</button>
</div>
@ -110,7 +114,6 @@ copy and paste this block in the area below
function key_html(key, darken_bg, daemon) {
let keyrep = $("#pgpkey-template").html()
console.log(keyrep)
keyrep = $(keyrep)
keyrep.attr("id", key.master_fpr)
@ -119,30 +122,24 @@ copy and paste this block in the area below
keyrep.addClass("bg-light")
}
let rev = keyrep.find("#isrevoked")
const tlevel = keyrep.find("#trustlevel")
if (key.revoked) {
rev.text("This key was revoked by it's owner.")
rev.addClass(".status-error")
tlevel.html("<b class='status-error'>This key was revoked by it's owner.</b>")
} else {
rev.text("Key is not revoked.")
tlevel.html("<b>Key is not revoked.</b>")
}
let uids = keyrep.find("#uids")
let uidtemplate = $(uids.html())
uids.find("#uid-template").remove()
let uidtxt = ""
if (daemon) {
uidtemplate.find(".icon").addClass("fa-robot")
} else {
uidtemplate.find(".icon").addClass("fa-user")
}
key.ids.forEach(id => {
let thisuid = uidtemplate.clone()
thisuid.attr("id", "")
thisuid.find("#id").text(id)
thisuid.appendTo(uids)
uidtxt += "🤖 " + id + "\n"
});
} else {
key.ids.forEach(id => {
uidtxt += "🕵 " + id + "\n"
});
}
keyrep.find("#uids").text(uidtxt.substring(0, uidtxt.length - 1))
// Subkeys
const keyflags = ["sign", "cert", "encr", "auth"]
@ -153,56 +150,50 @@ copy and paste this block in the area below
let skeyrep = $(subkeytemplate)
skeyrep.attr("id", `sub${skey.fpr}`)
let statusclass
let expiration = skeyrep.find("#expiration")
let exptxt = expiration.find(".status-text")
if (key.revoked) {
statusclass = "status-error"
exptxt.text("Revoked")
} else if (skey.expired) {
statusclass = "status-error"
exptxt.text(`${skey.expires_date} (expired)`)
} else if (skey.expires && skey.expires_days <= 14) {
statusclass = "status-warning"
exptxt.text(`${skey.expires_date} (${skey.expires_days} days)`)
} else if (skey.expires) {
statusclass = "status-ok"
exptxt.text(`${skey.expires_date} (${skey.expires_days} days)`)
} else {
statusclass = "status-ok"
exptxt.text("Does not expire")
}
expiration.addClass(statusclass)
// Master key?
if (skey.master) {
skeyrep.find("#ismaster").addClass("fas fa-key")
skeyrep.find("#ismaster").html("🔑")
} else {
skeyrep.find("#ismaster").html("")
}
// Usage flags
keyflags.forEach(flag => {
skeyrep.find(`#${flag}`).addClass(skey[flag] ? statusclass : "status-na")
if (!skey[flag]) {
skeyrep.find(`#${flag}`).addClass("status-none")
}
});
// Algorithm and fingerprint
let algo = skeyrep.find("#algo")
algo.addClass(statusclass)
algo.find(".status-text").html(`${skey.algorithm}, ${skey.bits} bits`)
let fpr = skeyrep.find("#fpr")
fpr.addClass(statusclass)
fpr.find(".status-text").html(pretty_fpr(skey.fpr))
skeyrep.find("#algo").html(`${skey.algorithm}, ${skey.bits} bits`)
skeyrep.find("#fpr").html(pretty_fpr(skey.fpr))
let expiration = skeyrep.find("#expiration")
// Expiration
if (key.revoked) {
skeyrep.addClass("status-error")
expiration.html(`Revoked`)
} else if (skey.expired) {
skeyrep.addClass("status-error")
expiration.html(`${skey.expires_date} (expired)`)
} else if (skey.expires && skey.expires_days <= 14) {
skeyrep.addClass("status-warning")
expiration.html(`${skey.expires_date} (${skey.expires_days} days)`)
} else if (skey.expires) {
skeyrep.addClass("status-ok")
expiration.html(`${skey.expires_date} (${skey.expires_days} days)`)
} else {
skeyrep.addClass("status-ok")
expiration.html("Does not expire")
}
skeyrep.appendTo(subkeys)
});
// Options
if (daemon) {
keyrep.find("#options").html(`<button class="btn btn-primary col-12" onclick="exportkey('${key.master_fpr}')">Export Public Key</button>`)
keyrep.find("#options").html(`<button class="btn btn-primary btn-block" onclick="exportkey('${key.master_fpr}')">Export Public Key</button>`)
} else {
keyrep.find("#options").html(`<button class="btn btn-secondary col-12 mb-3" onclick="exportkey('${key.master_fpr}')">Export Public Key</button><button class="btn btn-danger col-12" onclick="rmkey('${key.master_fpr}')">Remove Key</button>`)
keyrep.find("#options").html(`<button class="btn btn-secondary btn-block" onclick="exportkey('${key.master_fpr}')">Export Public Key</button><button class="btn btn-danger btn-block" onclick="rmkey('${key.master_fpr}')">Remove Key</button>`)
}
return keyrep

View file

@ -15,40 +15,66 @@
<div id="smtp_relay_config">
<form class="form-horizontal" role="form" onsubmit="set_smtp_relay_config(); return false;">
<h3>SMTP Relay Configuration</h3>
<div id="smtp-relays" class="col-12">
<div class="input-group mb-3">
<label for="use_relay" class="input-group-text"><b>Use Relay?</b></label>
<div class="input-group-text">
<div class="form-switch">
<input type="checkbox" role="switch" id="use_relay" class="form-check-input" value=false
onclick="checkfields();">
</div>
</div>
</div>
<div class="input-group mb-3">
<label class="input-group-text">Where to?</label>
<input type="text" class="form-control" id="relay_host" placeholder="relay.example.com">
<label class="input-group-text">:</label>
<div style="width: 20%">
<input type="number" class="form-control" id="relay_port" placeholder="Port (465)">
</div>
</div>
<div class="input-group mb-3">
<label class="input-group-text">Username</label>
<input type="text" class="form-control" id="relay_auth_user" placeholder="">
</div>
<div class="form-group">
<table id="smtp-relays" class="table" style="width: 100%">
<tr>
<td style="width: 15%;">
<label for="use_relay" class="col-sm-1 control-label"
style="vertical-align: middle; white-space: nowrap;"><b>Use Relay?</b></label>
</td>
<td>
<div class="col-sm-10">
<input type="checkbox" id="use_relay" name="use_relay" value=false onclick="checkfields();">
</div>
</td>
</tr>
<tr>
<td style="width: 15%;">
<label for="relay_host" class="col-sm-1 control-label"
style="vertical-align: middle; white-space: nowrap;">Hostname</label>
</td>
<td>
<div>
<div class="input-group">
<label class="input-group-text">Password/Key</label>
<input type="password" class="form-control" id="relay_auth_pass" placeholder="">
<input type="text" class="form-control" id="relay_host" placeholder="relay.example.net">
</div>
<p class="small">If you've already set up a relay before on this box, you can leave this field blank if
you don't want to change it's password.</p>
</td>
<td style="padding: 0; font-weight: bold; vertical-align: middle; white-space: nowrap;">:</td>
<td style="width: 20%;">
<div>
<input type="number" class="form-control" id="relay_port" min="1" max="65535" step="1"
value="465">
</div>
</td>
</tr>
<tr>
<td style="width: 15%;">
<label for="relay_auth_user" class="col-sm-1 control-label"
style="vertical-align: middle; white-space: nowrap;">Username</label>
</td>
<td>
<div>
<input type="text" class="form-control" id="relay_auth_user" placeholder="user">
</div>
</td>
</tr>
<tr>
<td style="width: 15%;">
<label for="relay_auth_pass" class="col-sm-1 control-label"
style="vertical-align: middle; white-space: nowrap;">Password/Key</label>
</td>
<td>
<div>
<input type="password" class="form-control" id="relay_auth_pass" placeholder="password">
</div>
<p class="small">If you've already set up a relay before on this box, you can leave this field
blank if you don't want to change it's password.</p>
</td>
</tr>
</table>
</div>
<h3>Authorized Servers</h3>
@ -72,33 +98,36 @@
placeholder="mail1.example.net mail2.example.net">
<p class="small">You can separate multiple servers with commas or spaces. You can also add IP addresses or
subnets using <code>10.20.30.40</code> or <code>10.0.0.0/8</code>. You can "import" SPF records using
<code>spf:example.com</code>. If your provider gave you an SPF record to add to your DNS, you can also paste it here.
<code>spf:example.com</code>.
</p>
</div>
<h3>DKIM Configuration</h3>
<p>DKIM allows receivers to verify that the email was sent by the relay you configured (this is, somebody you
trust). <b>If your relay provider does not provide you with this information, it's probably safe to skip this step.</b></p>
trust). <b>Not doing so will have your email sent to spam.</b></p>
<div class="col-lg-6 col-md-8 col-12">
<div class="input-group">
<input type="text" class="form-control" id="relay_dkim_selector" placeholder="selector"></td>
<label class="input-group-text" for="relay_dkim_selector">._domainkey.{{hostname}}</label>
</div>
</div>
<div class="form-group">
<table style="width: 100%">
<tr>
<td style="width: 15%;"><input type="text" style="text-align: right;" class="form-control"
id="relay_dkim_selector" placeholder="selector"></td>
<td><b>._domainkey.{{hostname}}</b></td>
</tr>
</table>
<h4>Paste the DKIM key here:</h4>
<p><textarea id="relay_dkim_key" class="form-control" style="width: 100%; height: 8em"
placeholder="k=algo;p=K3y/C0N7ent5/dGhpcyBpcyBub3QgYSByZWFsIGtleSwgc28gYmV3YXJlIDrigb4"></textarea>
</p>
<div>
<button type="submit" class="btn btn-primary">Update</button>
</div>
<h3>After configuration</h3>
<p>By that time you should be good to go. If your relay provider provides their own custom DNS verification
methods (<b>including custom DMARC configurations</b>), feel free to publish them on DNS.</p>
methods, feel free to publish them on DNS.</p>
<div>
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
</div>
@ -145,13 +174,9 @@
relay_auth_pass.value = ""
relay_authorized_servers.value = ""
if (data.spf_record) {
relay_authorized_servers.value = data.spf_record
}else if (data.authorized_servers) {
data.authorized_servers.forEach(element => {
relay_authorized_servers.value += `${element} `
});
}
if (data.dkim_selector) {
relay_dkim_sel.value = data.dkim_selector
@ -164,25 +189,19 @@
}
function set_smtp_relay_config() {
let relay_configuration = {
api(
"/system/smtp/relay",
"POST",
{
enabled: use_relay.checked,
host: relay_host.value,
port: relay_port.value,
user: relay_auth_user.value,
key: relay_auth_pass.value,
authorized_servers: relay_authorized_servers.value,
dkim_selector: relay_dkim_sel.value,
dkim_rr: relay_dkim_key.value
}
if (relay_authorized_servers.value.substr(0, 7) === "v=spf1 ") {
relay_configuration.spf_record = relay_authorized_servers.value
} else {
relay_configuration.authorized_servers = relay_authorized_servers.value
}
api(
"/system/smtp/relay",
"POST",
relay_configuration,
},
() => {
show_modal_error("Done!", "The configuration has been updated and Postfix was restarted successfully. Please make sure everything is functioning as intended.", () => {
return false

View file

@ -1,56 +1,37 @@
<style>
.code-white>code {
color: #ffffff
}
#ssl_provision_result>div>div {
white-space: pre;
}
#ssl_domains .icon {
min-width: 1.6em;
}
</style>
<h2>TLS (SSL) Certificates</h2>
<p>A TLS (formerly called SSL) certificate is a cryptographic file that proves to anyone connecting to a web address
that the connection is secure between you and the owner of that address.</p>
<p>A TLS (formerly called SSL) certificate is a cryptographic file that proves to anyone connecting to a web address that the connection is secure between you and the owner of that address.</p>
<p>You need a TLS certificate for this box&rsquo;s hostname ({{hostname}}) and every other domain name and subdomain
that this box is hosting a website for (see the list below).</p>
<p>You need a TLS certificate for this box&rsquo;s hostname ({{hostname}}) and every other domain name and subdomain that this box is hosting a website for (see the list below).</p>
<div id="ssl_provision">
<h3>Provision certificates</h3>
<div id="ssl_provision_p" style="display: none; margin-top: 1.5em">
<p>A TLS certificate can be automatically provisioned from <a href="https://letsencrypt.org/"
target="_blank">Let&rsquo;s Encrypt</a>, a free TLS certificate provider, for:</p>
<ul class="text-primary"></ul>
<div class="container input-group mt-3" style="overflow-x: auto;">
<button id="ssl_provision_button" class="btn btn-primary"
onclick="return provision_tls_cert();">Provision</button>
<label class="input-group-text" for=""><b>By provisioning the certificates, you&rsquo;re agreeing to the <a
href="https://letsencrypt.org/repository">Let&rsquo;s Encrypt Subscriber Agreement</a>.</b></label>
</div>
</div>
<button onclick='return provision_tls_cert();' class='btn btn-primary' style="float: left; margin: 0 1.5em 1em 0;">Provision</button>
<p><b>By provisioning the certificates, you&rsquo;re agreeing to the <a href="https://acme-v01.api.letsencrypt.org/terms">Let&rsquo;s Encrypt Subscriber Agreement</a>.</b></p>
<p>A TLS certificate can be automatically provisioned from <a href="https://letsencrypt.org/" target="_blank">Let&rsquo;s Encrypt</a>, a free TLS certificate provider, for:<br>
<span class="text-primary"></span></p>
</div>
<div id="ssl_provision_result" class="mt-4"></div>
<div class="clearfix"> </div>
<div id="ssl_provision_result"></div>
</div>
<h3>Certificate status</h3>
<p style="margin-top: 1.5em">Certificates expire after a period of time. All certificates will be automatically renewed
through <a href="https://letsencrypt.org/" target="_blank">Let&rsquo;s Encrypt</a> 14 days prior to expiration.</p>
<p style="margin-top: 1.5em">Certificates expire after a period of time. All certificates will be automatically renewed through <a href="https://letsencrypt.org/" target="_blank">Let&rsquo;s Encrypt</a> 14 days prior to expiration.</p>
<table id="ssl_domains" class="table align-middle col-12" style="margin-bottom: 2em; display: none">
<caption></caption>
<table id="ssl_domains" class="table" style="margin-bottom: 2em; width: auto; display: none">
<thead>
<tr>
<th>Domain</th>
<th>Certificate Status</th>
<th></th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@ -60,61 +41,41 @@
<h3 id="ssl_install_header">Install certificate</h3>
<p>If you don't want to use our automatic Let's Encrypt integration, you can give any other certificate provider a try.
You can generate the needed CSR below.</p>
<p>If you don't want to use our automatic Let's Encrypt integration, you can give any other certificate provider a try. You can generate the needed CSR below.</p>
<div class="col-lg-10 col-xl-8">
<div class="input-group">
<label class="input-group-text" for="ssldomain">Which domain are you getting a certificate for?</label>
<select id="ssldomain" onchange="show_csr()" class="form-select"></select>
</div>
</div>
<p><small>A multi-domain or wildcard certificate will be automatically applied to any domains it is valid for besides
the one you choose above.</small></p>
<p>Which domain are you getting a certificate for?</p>
<div class="col-lg-10 col-xl-8">
<div class="input-group">
<label class="input-group-text" for="sslcc">What country are you in?</label>
<select id="sslcc" onchange="show_csr()" class="form-select">
<p><select id="ssldomain" onchange="show_csr()" class="form-control" style="width: auto"></select></p>
<p>(A multi-domain or wildcard certificate will be automatically applied to any domains it is valid for besides the one you choose above.)</p>
<p>What country are you in? This is required by some TLS certificate providers. You may leave this blank if you know your TLS certificate provider doesn't require it.</p>
<p><select id="sslcc" onchange="show_csr()" class="form-control" style="width: auto">
<option value="">(Select)</option>
{% for code, name in csr_country_codes %}
<option value="{{code}}">{{name}}</option>
{% endfor %}
</select>
</div>
</div>
<p><small>This is required by some TLS certificate providers. You may just pick any if you know your TLS certificate
provider doesn't require it.</small></p>
</select></p>
<div id="csr_info" style="display: none;">
<div id="csr_info" style="display: none">
<p>You will need to provide the certificate provider this Certificate Signing Request (CSR):</p>
<div class="col-lg-10 col-xl-8 mb-3">
<textarea class="form-control font-monospace" id="ssl_csr" style="min-height: 26.5em;" readonly></textarea>
</div>
<pre id="ssl_csr"></pre>
<small>The CSR is safe to share. It can only be used in combination with a secret key stored on this machine.</small>
<p><small>The CSR is safe to share. It can only be used in combination with a secret key stored on this machine.</small></p>
<p>The certificate provider will then provide you with a TLS/SSL certificate. They may also provide you with an
intermediate chain. Paste each separately into the boxes below:</p>
<p>The certificate provider will then provide you with a TLS/SSL certificate. They may also provide you with an intermediate chain. Paste each separately into the boxes below:</p>
<div class="row g-4">
<div class="form-floating col-12 col-xl-6">
<textarea id="ssl_paste_cert" class="form-control" style="font-size:80%; font-family: monospace; height: 20em"
placeholder="-----BEGIN CERTIFICATE-----&#xA;stuff here&#xA;-----END CERTIFICATE-----"></textarea>
<label for="ssl_paste_cert" class="ms-3">TLS/SSL Certificate</label>
</div>
<p style="margin-bottom: .5em">TLS/SSL certificate:</p>
<p><textarea id="ssl_paste_cert" class="form-control" style="max-width: 40em; height: 8em" placeholder="-----BEGIN CERTIFICATE-----&#xA;stuff here&#xA;-----END CERTIFICATE-----"></textarea></p>
<div class="form-floating col-12 col-xl-6">
<textarea id="ssl_paste_chain" class="form-control" style="font-size:80%; font-family: monospace; height: 20em"
placeholder="-----BEGIN CERTIFICATE-----&#xA;stuff here&#xA;-----END CERTIFICATE-----&#xA;-----BEGIN CERTIFICATE-----&#xA;more stuff here&#xA;-----END CERTIFICATE-----"></textarea>
<label for="ssl_paste_chain" class="ms-3">TLS/SSL intermediate Chain (if provided)</label>
</div>
</div>
<p style="margin-bottom: .5em">TLS/SSL intermediate chain (if provided):</p>
<p><textarea id="ssl_paste_chain" class="form-control" style="max-width: 40em; height: 8em" placeholder="-----BEGIN CERTIFICATE-----&#xA;stuff here&#xA;-----END CERTIFICATE-----&#xA;-----BEGIN CERTIFICATE-----&#xA;more stuff here&#xA;-----END CERTIFICATE-----"></textarea></p>
<br>
<p>After you paste in the information, click the install button.</p>
<button class="btn btn-primary" onclick="install_cert()">Install</button>
<button class="btn-primary" onclick="install_cert()">Install</button>
</div>
<script>
@ -127,17 +88,12 @@
function(res) {
// provisioning status
$("#ssl_provision_p ul").html("")
if (!keep_provisioning_shown)
$('#ssl_provision').toggle(res.can_provision.length > 0)
$('#ssl_provision_p').toggle(res.can_provision.length > 0);
if (res.can_provision.length > 0) {
let hostlist = $("#ssl_provision_p ul")
res.can_provision.forEach(domain => {
$("#ssl_provision_p ul").append($("<li></li>").text(domain))
});
}
if (res.can_provision.length > 0)
$('#ssl_provision_p span').text(res.can_provision.join(", "));
// certificate status
var domains = res.status;
@ -146,40 +102,22 @@
$('#ssldomain').html('<option value="">(select)</option>');
$('#ssl_domains').show();
for (var i = 0; i < domains.length; i++) {
var row = $("<tr><th class='text-wrap'></th><td class='status'><div class='icon fas'></div><span class='status-text'></span></td> <td class='actions'><a href='#' onclick='return ssl_install(this);' class='btn btn-xs'>Install Certificate</a></td></tr>");
var row = $("<tr><th class='domain'><a href=''></a></th><td class='status'></td> <td class='actions'><a href='#' onclick='return ssl_install(this);' class='btn btn-xs'>Install Certificate</a></td></tr>");
tb.append(row);
row.attr('data-domain', domains[i].domain);
row.find('th').text(domains[i].domain);
row.find('.domain a').text(domains[i].domain);
row.find('.domain a').attr('href', 'https://' + domains[i].domain);
if (domains[i].status == "not-applicable") {
domains[i].status = "muted"; // text-muted css class
row.find('.actions a').remove(); // no actions applicable
}
let statusclass
let faclass
switch (domains[i].status) {
case "success":
statusclass = "status-ok"
faclass = "fa-check"
row.addClass("text-" + domains[i].status);
row.find('.status').text(domains[i].text);
if (domains[i].status == "success") {
row.find('.actions a').addClass('btn-default').text('Replace Certificate');
break;
case "warning":
statusclass = "status-warning"
faclass = "fa-exclamation-triangle"
row.find('.actions a').addClass('btn-secondary').text('Install Certificate');
break;
case "danger":
statusclass = "status-error"
faclass = "fa-times"
row.find('.actions a').addClass('btn-secondary').text('Install Certificate');
break;
default:
statusclass = "status-na"
row.find('.actions a').remove()
break;
} else {
row.find('.actions a').addClass('btn-primary').text('Install Certificate');
}
let txt = row.find(".status")
txt.addClass(statusclass);
txt.find(".fas").addClass(faclass)
txt.find("span").text(domains[i].text);
$('#ssldomain').append($('<option>').text(domains[i].domain));
}
@ -241,7 +179,7 @@
{ },
function(status) {
// Clear last attempt.
$('#ssl_provision_result').html("");
$('#ssl_provision_result').text("");
may_reenable_provision_button = true;
// Nothing was done. There might also be problem domains, but we've already displayed those.
@ -253,7 +191,6 @@
// Each provisioning API call returns zero or more "requests" which represent
// a request to Let's Encrypt for a single certificate. Normally there is just
// one request (for a single multi-domain certificate).
let global_logs = []
for (var i = 0; i < status.requests.length; i++) {
var r = status.requests[i];
@ -263,45 +200,38 @@
continue;
}
// create an HTML block to display the results of this request
var n = $("<div><h4/><p/></div>");
$('#ssl_provision_result').append(n);
// plain log line
if (typeof r === "string") {
if (r !== "") {
global_logs.append(r)
}
n.find("p").text(r);
continue;
}
let n = $("<div class=\"card mb-3\"><h5 class=\"card-header text-white code-white\"></h5><div class=\"card-body bg-light small\"></div></div>");
$('#ssl_provision_result').append(n);
if (status.requests.length > 0) {
n.find(".card-header").html(`Logs for ${r.domains.map((h) => { return `<code>${h}</code>` }).join(", ")}`);
}
// show a header only to disambiguate request blocks
if (status.requests.length > 0)
n.find("h4").text(r.domains.join(", "));
if (r.result == "error") {
n.find(".card-header").addClass("bg-danger")
n.find("p").addClass("text-danger").text(r.message);
} else if (r.result == "installed") {
n.find(".card-header").addClass("bg-success")
setTimeout("show_tls(true)", 1);
n.find("p").addClass("text-success").text("The TLS certificate was provisioned and installed.");
setTimeout("show_tls(true)", 1); // update main table of certificate statuses, call with arg keep_provisioning_shown true so that we don't clear what we just outputted
}
// display the detailed log info in case of problems
let logs = r.log.join("\n")
if (logs === "" || logs === null || logs === undefined) {
logs = "Something wrong happened, sorry!"
}
n.find("div").text(logs);
var trace = $("<div class='small text-muted' style='margin-top: 1.5em'>Log:</div>");
n.append(trace);
for (var j = 0; j < r.log.length; j++)
trace.append($("<div/>").text(r.log[j]));
}
if (global_logs.length !== 0) {
let card = $("<div class=\"card mb-3\"><div class=\"card-body small\"></div></div>")
$('#ssl_provision_result').append(card);
n.find(".card-body").text(global_logs.join("\n"))
}
if (may_reenable_provision_button) {
if (may_reenable_provision_button)
$('#ssl_provision_p .btn').removeAttr("disabled");
}
});
}
</script>

View file

@ -5,91 +5,44 @@
<hr>
<div class="row d-flex">
<div class="col-lg-6">
<div class="row">
<div class="col-sm-6">
<h4>In your browser</h4>
<p>You can edit your contacts and calendar from your web browser.</p>
<table class="table">
<caption></caption>
<thead>
<tr>
<th>For...</th>
<th>Visit this URL</th>
</tr>
</thead>
<tr>
<th>Contacts</td>
<td><a href="https://{{hostname}}/cloud/contacts">https://{{hostname}}/cloud/contacts</a></td>
</tr>
<tr>
<th>Calendar</td>
<td><a href="https://{{hostname}}/cloud/calendar">https://{{hostname}}/cloud/calendar</a></td>
</tr>
<thead><tr><th>For...</th> <th>Visit this URL</th></tr></thead>
<tr><th>Contacts</td> <td><a href="https://{{hostname}}/cloud/contacts">https://{{hostname}}/cloud/contacts</a></td></tr>
<tr><th>Calendar</td> <td><a href="https://{{hostname}}/cloud/calendar">https://{{hostname}}/cloud/calendar</a></td></tr>
</table>
<p>Log in settings are the same as with <a href="#mail-guide" onclick="return show_panel(this);">mail</a>:
your
<p>Log in settings are the same as with <a href="#mail-guide" onclick="return show_panel(this);">mail</a>: your
complete email address and your mail password.</p>
</div>
<div class="col-lg-6">
<div class="col-sm-6">
<h4>On your mobile device</h4>
<p>If you set up your <a href="#mail-guide" onclick="return show_panel(this);">mail</a> using
Exchange/ActiveSync,
<p>If you set up your <a href="#mail-guide" onclick="return show_panel(this);">mail</a> using Exchange/ActiveSync,
your contacts and calendar may already appear on your device.</p>
<p>Otherwise, here are some apps that can synchronize your contacts and calendar to your Android phone.</p>
<table class="table">
<caption></caption>
<thead>
<tr>
<th>For...</th>
<th>Use...</th>
</tr>
</thead>
<tr>
<td>Contacts and Calendar</td>
<td><a href="https://play.google.com/store/apps/details?id=at.bitfire.davdroid">DAVx⁵</a> ($5.99;
free <a href="https://f-droid.org/packages/at.bitfire.davdroid/">here</a>)</td>
</tr>
<tr>
<td>Only Contacts</td>
<td><a href="https://play.google.com/store/apps/details?id=org.dmfs.carddav.sync">CardDAV-Sync
free</a> (free)</td>
</tr>
<tr>
<td>Only Calendar</td>
<td><a href="https://play.google.com/store/apps/details?id=org.dmfs.caldav.lib">CalDAV-Sync</a>
($2.99)</td>
</tr>
<thead><tr><th>For...</th> <th>Use...</th></tr></thead>
<tr><td>Contacts and Calendar</td> <td><a href="https://play.google.com/store/apps/details?id=at.bitfire.davdroid">DAVx⁵</a> ($5.99; free <a href="https://f-droid.org/packages/at.bitfire.davdroid/">here</a>)</td></tr>
<tr><td>Only Contacts</td> <td><a href="https://play.google.com/store/apps/details?id=org.dmfs.carddav.sync">CardDAV-Sync free</a> (free)</td></tr>
<tr><td>Only Calendar</td> <td><a href="https://play.google.com/store/apps/details?id=org.dmfs.caldav.lib">CalDAV-Sync</a> ($2.99)</td></tr>
</table>
<p>Use the following settings:</p>
<table class="table">
<tr>
<td>Account Type</td>
<td>CardDAV or CalDAV</td>
</tr>
<tr>
<td>Server Name</td>
<td>{{hostname}}</td>
</tr>
<tr>
<td>Use SSL</td>
<td>Yes</td>
</tr>
<tr>
<td>Username</td>
<td>Your complete email address.</td>
</tr>
<tr>
<td>Password</td>
<td>Your mail password.</td>
</tr>
<tr><td>Account Type</td> <td>CardDAV or CalDAV</td></tr>
<tr><td>Server Name</td> <td>{{hostname}}</td></tr>
<tr><td>Use SSL</td> <td>Yes</td></tr>
<tr><td>Username</td> <td>Your complete email address.</td></tr>
<tr><td>Password</td> <td>Your mail password.</td></tr>
</table>
</div>
</div>

View file

@ -1,21 +1,19 @@
<style>
#backup-status tr.full-backup td {
font-weight: bold;
}
#backup-status th { text-align: center; }
#backup-status tr.full-backup td { font-weight: bold; }
</style>
<h2>Backup Status</h2>
<p>The box makes an incremental backup each night. By default the backup is stored on the machine itself, but you can
also store it on S3-compatible services like Amazon Web Services (AWS).</p>
<p>The box makes an incremental backup each night. By default the backup is stored on the machine itself, but you can also store in on S3-compatible services like Amazon Web Services (AWS).</p>
<h3>Configuration</h3>
<form class="form-horizontal" role="form" onsubmit="set_custom_backup(); return false;">
<div class="col-lg-10 col-xl-8">
<div class="input-group">
<label class="input-group-text" for="backup-target-type">Backup to</label>
<select class="form-select" rows="1" id="backup-target-type" onchange="toggle_form()">
<div class="form-group">
<label for="backup-target-type" class="col-sm-2 control-label">Backup to:</label>
<div class="col-sm-3">
<select class="form-control" rows="1" id="backup-target-type" onchange="toggle_form()">
<option value="off">Nowhere (Disable Backups)</option>
<option value="local">{{hostname}}</option>
<option value="rsync">rsync</option>
@ -24,73 +22,73 @@
</select>
</div>
</div>
<!-- LOCAL BACKUP -->
<div class="form-group backup-target-local">
<div class="col-lg-10 col-xl-8 mb-3">
<p>Backups are stored on this machine&rsquo;s own hard disk. You are responsible for periodically using SFTP (FTP
over SSH) to copy the backup files from <tt class="backup-location"></tt> to a safe location. These files are
encrypted, so they are safe to store anywhere.</p>
<p>Separately copy the encryption password from <tt class="backup-encpassword-file"></tt> to a safe and secure
location. You will need this file to decrypt backup files.</p>
<div class="col-sm-10 col-sm-offset-2">
<p>Backups are stored on this machine&rsquo;s own hard disk. You are responsible for periodically using SFTP (FTP over SSH) to copy the backup files from <tt class="backup-location"></tt> to a safe location. These files are encrypted, so they are safe to store anywhere.</p>
<p>Separately copy the encryption password from <tt class="backup-encpassword-file"></tt> to a safe and secure location. You will need this file to decrypt backup files.</p>
</div>
</div>
<!-- RSYNC BACKUP -->
<div class="form-group backup-target-rsync">
<div class="col-lg-10 col-xl-8 mb-3">
<div class="col-sm-10 col-sm-offset-2">
<p>Backups synced to a remote machine using rsync over SSH, with local
copies in <tt class="backup-location"></tt>. These files are encrypted, so
they are safe to store anywhere.</p>
<p>Separately copy the encryption
they are safe to store anywhere.</p> <p>Separately copy the encryption
password from <tt class="backup-encpassword-file"></tt> to a safe and
secure location. You will need this file to decrypt backup files.</p>
</div>
</div>
<div class="col-lg-10 col-xl-8 mb-3 backup-target-rsync">
<div class="input-group">
<label class="input-group-text">Where to?</label>
<input type="text" class="form-control" id="backup-target-rsync-host" placeholder="hostname.local">
<label class="input-group-text">:</label>
<div style="width: 20%">
<input type="number" class="form-control" id="backup-target-rsync-port" placeholder="Port (22)">
<div class="form-group backup-target-rsync">
<table class="col-sm-8">
<tr style="width: 100%;">
<td style="width: 75%;" class="col-sm-8">
<label for="backup-target-rsync-host" class="control-label">Hostname</label>
<input type="text" placeholder="hostname.local" class="form-control" rows="1" id="backup-target-rsync-host">
</td>
<td style="width: 25%;" class="col-sm-8">
<label for="backup-target-rsync-port" class="control-label">Port</label>
<input type="number" class="form-control" id="backup-target-rsync-port" placeholder="22">
</td>
</tr>
</table>
</div>
<div class="form-group backup-target-rsync">
<label for="backup-target-rsync-path" class="col-sm-2 control-label">Path</label>
<div class="col-sm-8">
<input type="text" placeholder="/backups/{{hostname}}" class="form-control" rows="1" id="backup-target-rsync-path">
</div>
</div>
</div>
<div class="col-lg-10 col-xl-8 mb-3 backup-target-rsync">
<div class="input-group">
<label for="backup-target-rsync-path" class="input-group-text">Path</label>
<input type="text" placeholder="/backups/{{hostname}}" class="form-control" id="backup-target-rsync-path">
<div class="form-group backup-target-rsync">
<label for="backup-target-rsync-user" class="col-sm-2 control-label">Username</label>
<div class="col-sm-8">
<input type="text" class="form-control" rows="1" id="backup-target-rsync-user">
</div>
</div>
<div class="col-lg-10 col-xl-8 mb-3 backup-target-rsync">
<div class="input-group">
<label for="backup-target-rsync-path" class="input-group-text">Username</label>
<input type="text" class="form-control" id="backup-target-rsync-user">
</div>
</div>
<div class="col-lg-10 col-xl-8 mb-3 backup-target-rsync">
<label for="ssh-pub-key" class="col-sm-2 control-label">
<h4>Public SSH Key</h4>
</label>
<textarea class="form-control font-monospace" id="ssh-pub-key" style="min-height: 12em;" readonly></textarea>
<div class="form-group backup-target-rsync">
<label for="ssh-pub-key" class="col-sm-2 control-label">Public SSH Key</label>
<div class="col-sm-8">
<input type="text" class="form-control" rows="1" id="ssh-pub-key" readonly>
<div class="small" style="margin-top: 2px">
Copy the Public SSH Key above, and paste it within the <tt>~/.ssh/authorized_keys</tt>
of target user on the backup server specified above. That way you'll enable secure and
passwordless authentication from your mail-in-a-box server and your backup server.
</div>
</div>
<!-- S3 BACKUP -->
<div class="col-lg-10 col-xl-8 mb-3 backup-target-s3">
<p>Backups are stored in an S3-compatible bucket. You must have an AWS or other S3 service account already.</p>
<p>You MUST manually copy the encryption password from <tt class="backup-encpassword-file"></tt> to a safe and
secure location. You will need this file to decrypt backup files. It is <b>NOT</b> stored in your S3 bucket.</p>
</div>
<div class="col-lg-10 col-xl-8 mb-3 backup-target-s3">
<div class="input-group">
<label for="backup-target-s3-host-select" class="input-group-text">S3 Region</label>
<select class="form-select" id="backup-target-s3-host-select">
<!-- S3 BACKUP -->
<div class="form-group backup-target-s3">
<div class="col-sm-10 col-sm-offset-2">
<p>Backups are stored in an S3-compatible bucket. You must have an AWS or other S3 service account already.</p>
<p>You MUST manually copy the encryption password from <tt class="backup-encpassword-file"></tt> to a safe and secure location. You will need this file to decrypt backup files. It is <b>NOT</b> stored in your S3 bucket.</p>
</div>
</div>
<div class="form-group backup-target-s3">
<label for="backup-target-s3-host-select" class="col-sm-2 control-label">S3 Region</label>
<div class="col-sm-8">
<select class="form-control" rows="1" id="backup-target-s3-host-select">
{% for name, host in backup_s3_hosts %}
<option value="{{host}}">{{name}}</option>
{% endfor %}
@ -98,83 +96,75 @@
</select>
</div>
</div>
<div class="col-lg-10 col-xl-8 mb-3 backup-target-s3">
<div class="input-group">
<label for="backup-target-s3-host" class="input-group-text">S3 Host / Endpoint</label>
<input type="text" placeholder="Endpoint" class="form-control" id="backup-target-s3-host">
<div class="form-group backup-target-s3">
<label for="backup-target-s3-host" class="col-sm-2 control-label">S3 Host / Endpoint</label>
<div class="col-sm-8">
<input type="text" placeholder="Endpoint" class="form-control" rows="1" id="backup-target-s3-host">
</div>
</div>
<div class="col-lg-10 col-xl-8 mb-3 backup-target-s3">
<div class="input-group">
<label for="backup-target-s3-path" class="input-group-text">S3 Path</label>
<input type="text" placeholder="your-bucket-name/backup-directory" class="form-control"
id="backup-target-s3-path">
<div class="form-group backup-target-s3">
<label for="backup-target-s3-path" class="col-sm-2 control-label">S3 Path</label>
<div class="col-sm-8">
<input type="text" placeholder="your-bucket-name/backup-directory" class="form-control" rows="1" id="backup-target-s3-path">
</div>
</div>
<div class="col-lg-10 col-xl-8 mb-3 backup-target-s3">
<div class="input-group">
<label for="backup-target-user" class="input-group-text">S3 Access Key</label>
<input type="text" class="form-control" id="backup-target-user">
<div class="form-group backup-target-s3">
<label for="backup-target-user" class="col-sm-2 control-label">S3 Access Key</label>
<div class="col-sm-8">
<input type="text" class="form-control" rows="1" id="backup-target-user">
</div>
</div>
<div class="col-lg-10 col-xl-8 mb-3 backup-target-s3">
<div class="input-group">
<label for="backup-target-pass" class="input-group-text">S3 Secret Access Key</label>
<input type="text" class="form-control" id="backup-target-pass">
<div class="form-group backup-target-s3">
<label for="backup-target-pass" class="col-sm-2 control-label">S3 Secret Access Key</label>
<div class="col-sm-8">
<input type="text" class="form-control" rows="1" id="backup-target-pass">
</div>
</div>
<!-- Backblaze -->
<div class="col-lg-10 col-xl-8 mb-3 backup-target-b2">
<p>Backups are stored in a <a href="https://www.backblaze.com/" target="_blank" rel="noreferrer">Backblaze</a> B2
bucket. You must have a Backblaze account already.</p>
<p>You MUST manually copy the encryption password from <tt class="backup-encpassword-file"></tt> to a safe and
secure location. You will need this file to decrypt backup files. It is NOT stored in your Backblaze B2 bucket.
</p>
</div>
<div class="col-lg-10 col-xl-8 mb-3 backup-target-b2">
<div class="input-group">
<label for="backup-target-b2-user" class="input-group-text">B2 Application KeyID</label>
<input type="text" class="form-control" id="backup-target-b2-user">
<div class="form-group backup-target-b2">
<div class="col-sm-10 col-sm-offset-2">
<p>Backups are stored in a <a href="https://www.backblaze.com/" target="_blank" rel="noreferrer">Backblaze</a> B2 bucket. You must have a Backblaze account already.</p>
<p>You MUST manually copy the encryption password from <tt class="backup-encpassword-file"></tt> to a safe and secure location. You will need this file to decrypt backup files. It is NOT stored in your Backblaze B2 bucket.</p>
</div>
</div>
<div class="col-lg-10 col-xl-8 mb-3 backup-target-b2">
<div class="input-group">
<label for="backup-target-b2-pass" class="input-group-text">B2 Application Key</label>
<input type="text" class="form-control" id="backup-target-b2-pass">
<div class="form-group backup-target-b2">
<label for="backup-target-b2-user" class="col-sm-2 control-label">B2 Application KeyID</label>
<div class="col-sm-8">
<input type="text" class="form-control" rows="1" id="backup-target-b2-user">
</div>
</div>
<div class="col-lg-10 col-xl-8 mb-3 backup-target-b2">
<div class="input-group">
<label for="backup-target-b2-bucket" class="input-group-text">B2 Bucket</label>
<input type="text" class="form-control" id="backup-target-b2-bucket">
<div class="form-group backup-target-b2">
<label for="backup-target-b2-pass" class="col-sm-2 control-label">B2 Application Key</label>
<div class="col-sm-8">
<input type="text" class="form-control" rows="1" id="backup-target-b2-pass">
</div>
</div>
<div class="form-group backup-target-b2">
<label for="backup-target-b2-bucket" class="col-sm-2 control-label">B2 Bucket</label>
<div class="col-sm-8">
<input type="text" class="form-control" rows="1" id="backup-target-b2-bucket">
</div>
</div>
<!-- Common -->
<div class="backup-target-local backup-target-rsync backup-target-s3 backup-target-b2">
<hr>
<div class="col-lg-10 col-xl-8">
<div class="input-group">
<label class="input-group-text" for="backup-min-age">Retention Days</label>
<input type="number" class="form-control" id="backup-min-age">
</div>
<div class="small" style="margin-top: 2px">This is the minimum time backup data is kept for. The box makes an
incremental backup most nights, which requires that previous backups back to the most recent full backup be
preserved, so backup data is often kept much longer than this setting. Full backups are made periodically when
the incremental backup data size exceeds a limit.</div>
<div class="form-group backup-target-local backup-target-rsync backup-target-s3 backup-target-b2">
<label for="min-age" class="col-sm-2 control-label">Retention Days:</label>
<div class="col-sm-8">
<input type="number" class="form-control" rows="1" id="min-age">
<div class="small" style="margin-top: 2px">This is the minimum time backup data is kept for. The box makes an incremental backup most nights, which requires that previous backups back to the most recent full backup be preserved, so backup data is often kept much longer than this setting. Full backups are made periodically when the incremental backup data size exceeds a limit.</div>
</div>
</div>
<div class="mt-3">
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button id="set-s3-backup-button" type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</form>
<h3>Available backups</h3>
<p>The backup location currently contains the backups listed below. The total size of the backups is currently <span
id="backup-total-size"></span>.</p>
<p>The backup location currently contains the backups listed below. The total size of the backups is currently <span id="backup-total-size"></span>.</p>
<table id="backup-status" class="table align-middle col-12">
<caption></caption>
<table id="backup-status" class="table" style="width: auto">
<thead>
<th colspan="2">When</th>
<th>Type</th>
@ -186,12 +176,8 @@
</table>
<!-- Hide these buttons until we're sure we can use them :) -->
<div class="row justify-content-evenly">
<button id="create-full-backup-button" class="btn btn-primary col-3" onclick="do_backup(true)"
style="display: none;">Create Full Backup Now</button>
<button id="create-incremental-backup-button" class="btn btn-primary col-3" onclick="do_backup(false)"
style="display: none;">Create Incremental Backup Now</button>
</div>
<button id="create-full-backup-button" class="btn btn-primary" onclick="do_backup(true)" style="display: none;">Create Full Backup Now</button>
<button id="create-incremental-backup-button" class="btn btn-primary" onclick="do_backup(false)" style="display: none;">Create Incremental Backup Now</button>
<script>
@ -222,7 +208,7 @@
function show_system_backup() {
show_custom_backup()
$('#backup-status tbody').html("<tr><td colspan='5' class='text-muted'>Loading...</td></tr>")
$('#backup-status tbody').html("<tr><td colspan='2' class='text-muted'>Loading...</td></tr>")
api(
"/system/backup/status",
"GET",
@ -237,13 +223,13 @@
var total_disk_size = 0;
if (typeof r.backups == "undefined") {
var tr = $('<tr><td colspan="5">Backups are turned off.</td></tr>');
var tr = $('<tr><td colspan="3">Backups are turned off.</td></tr>');
$('#backup-status tbody').append(tr);
$('#create-full-backup-button').css("display","none")
$('#create-incremental-backup-button').css("display","none")
return;
} else if (r.backups.length == 0) {
var tr = $('<tr><td colspan="5">No backups have been made yet.</td></tr>');
var tr = $('<tr><td colspan="3">No backups have been made yet.</td></tr>');
$('#backup-status tbody').append(tr);
}
@ -257,7 +243,7 @@
tr.append( $('<td/>').text(b.date_str) );
tr.append( $('<td/>').text(b.date_delta + " ago") );
tr.append( $('<td/>').text(b.full ? "full" : "increment") );
tr.append($('<td/>').text(nice_size(b.size)));
tr.append( $('<td style="text-align: right"/>').text( nice_size(b.size)) );
if (b.deleted_in)
tr.append( $('<td/>').text(b.deleted_in) );
else
@ -281,7 +267,7 @@
function(r) {
$("#backup-target-user").val(r.target_user);
$("#backup-target-pass").val(r.target_pass);
$("#backup-min-age").val(r.min_age_in_days);
$("#min-age").val(r.min_age_in_days);
$(".backup-location").text(r.file_target_directory);
$(".backup-encpassword-file").text(r.enc_pw_file);
$("#ssh-pub-key").val(r.ssh_pub_key);
@ -304,15 +290,6 @@
$("#backup-target-type").val("s3");
var hostpath = r.target.substring(5).split('/');
var host = hostpath.shift();
let s3_options = $("#backup-target-s3-host-select option").map(function() {return this.value}).get()
$("#backup-target-s3-host-select").val("other")
for (let h of s3_options) {
console.log(h)
if (h == host) {
$("#backup-target-s3-host-select").val(host)
break
}
}
$("#backup-target-s3-host").val(host);
$("#backup-target-s3-path").val(hostpath.join('/'));
} else if (r.target.substring(0, 5) == "b2://") {
@ -351,7 +328,7 @@
target_pass = '';
}
var min_age = $("#backup-min-age").val();
var min_age = $("#min-age").val();
api(
"/system/backup/config",
"POST",
@ -374,18 +351,18 @@
}
function init_inputs(target_type) {
function set_host(host, overwrite_other) {
function set_host(host) {
if(host !== 'other') {
$("#backup-target-s3-host").val(host);
} else if (overwrite_other) {
} else {
$("#backup-target-s3-host").val('');
}
}
if (target_type == "s3") {
$('#backup-target-s3-host-select').off('change').on('change', function() {
set_host($('#backup-target-s3-host-select').val(), true);
set_host($('#backup-target-s3-host-select').val());
});
set_host($('#backup-target-s3-host-select').val(), false);
set_host($('#backup-target-s3-host-select').val());
}
}

View file

@ -1,81 +1,42 @@
<h2>System Status Checks</h2>
<style>
#system-checks .message {
display: inline;
}
#system-checks .icon {
min-width: 2em;
}
#system-checks .heading {
#system-checks .heading td {
font-weight: bold;
font-size: 180%;
padding-top: 1.75em;
font-size: 120%;
padding-top: 1.5em;
}
#system-checks .heading.first {
#system-checks .heading.first td {
border-top: none;
padding-top: 0;
}
.status-error .fas {
color: rgb(190, 0, 0);
#system-checks .status-error td {
color: rgb(140, 0, 0);
}
.status-error.sym {
color: rgb(190, 0, 0);
#system-checks .status-warning td {
color: rgb(170, 120, 0);
}
.status-error .status-text {
color: rgb(70, 0, 0);
#system-checks .status-ok td {
color: rgb(0, 140, 0);
}
.status-warning .fas {
color: rgb(191, 150, 0);
#system-checks .status-na td {
color: rgb(108, 117, 125);
}
.status-warning.sym {
color: rgb(191, 150, 0);
}
.status-warning .status-text {
color: rgb(69, 54, 0);
}
.status-ok .fas {
color: rgb(0, 190, 0);
}
.status-ok.sym {
color: rgb(0, 190, 0);
}
.status-ok .status-text {
color: rgb(0, 70, 0);
}
.status-na .fas {
color: rgb(100, 100, 100);
}
.status-na.sym {
color: rgb(100, 100, 100);
}
.status-na .status-text {
color: rgb(100, 100, 100);
}
div.extra {
#system-checks div.extra {
display: none;
margin-top: 1em;
max-width: 50em;
word-wrap: break-word;
}
#system-checks .showhide {
display: block;
display: none;
font-size: 85%;
}
@ -86,6 +47,9 @@
}
</style>
<div>
<div>
<div id="system-reboot-required" style="display: none; margin-bottom: 1em;">
<button type="button" class="btn btn-danger" onclick="confirm_reboot(); return false;">Reboot Box</button>
<div>No reboot is necessary.</div>
@ -98,12 +62,21 @@
Mail-in-a-Box.)</small></p>
</div>
<div id="system-checks">
</div>
</div> <!-- /col -->
<br>
<div>
<table id="system-checks" class="table">
<thead></thead>
<tbody></tbody>
</table>
</div> <!-- /col -->
</div> <!-- /row -->
<script>
function show_system_status() {
$('#system-checks').html("")
$('#system-checks tbody').html("<tr><td class='text-muted'>Loading...</td></tr>")
api(
"/system/privacy",
@ -131,38 +104,24 @@
"POST",
{},
function (r) {
for (let i = 0; i < r.length; i++) {
let n = $("<div class='col-12'><div class='icon'></div><p class='message status-text' style='margin: 0'/>");
$('#system-checks tbody').html("");
for (var i = 0; i < r.length; i++) {
var n = $("<tr><td class='status'/><td class='message'><p style='margin: 0'/><p class='showhide btn btn-light' href='#'/><div class='extra'></div></tr>");
if (i == 0) n.addClass('first')
if (r[i].type == "heading") {
if (r[i].type == "heading")
n.addClass(r[i].type)
} else {
else
n.addClass("status-" + r[i].type)
n.find(".icon").addClass("fas")
}
if (r[i].type == "ok") n.find(".icon").addClass("fa-check")
if (r[i].type == "error") n.find(".icon").addClass("fa-times")
if (r[i].type == "warning") n.find(".icon").addClass("fa-exclamation-triangle")
n.find('p.status-text').text(r[i].text)
if (r[i].type == "ok") n.find('td.status').text("✔️")
if (r[i].type == "error") n.find('td.status').text("❌")
if (r[i].type == "warning") n.find('td.status').text("⚠️")
n.find('td.message p').text(r[i].text)
$('#system-checks tbody').append(n);
if (r[i].extra.length > 0) {
let open = false
n.append("<p class='showhide btn btn-light mt-3' href='#'>Show More</p><div class='extra ps-4 col-12'></div>")
n.find('.showhide').click(function () {
let extra = $(this).parent().find('.extra')
if (open) {
$(this).html("Show More");
extra.fadeOut();
} else {
$(this).html("Show Less");
extra.fadeIn();
}
open = !open
n.find('.showhide').show().text("Show More").click(function () {
$(this).hide();
$(this).parent().find('.extra').fadeIn();
return false;
});
}
@ -172,12 +131,7 @@
var m = $("<div/>").text(r[i].extra[j].text)
if (r[i].extra[j].monospace)
m.addClass("pre");
n.find('.extra').append(m);
}
$('#system-checks').append(n);
if (i < r.length - 1) {
$('#system-checks').append($("<hr>"));
n.find('> td.message > div').append(m);
}
}
})

View file

@ -1,95 +1,56 @@
<h2>Users</h2>
<style>
#user_table tr.account_inactive td.address {
color: #888;
text-decoration: line-through;
}
#user_table .actions {
margin-top: .33em;
font-size: 95%;
}
#user_table .account_inactive .if_active {
display: none;
}
#user_table .account_active .if_inactive {
display: none;
}
#user_table .account_active.if_inactive {
display: none;
}
#user_table tr.account_inactive td.address { color: #888; text-decoration: line-through; }
#user_table .actions { margin-top: .33em; font-size: 95%; }
#user_table .account_inactive .if_active { display: none; }
#user_table .account_active .if_inactive { display: none; }
#user_table .account_active.if_inactive { display: none; }
.row-center { text-align: center; }
</style>
<h3>Add a mail user</h3>
<p>Add an email address to this system. This will create a new login username/password.</p>
<form role="form" onsubmit="return do_add_user(); return false;">
<div class="mb-3">
<div class="row g-3">
<div class="col-12 col-lg-6">
<div class="input-group">
<label class="input-group-text" for="adduserEmail">Email address</label>
<input type="email" class="form-control" style="min-width: 15em;" id="adduserEmail"
placeholder="me@example.com">
<form class="form-inline" role="form" onsubmit="return do_add_user(); return false;">
<div class="form-group">
<label class="sr-only" for="adduserEmail">Email address</label>
<input type="email" class="form-control" id="adduserEmail" placeholder="Email Address">
</div>
<div class="form-group">
<label class="sr-only" for="adduserPassword">Password</label>
<input type="password" class="form-control" id="adduserPassword" placeholder="Password">
</div>
<div class="col-12 col-lg-6">
<div class="input-group">
<label class="input-group-text" for="adduserPassword">Password</label>
<input type="password" class="form-control" style="min-width: 10em;" id="adduserPassword"
placeholder="Password">
</div>
</div>
</div>
</div>
<div class="col-md-8 col-lg-6 mb-3">
<div class="input-group">
<label class="input-group-text" for="adduserPrivs">User Type</label>
<select class="form-select" id="adduserPrivs">
<div class="form-group">
<select class="form-control" id="adduserPrivs">
<option value="">Normal User</option>
<option value="admin">Administrator</option>
</select>
</div>
<div class="form-group">
<label class="sr-only" for="adduserQuota">Quota</label>
<input type="text" class="form-control" id="adduserQuota" placeholder="Quota" style="width:5em;">
</div>
<div class="col-md-8 col-lg-6 mb-3">
<div class="input-group">
<label class="input-group-text" for="adduserQuota">Storage Quota</label>
<input type="text" class="form-control" id="adduserQuota" placeholder="0">
</div>
</div>
<ul style="margin-top: 1em; padding-left: 1.5em; font-size: 90%;">
<li>Passwords must be at least eight characters. If you're out of ideas, you can <a href="#"
onclick="return generate_random_password()">generate a random password</a>.</li>
<li>Use <a href="#" onclick="return show_panel('aliases')">aliases</a> to create email addresses that forward to
existing accounts.</li>
<li>Administrators get access to this control panel.</li>
<li>User accounts cannot contain any international (non-ASCII) characters, but <a href="#"
onclick="return show_panel('aliases');">aliases</a> can.</li>
<li>Quotas may not contain any spaces, commas or decimal points. Suffixes of G (gigabytes) and M (megabytes) are
allowed. For unlimited storage enter 0 (zero)</li>
</ul>
<button type="submit" class="btn btn-primary">Add User</button>
</form>
<ul style="margin-top: 1em; padding-left: 1.5em; font-size: 90%;">
<li>Passwords must be at least eight characters consisting of English letters and numbers only. For best results, <a href="#" onclick="return generate_random_password()">generate a random password</a>.</li>
<li>Use <a href="#" onclick="return show_panel('aliases')">aliases</a> to create email addresses that forward to existing accounts.</li>
<li>Administrators get access to this control panel.</li>
<li>User accounts cannot contain any international (non-ASCII) characters, but <a href="#" onclick="return show_panel('aliases');">aliases</a> can.</li>
<li>Quotas may not contain any spaces, commas or decimal points. Suffixes of G (gigabytes) and M (megabytes) are allowed. For unlimited storage enter 0 (zero)</li>
</ul>
<h3>Existing mail users</h3>
<table id="user_table" class="table col-12">
<caption></caption>
<table id="user_table" class="table" style="width: auto">
<thead>
<tr>
<th width="35%">Email Address</th>
<th class="">Messages</th>
<th class="">Size</th>
<th class="">Used</th>
<th class="">Quota</th>
<th class="row-center">Messages</th>
<th class="row-center">Size</th>
<th class="row-center">Used</th>
<th class="row-center">Quota</th>
<th>Actions</th>
</tr>
</thead>
@ -102,10 +63,10 @@
<tr id="user-template">
<td class='address'>
</td>
<td class="box-count"></td>
<td class="box-size"></td>
<td class="percent"></td>
<td class="quota">
<td class="box-count row-center"></td>
<td class="box-size row-center"></td>
<td class="percent row-center"></td>
<td class="quota row-center">
</td>
<td class='actions'>
<span class='privs'>
@ -135,8 +96,7 @@
</tr>
<tr id="user-extra-template" class="if_inactive">
<td colspan="3" style="border: 0; padding-top: 0">
<div class='restore_info' style='color: #888; font-size: 90%'>To restore account, create a new account with this
email address. Or to permanently delete the mailbox, delete the directory <tt></tt> on the machine.</div>
<div class='restore_info' style='color: #888; font-size: 90%'>To restore account, create a new account with this email address. Or to permanently delete the mailbox, delete the directory <tt></tt> on the machine.</div>
</td>
</tr>
</table>
@ -157,57 +117,35 @@
<h4 style="margin-bottom: 0">Verbs</h4>
<table class="table" style="margin-top: .5em">
<caption></caption>
<thead>
<th>Verb</th>
<th>Action</th>
<th></th>
</thead>
<thead><th>Verb</th> <th>Action</th><th></th></thead>
<tr><td>GET</td><td><i>(none)</i></td> <td>Returns a list of existing mail users. Adding <code>?format=json</code> to the URL will give JSON-encoded results.</td></tr>
<tr>
<td><b>GET</b< /td>
<td><i>(none)</i></td>
<td>Returns a list of existing mail users. Adding <code>?format=json</code> to the URL will give JSON-encoded
results.</td>
<td>POST</td>
<td>/add</td>
<td>Adds a new mail user. Required POST-body parameters are <code>email</code> and <code>password</code>. Optional parameters: <code>privilege=admin</code> and <code>quota</code></td>
</tr>
<tr>
<td><b>POST</b< /td>
<td class="font-monospace">/add</td>
<td>Adds a new mail user. Required POST-body parameters are <code>email</code> and <code>password</code>. Optional
parameters: <code>privilege=admin</code> and <code>quota</code></td>
</tr>
<tr>
<td><b>POST</b></td>
<td class="font-monospace">/remove</td>
<td>POST</td>
<td>/remove</td>
<td>Removes a mail user. Required POST-by parameter is <code>email</code>.</td>
</tr>
<tr><td>POST</td><td>/privileges/add</td> <td>Used to make a mail user an admin. Required POST-body parameters are <code>email</code> and <code>privilege=admin</code>.</td></tr>
<tr><td>POST</td><td>/privileges/remove</td> <td>Used to remove the admin privilege from a mail user. Required POST-body parameter is <code>email</code>.</td></tr>
<tr>
<td><b>POST</b></td>
<td class="font-monospace">/privileges/add</td>
<td>Used to make a mail user an admin. Required POST-body parameters are <code>email</code> and
<code>privilege=admin</code>.</td>
<td>GET</td>
<td>/quota</td>
<td>Get the quota for a mail user. Required POST-body parameters are <code>email</code> and will return JSON result</td>
</tr>
<tr>
<td><b>POST</b></td>
<td class="font-monospace">/privileges/remove</td>
<td>Used to remove the admin privilege from a mail user. Required POST-body parameter is <code>email</code>.</td>
</tr>
<tr>
<td><b>GET</b></td>
<td class="font-monospace">/quota</td>
<td>Get the quota for a mail user. Required POST-body parameters are <code>email</code> and will return JSON result
</td>
</tr>
<tr>
<td><b>POST</b></td>
<td class="font-monospace">/quota</td>
<td>POST</td>
<td>/quota</td>
<td>Set the quota for a mail user. Required POST-body parameters are <code>email</code> and <code>quota</code>.</td>
</tr>
</table>
<h4>Examples:</h4>
<p>Try these examples. For simplicity the examples omit the <code>--user me@mydomain.com:yourpassword</code> command
line argument which you must fill in with your administrative email address and password.</p>
<p>Try these examples. For simplicity the examples omit the <code>--user me@mydomain.com:yourpassword</code> command line argument which you must fill in with your administrative email address and password.</p>
<pre># Gives a JSON-encoded list of all mail users
curl -X GET https://{{hostname}}/admin/mail/users?format=json
@ -236,7 +174,7 @@ curl -X POST -d "email=new_user@mydomail.com" https://{{hostname}}/admin/mail/us
}
);
$('#user_table tbody').html("<tr><td colspan='6' class='text-muted'>Loading...</td></tr>")
$('#user_table tbody').html("<tr><td colspan='2' class='text-muted'>Loading...</td></tr>")
api(
"/mail/users",
"GET",
@ -244,7 +182,7 @@ curl -X POST -d "email=new_user@mydomail.com" https://{{hostname}}/admin/mail/us
function(r) {
$('#user_table tbody').html("");
for (var i = 0; i < r.length; i++) {
var hdr = $("<tr><th colspan='6' class='bg-light'></th></tr>");
var hdr = $("<tr><th colspan='6' style='background-color: #EEE'></th></tr>");
hdr.find('th').text(r[i].domain);
$('#user_table tbody').append(hdr);

View file

@ -3,50 +3,36 @@
<h2>Static Web Hosting</h2>
<p>This machine is serving a simple, static website at <a href="https://{{hostname}}">https://{{hostname}}</a> and at
all domain names that you set up an email user or alias for.</p>
<p>This machine is serving a simple, static website at <a href="https://{{hostname}}">https://{{hostname}}</a> and at all domain names that you set up an email user or alias for.</p>
<h3>Uploading web files</h3>
<p>You can replace the default website with your own HTML pages and other static files. This control panel won&rsquo;t
help you design a website, but once you have <tt>.html</tt> files you can upload them following these instructions:
</p>
<p>You can replace the default website with your own HTML pages and other static files. This control panel won&rsquo;t help you design a website, but once you have <tt>.html</tt> files you can upload them following these instructions:</p>
<ol>
<li>Ensure that any domains you are publishing a website for have no problems on the <a href="#system_status"
onclick="return show_panel(this);">Status Checks</a> page.</li>
<li>Ensure that any domains you are publishing a website for have no problems on the <a href="#system_status" onclick="return show_panel(this);">Status Checks</a> page.</li>
<li>On your personal computer, install an SSH file transfer program such as <a
href="https://filezilla-project.org/">FileZilla</a> or <a
href="http://linuxcommand.org/man_pages/scp1.html">scp</a>.</li>
<li>On your personal computer, install an SSH file transfer program such as <a href="https://filezilla-project.org/">FileZilla</a> or <a href="http://linuxcommand.org/man_pages/scp1.html">scp</a>.</li>
<li>Log in to this machine with the file transfer program. The server is <strong>{{hostname}}</strong>, the protocol
is SSH or SFTP, and use the <strong>SSH login credentials</strong> that you used when you originally created this
machine at your cloud host provider. This is <strong>not</strong> what you use to log in either for email or this
control panel. Your SSH credentials probably involves a private key file.</li>
<li>Log in to this machine with the file transfer program. The server is <strong>{{hostname}}</strong>, the protocol is SSH or SFTP, and use the <strong>SSH login credentials</strong> that you used when you originally created this machine at your cloud host provider. This is <strong>not</strong> what you use to log in either for email or this control panel. Your SSH credentials probably involves a private key file.</li>
<li>Upload your <tt>.html</tt> or other files to the directory <tt>{{storage_root}}/www/default</tt> on this machine.
They will appear directly and immediately on the web.</li>
<li>Upload your <tt>.html</tt> or other files to the directory <tt>{{storage_root}}/www/default</tt> on this machine. They will appear directly and immediately on the web.</li>
<li>The websites set up on this machine are listed in the table below with where to put the files for each website.
</li>
<li>The websites set up on this machine are listed in the table below with where to put the files for each website.</li>
<table id="web_domains_existing" class="table col-12" style="margin-bottom: 1em;">
<caption></caption>
<table id="web_domains_existing" class="table" style="margin-bottom: 1em; width: auto;">
<thead>
<tr>
<th>Site</th>
<th>Directory for Files</th>
<th/>
</tr>
</thead>
<tbody>
</tbody>
</table>
<p>To add a domain to this table, create a dummy <a href="#users" onclick="return show_panel(this);">mail user</a> or
<a href="#aliases" onclick="return show_panel(this);">alias</a> on the domain first and see the <a
href="https://mailinabox.email/guide.html#domain-name-configuration">setup guide</a> for adding nameserver records
to the new domain at your registrar (but <i>not</i> glue records).</p>
<p>To add a domain to this table, create a dummy <a href="#users" onclick="return show_panel(this);">mail user</a> or <a href="#aliases" onclick="return show_panel(this);">alias</a> on the domain first and see the <a href="https://mailinabox.email/guide.html#domain-name-configuration">setup guide</a> for adding nameserver records to the new domain at your registrar (but <i>not</i> glue records).</p>
</ol>

View file

@ -1,3 +1,16 @@
<style>
.title {
margin: 1em;
text-align: center;
}
.subtitle {
margin: 2em;
text-align: center;
}
</style>
<h1 class="title">{{hostname}}</h1>
<p class="subtitle">Welcome to your Power Mail-in-a-Box control panel.</p>
<p class="subtitle">Welcome to your Mail-in-a-Box control panel.</p>

View file

@ -1,11 +1,22 @@
<style>
#wkd_table #uids {
white-space: pre-line;
#wkd_table .status-error {
color: rgb(140, 0, 0);
}
#wkd_table .domain-header {
margin-top: 0.5em;
margin-bottom: 0.5em;
#wkd_table .status-warning {
color: rgb(170, 120, 0);
}
#wkd_table .status-ok {
color: rgb(0, 140, 0);
}
#wkd_table .status-none {
color: rgb(190, 190, 190);
}
#wkd_table #uids {
white-space: pre-line;
}
</style>
@ -13,7 +24,7 @@
<tr>
<td style="vertical-align: middle; white-space: nowrap;" id="email">email@example.com</td>
<td id="key-dropdown" class="dropdown show" style="width: 100%;">
<button class="btn bg-light" style="width: 100%;" data-bs-toggle="dropdown" id="current-key">
<button class="btn bg-light" style="width: 100%;" data-toggle="dropdown" id="current-key">
</button>
<div class="dropdown-menu" style="width: 100%;" id="menu">
<button class="btn bg-light" style="width:100%;" id="key-none">
@ -22,22 +33,20 @@
<a>Do not serve a key in WKD.</a>
</button>
<button class="btn bg-light" style="width:100%" id="key-sample">
<div class="row">
<div class="col-6" id="fingerprint">
<b class="font-monospace status-text" id="fpr"></b><span id="subkeys"></span>
</div>
<div class="col-6">
<b>
<span class="sym" id="sign">S</span>
<span class="sym" id="cert">C</span>
<span class="sym" id="encr">E</span>
<span class="sym" id="auth">A</span>
</b>,
<span id="expire"><span class="status-text"></span></span>
<div>
<div style="float: left; padding-right: 20pt;" id="fingerprint">
</div>
<div style="float: right; padding-left: 20pt">
<b><a id="sign">S</a>
<a id="cert">C</a>
<a id="encr">E</a>
<a id="auth">A</a></b>,
<a id="expire"></a>
</div>
<br>
<div id="key-emails">
</div>
</div>
</button>
</div>
</td>
@ -59,8 +68,7 @@
<p>WKD (<b>W</b>eb <b>K</b>ey <b>D</b>irectory) is an
<b><a href="https://tools.ietf.org/id/draft-koch-openpgp-webkey-service-11.html">experimental feature</a></b>
that allows users to authoratively publish their public PGP keys on the web, via HTTPS.
</p>
that allows users to authoratively publish their public PGP keys on the web, via HTTPS.</p>
<p>Unlike other solutions (like public keyservers), WKD has the advantage that the owner
of the domain has some degree of control over what keys are published and as such there
is more certainity that the key actually belongs to it's owner.</p>
@ -71,8 +79,7 @@
If you have a separate server to host WKD, you can still use it instead of this box on a per-domain basis.
<br>
This box uses the Advanced Method to serve the keys. For example, to host your <code>@some.example.com</code> keys,
you can add a A, AAAA or CNAME record for <code>openpgpkey.some.example.com</code>. It will override the box's
records.
you can add a A, AAAA or CNAME record for <code>openpgpkey.some.example.com</code>. It will override the box's records.
<br><br>
There's not a way to "disable" WKD at the moment - but if you don't want to publish keys, or if you want to use the
Direct method somewhere else, you can always set the records to an unreachable destination
@ -87,22 +94,11 @@
You can add keys on the PGP Keyring Management menu.
</a>
<div class="input-group mt-3 mb-3">
<label for="wkd-show-all-entries" class="input-group-text"><b>Show all email addresses</b></label>
<div class="input-group-text">
<div class="form-switch">
<input type="checkbox" role="switch" id="wkd-show-all-entries" class="form-check-input" value=false
onclick="toggle_emails_with_no_pgp_key();">
</div>
</div>
</div>
<table id="wkd_table" class="table" style="width: 100%">
<caption></caption>
<thead>
<tr>
<th>Email Address</th>
<th></th>
<th>Key</th>
</tr>
</thead>
<tbody id="wkd_tbody">
@ -113,8 +109,6 @@
<script>
let dirty_config = {}
let toggleable_lines = []
let show_toggleable_lines = document.getElementById("wkd-show-all-entries").checked
function pretty_long_id(fpr) {
let plid = ""
for (let i = 6; i < 10; ++i) {
@ -151,9 +145,7 @@
let keyinfo = keys[key]
let skey = keyinfo.subkeys[0] // Master subkey
let fpr = option.find("#fingerprint")
fpr.find("#fpr").text(pretty_long_id(key))
fpr.find("#subkeys").text(` (${keyinfo.subkeys.length} subkey${keyinfo.subkeys.length == 1 ? "" : "s"})`)
option.find("#fingerprint").html(`<b>${pretty_long_id(key)}</b> (${keyinfo.subkeys.length} subkey${keyinfo.subkeys.length == 1 ? "" : "s"})`)
option.click(()=>{
$("#wkd_submit").attr("disabled", false)
dirty_config[email] = key
@ -162,48 +154,46 @@
option.appendTo(menurep.find("#menu"))
let classType = ""
let expire = option.find("#expire")
let exp = expire.find(".status-text")
let exp = option.find("#expire")
// Purpose and expiration
// For evaluation we're only going to use the master subkey
if (keyinfo.revoked) {
classType = "status-error"
exp.text(`revoked`)
exp.html(`revoked`)
} else if (skey.expired) {
classType = "status-error"
exp.text(`expired on ${skey.expires_date}`)
exp.html(`expired on ${skey.expires_date}`)
} else if (skey.expires && skey.expires_days <= 14) {
classType = "status-warning"
exp.text(`expires in ${skey.expires_days} days (${skey.expires_date})`)
exp.html(`expires in ${skey.expires_days} days (${skey.expires_date})`)
} else if (skey.expires) {
classType = "status-ok"
exp.text(`expires in ${skey.expires_days} days (${skey.expires_date})`)
exp.html(`expires in ${skey.expires_days} days (${skey.expires_date})`)
} else {
classType = "status-ok"
exp.text("does not expire")
exp.html("does not expire")
}
expire.addClass(classType)
fpr.addClass(classType)
exp.addClass(classType)
let s = option.find("#sign")
let c = option.find("#cert")
let e = option.find("#encr")
let a = option.find("#auth")
s.addClass(skey.sign ? classType : "status-na")
c.addClass(skey.cert ? classType : "status-na")
e.addClass(skey.encr ? classType : "status-na")
a.addClass(skey.auth ? classType : "status-na")
s.addClass(skey.sign ? classType : "status-none")
c.addClass(skey.cert ? classType : "status-none")
e.addClass(skey.encr ? classType : "status-none")
a.addClass(skey.auth ? classType : "status-none")
let txt = ""
let n_emails = keyinfo.ids_emails.length
if (n_emails == 1) {
txt = `<b class="font-monospace">${email}</b>`
txt = `<code><b>${email}</b></code>`
} else if (email.length >= 70) {
// Absurd situation, but can happen!
// We'll only
txt = `<b class="font-monospace">${email}</b> and ${n_emails - 1} other${n_emails == 2 ? "" : "s"}`
txt = `<code><b>${email}</b></code> and ${n_emails - 1} other${n_emails == 2 ? "" : "s"}`
} else {
let buf = 70 - email.length
let others = n_emails - 1
@ -215,7 +205,7 @@
return x.length == y.length ? x.localeCompare(y) : x.length > y.length ? -1 : 1
})
txt = `<b class="font-monospace">${email}</b>`
txt = `<code><b>${email}</b></code>`
// From the remaining emails, pick the longest ones within the buffer constraints
// If none, append the "and x others text"
@ -223,7 +213,7 @@
if (e.length <= buf) {
others--
buf -= e.length
txt += `, <span class="font-monospace">${e}</span>`
txt += `, <code>${e}</code>`
}
});
@ -249,23 +239,14 @@
function generate_wkd_dropdowns(wkd_info) {
$("#wkd_tbody").html("")
Object.keys(wkd_info.wkd).forEach(domain => {
$(`<tr><td colspan="2" class="bg-light"><h4 class="domain-header">${domain}</h4></td></tr>`).appendTo("#wkd_tbody")
$(`<tr><td colspan="3"><h4>${domain}</h4></td></tr>`).appendTo("#wkd_tbody")
Object.keys(wkd_info.wkd[domain]).forEach(email => {
let menu = generate_wkd_menu(email, wkd_info.wkd[domain][email], wkd_info.keys)
menu.appendTo("#wkd_tbody")
// No possible keys, we can hide this line to save space
if (wkd_info.wkd[domain][email].options.length === 0) {
toggleable_lines.push(menu)
}
generate_wkd_menu(email, wkd_info.wkd[domain][email], wkd_info.keys).appendTo("#wkd_tbody")
})
});
toggle_emails_with_no_pgp_key()
}
function show_wkd() {
toggleable_lines = []
$("#wkd_tbody").html("<tr><td colspan='2' class='text-muted'>Loading...</td></tr>")
$("#wkd_tbody").html("<tr><td class='text-muted'>Loading...</td></tr>")
api(
"/system/pgp/wkd",
"GET",
@ -295,12 +276,4 @@
}
)
}
function toggle_emails_with_no_pgp_key() {
let show_toggleable_lines = document.getElementById("wkd-show-all-entries").checked
toggleable_lines.forEach(line => {
line.toggle(show_toggleable_lines)
});
}
</script>

View file

@ -6,58 +6,47 @@ import os.path
# THE ENVIRONMENT FILE AT /etc/mailinabox.conf
def load_environment():
# Load settings from /etc/mailinabox.conf.
return load_env_vars_from_file("/etc/mailinabox.conf")
def load_env_vars_from_file(fn):
# Load settings from a KEY=VALUE file.
import collections
env = collections.OrderedDict()
for line in open(fn):
env.setdefault(*line.strip().split("=", 1))
for line in open(fn): env.setdefault(*line.strip().split("=", 1))
return env
def save_environment(env):
with open("/etc/mailinabox.conf", "w") as f:
for k, v in env.items():
f.write("%s=%s\n" % (k, v))
# THE SETTINGS FILE AT STORAGE_ROOT/settings.yaml.
def write_settings(config, env):
import rtyaml
fn = os.path.join(env['STORAGE_ROOT'], 'settings.yaml')
with open(fn, "w") as f:
f.write(rtyaml.dump(config))
def load_settings(env):
import rtyaml
fn = os.path.join(env['STORAGE_ROOT'], 'settings.yaml')
try:
config = rtyaml.load(open(fn, "r"))
if not isinstance(config, dict):
raise ValueError() # caught below
if not isinstance(config, dict): raise ValueError() # caught below
return config
except:
return { }
# UTILITIES
def safe_domain_name(name):
# Sanitize a domain name so it is safe to use as a file name on disk.
import urllib.parse
return urllib.parse.quote(name, safe='')
def sort_domains(domain_names, env):
# Put domain names in a nice sorted order.
@ -79,20 +68,17 @@ def sort_domains(domain_names, env):
zones[domain] = domain
# Sort the zones.
zone_domains = sorted(
zones.values(),
zone_domains = sorted(zones.values(),
key = lambda d : (
# PRIMARY_HOSTNAME or the zone that contains it is always first.
not (d == env['PRIMARY_HOSTNAME'] or env['PRIMARY_HOSTNAME'].
endswith("." + d)),
not (d == env['PRIMARY_HOSTNAME'] or env['PRIMARY_HOSTNAME'].endswith("." + d)),
# Then just dumb lexicographically.
d,
))
# Now sort the domain names that fall within each zone.
domain_names = sorted(
domain_names,
domain_names = sorted(domain_names,
key = lambda d : (
# First by zone.
zone_domains.index(zones[d]),
@ -109,28 +95,18 @@ def sort_domains(domain_names, env):
return domain_names
def sort_email_addresses(email_addresses, env):
email_addresses = set(email_addresses)
domains = set(
email.split("@", 1)[1] for email in email_addresses if "@" in email)
domains = set(email.split("@", 1)[1] for email in email_addresses if "@" in email)
ret = []
for domain in sort_domains(domains, env):
domain_emails = set(email for email in email_addresses
if email.endswith("@" + domain))
domain_emails = set(email for email in email_addresses if email.endswith("@" + domain))
ret.extend(sorted(domain_emails))
email_addresses -= domain_emails
ret.extend(sorted(email_addresses)) # whatever is left
return ret
def shell(method,
cmd_args,
env={},
capture_stderr=False,
return_bytes=False,
trap=False,
input=None):
def shell(method, cmd_args, env={}, capture_stderr=False, return_bytes=False, trap=False, input=None):
# A safe way to execute processes.
# Some processes like apt-get require being given a sane PATH.
import subprocess
@ -152,21 +128,18 @@ def shell(method,
except subprocess.CalledProcessError as e:
ret = e.output
code = e.returncode
if not return_bytes and isinstance(ret, bytes):
ret = ret.decode("utf8")
if not return_bytes and isinstance(ret, bytes): ret = ret.decode("utf8")
if not trap:
return ret
else:
return code, ret
def create_syslog_handler():
import logging.handlers
handler = logging.handlers.SysLogHandler(address='/dev/log')
handler.setLevel(logging.WARNING)
return handler
def du(path):
# Computes the size of all files in the path, like the `du` command.
# Based on http://stackoverflow.com/a/17936789. Takes into account
@ -186,12 +159,10 @@ def du(path):
total_size += stat.st_size
return total_size
def wait_for_service(port, public, env, timeout):
# Block until a service on a given port (bound privately or publicly)
# is taking connections, with a maximum timeout.
import socket
import time
import socket, time
start = time.perf_counter()
while True:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
@ -204,10 +175,19 @@ def wait_for_service(port, public, env, timeout):
return False
time.sleep(min(timeout/4, 1))
def fix_boto():
# Google Compute Engine instances install some Python-2-only boto plugins that
# conflict with boto running under Python 3. Disable boto's default configuration
# file prior to importing boto so that GCE's plugin is not loaded:
import os
os.environ["BOTO_CONFIG"] = "/etc/boto3.cfg"
def get_php_version():
# Gets the version of PHP installed in the system.
return shell("check_output", ["/usr/bin/php", "-v"])[4:7]
os_codes = {None, "Debian10", "Ubuntu2004"}
def get_os_code():
# Massive mess incoming
dist = shell("check_output", ["/usr/bin/lsb_release", "-is"]).strip()
@ -221,8 +201,6 @@ def get_os_code():
elif dist == "Ubuntu":
if version == "20.04":
return "Ubuntu2004"
elif version == "22.04":
return "Ubuntu2204"
return None

View file

@ -2,20 +2,14 @@
# domains for which a mail account has been set up.
########################################################################
import os.path
import re
import rtyaml
import os.path, re, rtyaml
from mailconfig import get_mail_domains
from dns_update import get_custom_dns_config, get_dns_zones
from ssl_certificates import get_ssl_certificates, get_domain_ssl_files, check_certificate
from utils import shell, safe_domain_name, sort_domains, get_php_version
def get_web_domains(env,
include_www_redirects=True,
include_auto=True,
exclude_dns_elsewhere=True):
def get_web_domains(env, include_www_redirects=True, include_auto=True, exclude_dns_elsewhere=True):
# What domains should we serve HTTP(S) for?
domains = set()
@ -34,20 +28,14 @@ def get_web_domains(env,
# Add Autoconfiguration domains for domains that there are user accounts at:
# 'autoconfig.' for Mozilla Thunderbird auto setup.
# 'autodiscover.' for ActiveSync autodiscovery (Z-Push).
domains |= set(
'autoconfig.' + maildomain
for maildomain in get_mail_domains(env, users_only=True))
domains |= set(
'autodiscover.' + maildomain
for maildomain in get_mail_domains(env, users_only=True))
domains |= set('autoconfig.' + maildomain for maildomain in get_mail_domains(env, users_only=True))
domains |= set('autodiscover.' + maildomain for maildomain in get_mail_domains(env, users_only=True))
# 'mta-sts.' for MTA-STS support for all domains that have email addresses.
domains |= set('mta-sts.' + maildomain
for maildomain in get_mail_domains(env))
domains |= set('mta-sts.' + maildomain for maildomain in get_mail_domains(env))
# 'openpgpkey.' for WKD support
domains |= set('openpgpkey.' + maildomain
for maildomain in get_mail_domains(env))
domains |= set('openpgpkey.' + maildomain for maildomain in get_mail_domains(env))
if exclude_dns_elsewhere:
# ...Unless the domain has an A/AAAA record that maps it to a different
@ -64,17 +52,14 @@ def get_web_domains(env,
return domains
def get_domains_with_a_records(env):
domains = set()
dns = get_custom_dns_config(env)
for domain, rtype, value, ttl in dns:
if rtype == "CNAME" or (rtype in ("A", "AAAA")
and value not in ("local", env['PUBLIC_IP'])):
if rtype == "CNAME" or (rtype in ("A", "AAAA") and value not in ("local", env['PUBLIC_IP'])):
domains.add(domain)
return domains
def get_web_domains_with_root_overrides(env):
# Load custom settings so we can tell what domains have a redirect or proxy set up on '/',
# which means static hosting is not happening.
@ -83,22 +68,18 @@ def get_web_domains_with_root_overrides(env):
if os.path.exists(nginx_conf_custom_fn):
custom_settings = rtyaml.load(open(nginx_conf_custom_fn))
for domain, settings in custom_settings.items():
for type, value in [('redirect', settings.get('redirects',
{}).get('/')),
('proxy', settings.get('proxies',
{}).get('/'))]:
for type, value in [('redirect', settings.get('redirects', {}).get('/')),
('proxy', settings.get('proxies', {}).get('/'))]:
if value:
root_overrides[domain] = (type, value)
return root_overrides
DOMAIN_EXTERNAL = -1
DOMAIN_PRIMARY = 1
DOMAIN_WWW = 2
DOMAIN_REDIRECT = 4
DOMAIN_WKD = 8
def get_web_domain_flags(env):
flags = dict()
zones = get_dns_zones(env)
@ -127,24 +108,19 @@ def get_web_domain_flags(env):
# Last check for websites hosted elsewhere
for d in flags.keys():
if d in external:
# -1 = All bits set to 1, assuming twos-complement
flags[d] = DOMAIN_EXTERNAL
flags[d] = DOMAIN_EXTERNAL # -1 = All bits set to 1, assuming twos-complement
return flags
def do_web_update(env):
# Pre-load what SSL certificates we will use for each domain.
ssl_certificates = get_ssl_certificates(env)
# Build an nginx configuration file.
nginx_conf = open(
os.path.join(os.path.dirname(__file__),
"../conf/nginx-top.conf")).read()
nginx_conf = open(os.path.join(os.path.dirname(__file__), "../conf/nginx-top.conf")).read()
nginx_conf = re.sub("{{phpver}}", get_php_version(), nginx_conf)
# Add upstream additions
nginx_upstream_include = os.path.join(env["STORAGE_ROOT"], "www",
".upstream.conf")
nginx_upstream_include = os.path.join(env["STORAGE_ROOT"], "www", ".upstream.conf")
if not os.path.exists(nginx_upstream_include):
with open(nginx_upstream_include, "a+") as f:
f.writelines([
@ -157,23 +133,14 @@ def do_web_update(env):
nginx_conf += "\ninclude %s;\n" % (nginx_upstream_include)
# Load the templates.
template0 = open(
os.path.join(os.path.dirname(__file__), "../conf/nginx.conf")).read()
template1 = open(
os.path.join(os.path.dirname(__file__),
"../conf/nginx-alldomains.conf")).read()
template2 = open(
os.path.join(os.path.dirname(__file__),
"../conf/nginx-primaryonly.conf")).read()
template0 = open(os.path.join(os.path.dirname(__file__), "../conf/nginx.conf")).read()
template1 = open(os.path.join(os.path.dirname(__file__), "../conf/nginx-alldomains.conf")).read()
template2 = open(os.path.join(os.path.dirname(__file__), "../conf/nginx-primaryonly.conf")).read()
template3 = "\trewrite ^(.*) https://$REDIRECT_DOMAIN$1 permanent;\n"
template4 = open(
os.path.join(os.path.dirname(__file__),
"../conf/nginx-openpgpkey.conf")).read()
template4 = open(os.path.join(os.path.dirname(__file__), "../conf/nginx-openpgpkey.conf")).read()
# Add the PRIMARY_HOST configuration first so it becomes nginx's default server.
nginx_conf += make_domain_config(env['PRIMARY_HOSTNAME'],
[template0, template1, template2],
ssl_certificates, env)
nginx_conf += make_domain_config(env['PRIMARY_HOSTNAME'], [template0, template1, template2], ssl_certificates, env)
# Add configuration all other web domains.
pairs = list(get_web_domain_flags(env).items())
@ -187,20 +154,14 @@ def do_web_update(env):
if flags & DOMAIN_WWW == 0:
# This is a regular domain.
if flags & DOMAIN_WKD == DOMAIN_WKD:
nginx_conf += make_domain_config(
domain, [template0, template1, template4],
ssl_certificates, env)
nginx_conf += make_domain_config(domain, [template0, template1, template4], ssl_certificates, env)
elif flags & DOMAIN_REDIRECT == 0:
nginx_conf += make_domain_config(domain,
[template0, template1],
ssl_certificates, env)
nginx_conf += make_domain_config(domain, [template0, template1], ssl_certificates, env)
else:
nginx_conf += make_domain_config(domain, [template0],
ssl_certificates, env)
nginx_conf += make_domain_config(domain, [template0], ssl_certificates, env)
else:
# Add default 'www.' redirect.
nginx_conf += make_domain_config(domain, [template0, template3],
ssl_certificates, env)
nginx_conf += make_domain_config(domain, [template0, template3], ssl_certificates, env)
# Did the file change? If not, don't bother writing & restarting nginx.
nginx_conf_fn = "/etc/nginx/conf.d/local.conf"
@ -221,7 +182,6 @@ def do_web_update(env):
return "web updated\n"
def make_domain_config(domain, templates, ssl_certificates, env):
# GET SOME VARIABLES
@ -246,9 +206,7 @@ def make_domain_config(domain, templates, ssl_certificates, env):
finally:
f.close()
return sha1.hexdigest()
nginx_conf_extra += "\t# ssl files sha1: %s / %s\n" % (hashfile(
tls_cert["private-key"]), hashfile(tls_cert["certificate"]))
nginx_conf_extra += "\t# ssl files sha1: %s / %s\n" % (hashfile(tls_cert["private-key"]), hashfile(tls_cert["certificate"]))
# Add in any user customizations in YAML format.
hsts = "yes"
@ -293,8 +251,7 @@ def make_domain_config(domain, templates, ssl_certificates, env):
nginx_conf_extra += "\n\t\talias %s;" % alias
nginx_conf_extra += "\n\t}\n"
for path, url in yaml.get("redirects", {}).items():
nginx_conf_extra += "\trewrite %s %s permanent;\n" % (path,
url)
nginx_conf_extra += "\trewrite %s %s permanent;\n" % (path, url)
# override the HSTS directive type
hsts = yaml.get("hsts", hsts)
@ -306,9 +263,7 @@ def make_domain_config(domain, templates, ssl_certificates, env):
nginx_conf_extra += "\tadd_header Strict-Transport-Security \"max-age=15768000; includeSubDomains; preload\" always;\n"
# Add in any user customizations in the includes/ folder.
nginx_conf_custom_include = os.path.join(
env["STORAGE_ROOT"], "www",
safe_domain_name(domain) + ".conf")
nginx_conf_custom_include = os.path.join(env["STORAGE_ROOT"], "www", safe_domain_name(domain) + ".conf")
if not os.path.exists(nginx_conf_custom_include):
with open(nginx_conf_custom_include, "a+") as f:
f.writelines([
@ -325,75 +280,57 @@ def make_domain_config(domain, templates, ssl_certificates, env):
# of the previous template.
nginx_conf = "# ADDITIONAL DIRECTIVES HERE\n"
for t in templates + [nginx_conf_extra]:
nginx_conf = re.sub("[ \t]*# ADDITIONAL DIRECTIVES HERE *\n", t,
nginx_conf)
nginx_conf = re.sub("[ \t]*# ADDITIONAL DIRECTIVES HERE *\n", t, nginx_conf)
# Replace substitution strings in the template & return.
nginx_conf = nginx_conf.replace("$STORAGE_ROOT", env['STORAGE_ROOT'])
nginx_conf = nginx_conf.replace("$HOSTNAME", domain)
nginx_conf = nginx_conf.replace("$ROOT", root)
nginx_conf = nginx_conf.replace("$SSL_KEY", tls_cert["private-key"])
nginx_conf = nginx_conf.replace("$SSL_CERTIFICATE",
tls_cert["certificate"])
nginx_conf = nginx_conf.replace(
"$REDIRECT_DOMAIN",
re.sub(r"^www\.", "",
domain)) # for default www redirects to parent domain
nginx_conf = nginx_conf.replace("$SSL_CERTIFICATE", tls_cert["certificate"])
nginx_conf = nginx_conf.replace("$REDIRECT_DOMAIN", re.sub(r"^www\.", "", domain)) # for default www redirects to parent domain
return nginx_conf
def get_web_root(domain, env, test_exists=True):
# Try STORAGE_ROOT/web/domain_name if it exists, but fall back to STORAGE_ROOT/web/default.
for test_domain in (domain, 'default'):
root = os.path.join(env["STORAGE_ROOT"], "www",
safe_domain_name(test_domain))
if os.path.exists(root) or not test_exists:
break
root = os.path.join(env["STORAGE_ROOT"], "www", safe_domain_name(test_domain))
if os.path.exists(root) or not test_exists: break
return root
def is_default_web_root(domain, env):
root = os.path.join(env["STORAGE_ROOT"], "www", safe_domain_name(domain))
return not os.path.exists(root)
def get_web_domains_info(env):
www_redirects = set(get_web_domains(env)) - \
set(get_web_domains(env, include_www_redirects=False))
www_redirects = set(get_web_domains(env)) - set(get_web_domains(env, include_www_redirects=False))
has_root_proxy_or_redirect = set(get_web_domains_with_root_overrides(env))
ssl_certificates = get_ssl_certificates(env)
# for the SSL config panel, get cert status
def check_cert(domain):
try:
tls_cert = get_domain_ssl_files(domain,
ssl_certificates,
env,
allow_missing_cert=True)
tls_cert = get_domain_ssl_files(domain, ssl_certificates, env, allow_missing_cert=True)
except OSError: # PRIMARY_HOSTNAME cert is missing
tls_cert = None
if tls_cert is None:
return ("danger", "No certificate installed.")
cert_status, cert_status_details = check_certificate(
domain, tls_cert["certificate"], tls_cert["private-key"])
if tls_cert is None: return ("danger", "No certificate installed.")
cert_status, cert_status_details = check_certificate(domain, tls_cert["certificate"], tls_cert["private-key"])
if cert_status == "OK":
return ("success", "Signed & valid. " + cert_status_details)
elif cert_status == "SELF-SIGNED":
return ("warning",
"Self-signed. Get a signed certificate to stop warnings.")
return ("warning", "Self-signed. Get a signed certificate to stop warnings.")
else:
return ("danger", "Certificate has a problem: " + cert_status)
return [{
"domain":
domain,
"root":
get_web_root(domain, env),
"custom_root":
get_web_root(domain, env, test_exists=False),
"ssl_certificate":
check_cert(domain),
"static_enabled":
domain not in (www_redirects | has_root_proxy_or_redirect),
} for domain in get_web_domains(env)]
return [
{
"domain": domain,
"root": get_web_root(domain, env),
"custom_root": get_web_root(domain, env, test_exists=False),
"ssl_certificate": check_cert(domain),
"static_enabled": domain not in (www_redirects | has_root_proxy_or_redirect),
}
for domain in get_web_domains(env)
]

View file

@ -2,14 +2,7 @@
# WDK (Web Key Directory) Manager: Facilitates discovery of keys by third-parties
# Current relevant documents: https://tools.ietf.org/id/draft-koch-openpgp-webkey-service-11.html
import pgp
import utils
import rtyaml
import mailconfig
import copy
import shutil
import os
import re
import pgp, utils, rtyaml, mailconfig, copy, shutil, os, re
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.backends import default_backend
@ -17,25 +10,21 @@ env = utils.load_environment()
wkdpath = f"{env['GNUPGHOME']}/.wkdlist.yml"
class WKDError(Exception):
"""
Errors specifically related to WKD.
"""
def __init__(self, msg):
self.message = msg
def __str__(self):
return self.message
def sha1(message):
h = hashes.Hash(hashes.SHA1(), default_backend())
h.update(message)
return h.finalize()
def zbase32(digest):
# Crudely check if all quintets are complete
if len(digest) % 5 != 0:
@ -68,7 +57,11 @@ def strip_and_export(fpr, target_email, buffer=None, context=None):
return None
# Horrible hack: Because it's a reference (aka pointer), we can pass these around the functions
statusref = {"seq_read": False, "sequence": [], "seq_number": -1}
statusref = {
"seq_read": False,
"sequence": [],
"seq_number": -1
}
def parse_key_dump(dump):
UID_REGEX = r".*:.* <(.*)>:.*:([0-9]),.*"
@ -92,6 +85,7 @@ def strip_and_export(fpr, target_email, buffer=None, context=None):
statusref["sequence"] += ["deluid", "save"]
statusref["seq_read"] = True
def interaction(request, prompt):
if request in ["GOT_IT", "KEY_CONSIDERED", "KEYEXPIRED", ""]:
return 0
@ -114,7 +108,6 @@ def strip_and_export(fpr, target_email, buffer=None, context=None):
context.interact(k, interaction, sink=buffer)
return pgp.export_key(fpr, context)
def email_compatible_with_key(email, fingerprint):
# 1. Does the user exist?
if not email in mailconfig.get_all_mail_addresses(env):
@ -128,18 +121,13 @@ def email_compatible_with_key(email, fingerprint):
# 3. Does the key have a user id with the email of the user?
if email not in [u.email for u in key.uids]:
raise WKDError(
f"The key \"{fingerprint}\" has no such UID with the email \"{email}\"!"
)
raise WKDError(f"The key \"{fingerprint}\" has no such UID with the email \"{email}\"!")
return key
return None
# Gets a table with all the keys that can be served for each user and/or alias
def get_user_fpr_maps():
uk_maps = {}
for email in mailconfig.get_all_mail_addresses(env):
@ -153,10 +141,7 @@ def get_user_fpr_maps():
pass
return uk_maps
# Gets the current WKD configuration
def get_wkd_config():
# Test
try:
@ -174,12 +159,9 @@ def get_wkd_config():
except:
return {}
# Sets the WKD configuration. Takes a dictionary {email: fingerprint}.
# email: An user or alias on this box. e.g. "administrator@example.com"
# fingerprint: The fingerprint of the key we want to bind it to. e.g "0123456789ABCDEF0123456789ABCDEF01234567"
def update_wkd_config(config_sample):
config = dict(config_sample)
for email, fingerprint in config_sample.items():
@ -195,11 +177,8 @@ def update_wkd_config(config_sample):
with open(wkdpath, "w") as wkdfile:
wkdfile.write(rtyaml.dump(config))
# Looks for incompatible email/key pairs on the WKD configuration file
# and returns the uid indexes for compatible email/key pairs
def parse_wkd_list():
removed = []
uidlist = []
@ -219,8 +198,7 @@ def parse_wkd_list():
key = email_compatible_with_key(u, k)
# Key is compatible
# Swap with the full-length fingerprint (if somehow this was changed by hand)
writeable[u] = key.fpr
writeable[u] = key.fpr # Swap with the full-length fingerprint (if somehow this was changed by hand)
uidlist.append((u, key.fpr))
except:
writeable.pop(u)
@ -230,10 +208,8 @@ def parse_wkd_list():
wkdfile.write(rtyaml.dump(writeable))
return (removed, uidlist)
WKD_LOCATION = "/var/lib/mailinabox/wkd/"
def build_wkd():
# Clean everything
try:

View file

@ -1,7 +0,0 @@
from daemon import app
import auth, utils
app.logger.addHandler(utils.create_syslog_handler())
if __name__ == "__main__":
app.run(port=10222)

View file

@ -3,12 +3,7 @@ Mail-in-a-Box Security Guide
Mail-in-a-Box turns a fresh Ubuntu 18.04 LTS 64-bit machine into a mail server appliance by installing and configuring various components.
This page documents the security posture of Mail-in-a-Box. The term “box” is used below to mean a configured Mail-in-a-Box.
Reporting Security Vulnerabilities
----------------------------------
Security vulnerabilities should be reported to the [project's maintainer](https://joshdata.me) via email.
This page documents the security features of Mail-in-a-Box. The term “box” is used below to mean a configured Mail-in-a-Box.
Threat Model
------------
@ -54,7 +49,9 @@ Additionally:
### Password Storage
The passwords for mail users are stored on disk using the [SHA512-CRYPT](http://man7.org/linux/man-pages/man3/crypt.3.html) hashing scheme. ([source](management/mailconfig.py)) Password changes (as well as changes to control panel two-factor authentication settings) expire any control panel login sessions.
The passwords for mail users are stored on disk using the [SHA512-CRYPT](http://man7.org/linux/man-pages/man3/crypt.3.html) hashing scheme. ([source](management/mailconfig.py))
When using the web-based administrative control panel, after logging in an API key is placed in the browser's local storage (rather than, say, the user's actual password). The API key is an HMAC based on the user's email address and current password, and it is keyed by a secret known only to the control panel service. By resetting an administrator's password, any HMACs previously generated for that user will expire.
### Console access
@ -68,7 +65,7 @@ If DNSSEC is enabled at the box's domain name's registrar, the SSHFP record that
`fail2ban` provides some protection from brute-force login attacks (repeated logins that guess account passwords) by blocking offending IP addresses at the network level.
The following services are protected: SSH, IMAP (dovecot), SMTP submission (postfix), webmail (roundcube), Nextcloud/CalDAV/CardDAV (over HTTP), and the Mail-in-a-Box control panel (over HTTP).
The following services are protected: SSH, IMAP (dovecot), SMTP submission (postfix), webmail (roundcube), Nextcloud/CalDAV/CardDAV (over HTTP), and the Mail-in-a-Box control panel & munin (over HTTP).
Some other services running on the box may be missing fail2ban filters.

View file

@ -2,7 +2,7 @@
#########################################################
# This script is intended to be run like this:
#
# curl -L https://power-mailinabox.net/setup.sh | sudo bash
# curl https://dvn.pt/power-miab | sudo bash
#
#########################################################
@ -20,7 +20,6 @@ if [ ! -f /usr/bin/lsb_release ]; then
echo "* Debian 10 (buster)"
echo "* Debian 11 (bullseye)"
echo "* Ubuntu 20.04 LTS (Focal Fossa)"
echo "* Ubuntu 22.04 LTS (Jammy Jellyfish)"
exit 1
fi
@ -32,44 +31,16 @@ fi
if [ -z "$TAG" ]; then
# Make sure we're running on the correct operating system
OS=$(lsb_release -d | sed 's/.*:\s*//')
if [ "$OS" == "Debian GNU/Linux 11 (bullseye)" ] ||
[ "$(echo $OS | grep -o 'Ubuntu 20.04')" == "Ubuntu 20.04" ] ||
[ "$(echo $OS | grep -o 'Ubuntu 22.04')" == "Ubuntu 22.04" ]
if [ "$OS" == "Debian GNU/Linux 10 (buster)" ] ||
[ "$OS" == "Debian GNU/Linux 11 (bullseye)" ] ||
[ "$(echo $OS | grep -o 'Ubuntu 20.04')" == "Ubuntu 20.04" ]
then
TAG=v60.5
elif [ "$OS" == "Debian GNU/Linux 10 (buster)" ]; then
echo "We are going to install the last version of Power Mail-in-a-Box supporting Debian 10 (buster)."
echo "IF THIS IS A NEW INSTALLATION, STOP NOW, AND USE A SUPPORTED DISTRIBUTION INSTEAD (ONE OF THESE):"
echo "* Debian 11 (bullseye)"
echo "* Ubuntu 20.04 LTS (Focal Fossa)"
echo "* Ubuntu 22.04 LTS (Jammy Jellyfish)"
echo
echo "IF YOU'RE UPGRADING THE BOX TO THE LATEST VERSION, PLEASE VISIT THIS PAGE FOR NOTES ON HOW TO"
echo "UPGRADE YOUR SISTEM TO DEBIAN 11 (bullseye)"
echo "https://power-mailinabox.net/buster-eol"
while true; do
read -p "Do you want to proceed? ([Y]es/[N]o) " yn
case $yn in
Yes | Y | yes | y )
break
;;
No | N | no | n )
echo "Installation cancelled."
exit 1
;;
* )
;;
esac
done
TAG=v56.5
TAG=v55.0
else
echo "This script must be run on a system running one of the following OS-es:"
echo "* Debian 10 (buster)"
echo "* Debian 11 (bullseye)"
echo "* Ubuntu 20.04 LTS (Focal Fossa)"
echo "* Ubuntu 22.04 LTS (Jammy Jellyfish)"
exit 1
fi
fi
@ -86,7 +57,7 @@ if [ ! -d $HOME/mailinabox ]; then
echo Downloading Mail-in-a-Box $TAG. . .
git clone \
-b $TAG --depth 1 \
https://git.nibbletools.com/beenull/power-mailinabox \
https://github.com/ddavness/power-mailinabox \
$HOME/mailinabox \
< /dev/null 2> /dev/null

View file

@ -10,9 +10,16 @@
source setup/functions.sh # load our functions
source /etc/mailinabox.conf # load global vars
# Install the packages.
#
# * nsd: The non-recursive nameserver that publishes our DNS records.
# * ldnsutils: Helper utilities for signing DNSSEC zones.
# * openssh-client: Provides ssh-keyscan which we use to create SSHFP records.
echo "Installing nsd (DNS server)..."
apt_install ldnsutils openssh-client
# Prepare nsd's configuration.
# We configure nsd before installation as we only want it to bind to some addresses
# and it otherwise will have port / bind conflicts with bind9 used as the local resolver
mkdir -p /var/run/nsd
mkdir -p /etc/nsd
mkdir -p /etc/nsd/zones
@ -39,6 +46,18 @@ server:
EOF
# Add log rotation
cat > /etc/logrotate.d/nsd <<EOF;
/var/log/nsd.log {
weekly
missingok
rotate 12
compress
delaycompress
notifempty
}
EOF
# Since we have bind9 listening on localhost for locally-generated
# DNS queries that require a recursive nameserver, and the system
# might have other network interfaces for e.g. tunnelling, we have
@ -55,25 +74,8 @@ echo "include: /etc/nsd/nsd.conf.d/*.conf" >> /etc/nsd/nsd.conf;
# now be stored in /etc/nsd/nsd.conf.d.
rm -f /etc/nsd/zones.conf
# Add log rotation
cat > /etc/logrotate.d/nsd <<EOF;
/var/log/nsd.log {
weekly
missingok
rotate 12
compress
delaycompress
notifempty
}
EOF
# Install the packages.
#
# * nsd: The non-recursive nameserver that publishes our DNS records.
# * ldnsutils: Helper utilities for signing DNSSEC zones.
# * openssh-client: Provides ssh-keyscan which we use to create SSHFP records.
echo "Installing nsd (DNS server)..."
apt_install nsd ldnsutils openssh-client
# Attempting a late install of nsd (after configuration)
apt_install nsd
# Create DNSSEC signing keys.

View file

@ -14,7 +14,7 @@ function hide_output {
# Execute command, redirecting stderr/stdout to the temporary file. Since we
# check the return code ourselves, disable 'set -e' temporarily.
set +e
"$@" &> "$OUTPUT"
"$@" &> $OUTPUT
E=$?
set -e
@ -24,7 +24,7 @@ function hide_output {
echo
echo FAILED: "$@"
echo -----------------------------------------
cat "$OUTPUT"
cat $OUTPUT
echo -----------------------------------------
exit $E
fi
@ -222,18 +222,17 @@ function git_clone {
}
function php_version {
php --version | head -n 1 | cut -d " " -f 2 | cut -d "." -f 1,2
php --version | head -n 1 | cut -d " " -f 2 | cut -c 1-3
}
function python_version {
python3 --version | cut -d " " -f 2 | cut -d "." -f 1,2
python3 --version | cut -d " " -f 2 | cut -c 1-3
}
export OS_UNSUPPORTED=0
export OS_DEBIAN_10=1
export OS_UBUNTU_2004=2
export OS_DEBIAN_11=3
export OS_UBUNTU_2204=4
function get_os_code {
# A lot of if-statements here - dirty code looking tasting today
@ -252,9 +251,6 @@ function get_os_code {
if [[ $VER == "20.04" ]]; then
echo $OS_UBUNTU_2004
return 0
elif [[ $VER == "22.04" ]]; then
echo $OS_UBUNTU_2204
return 0
fi
fi

View file

@ -89,8 +89,6 @@ management/editconf.py /etc/dovecot/conf.d/10-ssl.conf \
"ssl_min_protocol=TLSv1.2" \
"ssl_cipher_list=ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384" \
"ssl_prefer_server_ciphers=no" \
"ssl_dh_parameters_length=2048" \
"ssl_dh=<$STORAGE_ROOT/ssl/dh2048.pem"
# Disable in-the-clear IMAP/POP because there is no reason for a user to transmit
# login credentials outside of an encrypted connection. Only the over-TLS versions
@ -187,7 +185,6 @@ plugin {
sieve = $STORAGE_ROOT/mail/sieve/%d/%n.sieve
sieve_dir = $STORAGE_ROOT/mail/sieve/%d/%n
sieve_redirect_envelope_from = recipient
sieve_vacation_send_from_recipient = yes
}
EOF

View file

@ -13,8 +13,8 @@
# destinations according to aliases, and passses email on to
# another service for local mail delivery.
#
# The first hop in local mail delivery is to spampd via
# LMTP. spampd then passes mail over to Dovecot for
# The first hop in local mail delivery is to Spamassassin via
# LMTP. Spamassassin then passes mail over to Dovecot for
# storage in the user's mailbox.
#
# Postfix also listens on ports 465/587 (SMTPS, SMTP+STARTLS) for
@ -42,7 +42,7 @@ source /etc/mailinabox.conf # load global vars
# * `ca-certificates`: A trust store used to squelch postfix warnings about
# untrusted opportunistically-encrypted connections.
echo "Installing Postfix (SMTP server)..."
apt_install postfix postfix-sqlite postfix-pcre postgrey ca-certificates libsasl2-modules
apt_install postfix postfix-sqlite postfix-pcre postgrey ca-certificates
# ### Basic Settings
@ -58,7 +58,7 @@ management/editconf.py /etc/postfix/main.cf \
smtp_bind_address=$PRIVATE_IP \
smtp_bind_address6=$PRIVATE_IPV6 \
myhostname=$PRIMARY_HOSTNAME\
smtpd_banner="\$myhostname ESMTP Power Mail-in-a-Box (Postfix)" \
smtpd_banner="\$myhostname ESMTP Hi, I'm a Power Mail-in-a-Box (Debian/Postfix)" \
mydestination=localhost
# Tweak some queue settings:
@ -122,7 +122,7 @@ sed -i "s/PUBLIC_IP/$PUBLIC_IP/" /etc/postfix/outgoing_mail_header_filters
# the world are very far behind and if we disable too much, they may not be able to use TLS and
# won't fall back to cleartext. So we don't disable too much. smtpd_tls_exclude_ciphers applies to
# both port 25 and port 587, but because we override the cipher list for both, it probably isn't used.
# Use Mozilla's "Old" recommendations at https://ssl-config.mozilla.org/#server=postfix&version=3.4.8&config=old&openssl=1.1.1&guideline=5.6
# Use Mozilla's "Old" recommendations at https://ssl-config.mozilla.org/#server=postfix&server-version=3.3.0&config=old&openssl-version=1.1.1
management/editconf.py /etc/postfix/main.cf \
smtpd_tls_security_level=may\
smtpd_tls_auth_only=yes \
@ -132,8 +132,8 @@ management/editconf.py /etc/postfix/main.cf \
smtpd_tls_protocols="!SSLv2,!SSLv3" \
smtpd_tls_ciphers=medium \
tls_medium_cipherlist=ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA256:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA \
smtpd_tls_exclude_ciphers=aNULL,DES,3DES,MD5,DES+MD5,RC4 \
tls_preempt_cipherlist=yes \
smtpd_tls_exclude_ciphers=aNULL,RC4 \
tls_preempt_cipherlist=no \
smtpd_tls_received_header=yes
# For ports 465/587 (via the 'mandatory' settings):
@ -193,17 +193,17 @@ management/editconf.py /etc/postfix/main.cf \
# ### Incoming Mail
# Pass mail to spampd, which acts as the local delivery agent (LDA),
# which then passes the mail over to the Dovecot LMTP server after.
# spampd runs on port 10025 by default.
# Pass any incoming mail over to a local delivery agent. Spamassassin
# will act as the LDA agent at first. It is listening on port 10025
# with LMTP. Spamassassin will pass the mail over to Dovecot after.
#
# In a basic setup we would pass mail directly to Dovecot by setting
# virtual_transport to `lmtp:unix:private/dovecot-lmtp`.
management/editconf.py /etc/postfix/main.cf "virtual_transport=lmtp:[127.0.0.1]:10025"
# Clear the lmtp_destination_recipient_limit setting which in previous
# versions of Mail-in-a-Box was set to 1 because of a spampd bug.
# Because of a spampd bug, limit the number of recipients in each connection.
# See https://github.com/mail-in-a-box/mailinabox/issues/1523.
management/editconf.py /etc/postfix/main.cf -e lmtp_destination_recipient_limit=
management/editconf.py /etc/postfix/main.cf lmtp_destination_recipient_limit=1
# Who can send mail to us? Some basic filters.
#
@ -232,32 +232,11 @@ management/editconf.py /etc/postfix/main.cf \
# As a matter of fact RFC is not strict about retry timer so postfix and
# other MTA have their own intervals. To fix the problem of receiving
# e-mails really latter, delay of greylisting has been set to
# 180 seconds (default is 300 seconds). We will move the postgrey database
# under $STORAGE_ROOT. This prevents a "warming up" that would have occured
# previously with a migrated or reinstalled OS. We will specify this new path
# with the --dbdir=... option. Arguments within POSTGREY_OPTS can not have spaces,
# including dbdir. This is due to the way the init script sources the
# /etc/default/postgrey file. --dbdir=... either needs to be a path without spaces
# (luckily $STORAGE_ROOT does not currently work with spaces), or it needs to be a
# symlink without spaces that can point to a folder with spaces). We'll just assume
# $STORAGE_ROOT won't have spaces to simplify things.
# 180 seconds (default is 300 seconds).
management/editconf.py /etc/default/postgrey \
POSTGREY_OPTS=\""--inet=127.0.0.1:10023 --delay=180 --dbdir=$STORAGE_ROOT/mail/postgrey/db"\"
POSTGREY_OPTS=\"'--inet=127.0.0.1:10023 --delay=180'\"
# If the $STORAGE_ROOT/mail/postgrey is empty, copy the postgrey database over from the old location
if [ ! -d $STORAGE_ROOT/mail/postgrey/db ]; then
# Stop the service
service postgrey stop
# Ensure the new paths for postgrey db exists
mkdir -p $STORAGE_ROOT/mail/postgrey/db
# Move over database files
mv /var/lib/postgrey/* $STORAGE_ROOT/mail/postgrey/db/ || true
fi
# Ensure permissions are set
chown -R postgrey:postgrey $STORAGE_ROOT/mail/postgrey/
chmod 700 $STORAGE_ROOT/mail/postgrey/{,db}
# We are going to setup a newer whitelist for postgrey, the version included in the distribution is old
cat > /etc/cron.daily/mailinabox-postgrey-whitelist << EOF;
#!/bin/bash

View file

@ -25,19 +25,9 @@ if [ ! -f $db_path ]; then
echo "CREATE TABLE noreply (id INTEGER PRIMARY KEY AUTOINCREMENT, email TEXT NOT NULL UNIQUE);" | sqlite3 $db_path
echo "CREATE TABLE mfa (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL, type TEXT NOT NULL, secret TEXT NOT NULL, mru_token TEXT, label TEXT, FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE);" | sqlite3 $db_path;
echo "CREATE TABLE auto_aliases (id INTEGER PRIMARY KEY AUTOINCREMENT, source TEXT NOT NULL UNIQUE, destination TEXT NOT NULL, permitted_senders TEXT);" | sqlite3 $db_path;
else
sql=$(sqlite3 $db_path "SELECT sql FROM sqlite_master WHERE name = 'users'");
if echo $sql | grep --invert-match quota; then
elif sqlite3 $db_path ".schema users" | grep --invert-match quota; then
echo "ALTER TABLE users ADD COLUMN quota TEXT NOT NULL DEFAULT '0';" | sqlite3 $db_path;
fi
fi
# Recover the database if it was hit by the Roundcube password changer "bug" (#85)
# If the journal_mode is set to wal, postfix cannot read it and we wouldn't
# be able to send or receive mail.
#
# This operation is idempotent so it's safe to run even in healthy databases, too.
echo "PRAGMA journal_mode=delete;" | sqlite3 $db_path > /dev/null
# ### User Authentication
@ -168,7 +158,7 @@ EOF
# SQL statement to check if we're sending to a noreply address.
cat > /etc/postfix/noreply-addresses.cf << EOF;
dbpath=$db_path
dbpath=/home/user-data/mail/users.sqlite
query = SELECT 'REJECT This address is not ready to receive email.' FROM noreply WHERE email='%s'
EOF

View file

@ -1,30 +1,35 @@
#!/bin/bash
source setup/functions.sh
source /etc/mailinabox.conf # load global vars
echo "Installing Mail-in-a-Box system management daemon..."
# DEPENDENCIES
# We used to install management daemon-related Python packages
# directly to /usr/local/lib. We moved to a virtualenv because
# these packages might conflict with apt-installed packages.
# We may have a lingering version of acme that conflcits with
# certbot, which we're about to install below, so remove it
# first. Once acme is installed by an apt package, this might
# break the package version and `apt-get install --reinstall python3-acme`
# might be needed in that case.
while [ -d /usr/local/lib/python3.4/dist-packages/acme ]; do
pip3 uninstall -y acme;
done
# duplicity is used to make backups of user data.
#
# virtualenv is used to isolate the Python 3 packages we
# install via pip from the system-installed packages.
#
# certbot installs EFF's certbot which we use to
# provision free TLS certificates.
#
# gcc and build tools are required to install the latest version
# of duplicity
apt_install python3-pip python3-gpg virtualenv certbot rsync librsync2 python3-fasteners python3-future python3-lockfile \
gcc python3-dev librsync-dev gettext
apt_install duplicity python3-pip python3-gpg virtualenv certbot
apt_get_quiet remove --autoremove --purge duplicity || /bin/true
# Duplicity does the actual backups.
# b2sdk is used for backblaze backups.
# boto3 is used for amazon aws backups.
# boto is used for amazon aws backups.
# Both are installed outside the pipenv, so they can be used by duplicity
hide_output pip3 install --upgrade b2sdk boto3 duplicity
hide_output pip3 install --upgrade boto
# Create a virtualenv for the installation of Python 3 packages
# used by the management daemon.
@ -33,15 +38,6 @@ mkdir -p $inst_dir
venv=$inst_dir/env
if [ ! -d $venv ]; then
hide_output virtualenv -ppython3 $venv
elif [ ! -f $venv/.oscode ]; then
echo "Re-creating Python environment..."
rm -rf $venv
hide_output virtualenv -ppython3 $venv
elif [ "$(cat $venv/.oscode)" != $(get_os_code) ]; then
echo "Existing management environment is from an earlier version of the OS you're running."
echo "Re-creating Python environment..."
rm -rf $venv
hide_output virtualenv -ppython3 $venv
fi
# Upgrade pip because the Ubuntu-packaged version is out of date.
@ -52,17 +48,32 @@ hide_output $venv/bin/pip install --upgrade pip
# NOTE: email_validator is repeated in setup/questions.sh, so please keep the versions synced.
hide_output $venv/bin/pip install --upgrade \
rtyaml "email_validator>=1.0.0" "exclusiveprocess" \
flask dnspython python-dateutil expiringdict gunicorn \
flask dnspython python-dateutil expiringdict \
qrcode[pil] pyotp \
"idna>=2.0.0" "cryptography==2.2.2" boto psutil postfix-mta-sts-resolver boto3 b2sdk
"idna>=2.0.0" "cryptography==2.2.2" boto psutil postfix-mta-sts-resolver
# Install backblaze B2 libraries.
# Depending on the OS, Duplicity may require different dependencies.
case $(get_os_code) in
$OS_DEBIAN_10)
apt_install python-pip
hide_output pip2 install --upgrade "b2<2.0.0"
hide_output $venv/bin/pip install --upgrade "b2<2.0.0"
;;
$OS_UBUNTU_2004 | $OS_DEBIAN_11)
hide_output pip3 install --upgrade "b2sdk==1.7.0"
hide_output $venv/bin/pip install --upgrade "b2sdk==1.7.0"
;;
esac
# Make the venv use the packaged gpgme bindings (the ones pip provides are severely out-of-date)
if [ ! -d $venv/lib/python$(python_version)/site-packages/gpg/ ]; then
ln -s /usr/lib/python3/dist-packages/gpg/ $venv/lib/python$(python_version)/site-packages/
fi
echo $(get_os_code) > $venv/.oscode
# CONFIGURATION
# Create a backup directory and a random key for encrypting backups.
@ -80,39 +91,34 @@ rm -rf $assets_dir
mkdir -p $assets_dir
# jQuery CDN URL
jquery_version=3.6.1
jquery_url=https://code.jquery.com # Check this link for new versions
jquery_version=3.6.0
jquery_url=https://code.jquery.com
# Get jQuery
wget_verify $jquery_url/jquery-$jquery_version.min.js ea61688671d0c3044f2c5b2f2c4af0a6620ac6c2 $assets_dir/jquery.min.js
wget_verify $jquery_url/jquery-$jquery_version.min.js b82d238d4e31fdf618bae8ac11a6c812c03dd0d4 $assets_dir/jquery.min.js
# Bootstrap CDN URL
# See https://github.com/twbs/bootstrap/releases to check for new versions
bootstrap_version=5.2.2
bootstrap_version=4.6.0
bootstrap_url=https://github.com/twbs/bootstrap/releases/download/v$bootstrap_version/bootstrap-$bootstrap_version-dist.zip
# Get Bootstrap
wget_verify $bootstrap_url 740b34c22cef5c2f12a34f084b813ea308fedf74 /tmp/bootstrap.zip
wget_verify $bootstrap_url a1d385dc33cb415512d2f38215a554c4380dac2d /tmp/bootstrap.zip
unzip -q /tmp/bootstrap.zip -d $assets_dir
mv $assets_dir/bootstrap-$bootstrap_version-dist $assets_dir/bootstrap
rm -f /tmp/bootstrap.zip
# FontAwesome CDN URL
# See https://github.com/FortAwesome/Font-Awesome/releases to check for new versions
fontawesome_version=6.2.1
fontawesome_version=5.15.3
fontawesome_url=https://github.com/FortAwesome/Font-Awesome/releases/download/$fontawesome_version/fontawesome-free-$fontawesome_version-web.zip
# Get FontAwesome
wget_verify $fontawesome_url cd0f2bcc9653b56e3e2dd82d6598aa6bbca8d796 /tmp/fontawesome.zip
wget_verify $fontawesome_url 914f0b8de446e338779771fcb6364b879f4527ae /tmp/fontawesome.zip
unzip -q /tmp/fontawesome.zip -d $assets_dir
mv $assets_dir/fontawesome-free-$fontawesome_version-web $assets_dir/fontawesome
rm -f /tmp/fontawesome.zip
# Create an init script to start the management daemon and keep it
# running after a reboot.
# Set a long timeout since some commands take a while to run, matching
# the timeout we set for PHP (fastcgi_read_timeout in the nginx confs).
# Note: Authentication currently breaks with more than 1 gunicorn worker.
cat > $inst_dir/start <<EOF;
#!/bin/bash
# Set character encoding flags to ensure that any non-ASCII don't cause problems.
@ -121,13 +127,8 @@ export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
export LC_TYPE=en_US.UTF-8
mkdir -p /var/lib/mailinabox
tr -cd '[:xdigit:]' < /dev/urandom | head -c 32 > /var/lib/mailinabox/api.key
chmod 640 /var/lib/mailinabox/api.key
source $venv/bin/activate
export PYTHONPATH=$(pwd)/management
exec gunicorn -b localhost:10222 -w 1 --timeout 630 wsgi:app
exec python $(pwd)/management/daemon.py
EOF
chmod +x $inst_dir/start
cp --remove-destination conf/mailinabox.service /lib/systemd/system/mailinabox.service # target was previously a symlink so remove it first

View file

@ -9,56 +9,11 @@ source /etc/mailinabox.conf # load global vars
echo "Installing Nextcloud (contacts/calendar)..."
# Nextcloud core and app (plugin) versions to install.
# With each version we store a hash to ensure we install what we expect.
# Nextcloud core
# --------------
# * See https://nextcloud.com/changelog for the latest version.
# * Check https://docs.nextcloud.com/server/latest/admin_manual/installation/system_requirements.html
# for whether it supports the version of PHP available on this machine.
# * Since Nextcloud only supports upgrades from consecutive major versions,
# we automatically install intermediate versions as needed.
# * The hash is the SHA1 hash of the ZIP package, which you can find by just running this script and
# copying it from the error message when it doesn't match what is below.
nextcloud_ver=24.0.7
nextcloud_hash=7fb1afeb3c212bf5530c3d234b23bf314b47655a
# Nextcloud apps
# --------------
# * Find the most recent tag that is compatible with the Nextcloud version above by
# consulting the <dependencies>...<nextcloud> node at:
# https://github.com/nextcloud-releases/contacts/blob/master/appinfo/info.xml
# https://github.com/nextcloud-releases/calendar/blob/master/appinfo/info.xml
# https://github.com/nextcloud-releases/user_external
# * The hash is the SHA1 hash of the ZIP package, which you can find by just running this script and
# copying it from the error message when it doesn't match what is below.
contacts_ver=4.2.2
contacts_hash=cbab9a7acdc11a9e2779c20b850bb21faec1c80f
calendar_ver=3.5.2
calendar_hash=dcf2cba6933dc8805ca4b4d04ed7b993ff4652a1
user_external_ver=3.0.0
user_external_hash=0df781b261f55bbde73d8c92da3f99397000972f
# Clear prior packages and install dependencies from apt.
# Just in case someone tries to cross over from the upstream version.
apt-get purge -qq -y owncloud* 2> /dev/null || /bin/true
apt_install php php-fpm \
php-cli php-sqlite3 php-gd php-imap php-curl php-pear curl \
php-dev php-xml php-mbstring php-zip php-apcu php-json \
php-dev php-gd php-xml php-mbstring php-zip php-apcu php-json \
php-intl php-imagick php-gmp php-bcmath
phpenmod apcu
management/editconf.py /etc/php/$(php_version)/mods-available/apcu.ini -c ';' \
apc.enabled=1 \
apc.enable_cli=1
management/editconf.py /etc/php/$(php_version)/cli/php.ini -c ';' \
apc.enable_cli=1
InstallNextcloud() {
version=$1
@ -89,42 +44,18 @@ InstallNextcloud() {
# their github repositories.
mkdir -p /usr/local/lib/owncloud/apps
IFS='.'
read -a checkVer <<< "$version_contacts"
unset IFS
if [ "${checkVer[0]}" -gt 4 ] || [ "${checkVer[0]}" -eq 4 -a "${checkVer[1]}" -gt 0 ] || [ "${checkVer[0]}" -eq 4 -a "${checkVer[2]}" -gt 0 ]; then
# Contacts 4.0.1 and later are downloaded from here
wget_verify https://github.com/nextcloud-releases/contacts/releases/download/v$version_contacts/contacts-v$version_contacts.tar.gz $hash_contacts /tmp/contacts.tgz
else
# 4.0.0 and earlier are downloaded from here
wget_verify https://github.com/Nextcloud/contacts/releases/download/v$version_contacts/contacts.tar.gz $hash_contacts /tmp/contacts.tgz
fi
wget_verify https://github.com/nextcloud-releases/contacts/releases/download/v$version_contacts/contacts.tar.gz $hash_contacts /tmp/contacts.tgz
tar xf /tmp/contacts.tgz -C /usr/local/lib/owncloud/apps/
rm /tmp/contacts.tgz
IFS='.'
read -a checkVer <<< "$version_calendar"
unset IFS
if [ "${checkVer[0]}" -eq 2 -a "${checkVer[1]}" -gt 2 ] || [ "${checkVer[0]}" -gt 2 ]; then
# Calendar 2.3.0 and later are downloaded from here
wget_verify https://github.com/nextcloud-releases/calendar/releases/download/v$version_calendar/calendar-v$version_calendar.tar.gz $hash_calendar /tmp/calendar.tgz
else
wget_verify https://github.com/nextcloud/calendar/releases/download/v$version_calendar/calendar.tar.gz $hash_calendar /tmp/calendar.tgz
fi
wget_verify https://github.com/nextcloud-releases/calendar/releases/download/v$version_calendar/calendar.tar.gz $hash_calendar /tmp/calendar.tgz
tar xf /tmp/calendar.tgz -C /usr/local/lib/owncloud/apps/
rm /tmp/calendar.tgz
# Starting with Nextcloud 15, the app user_external is no longer included in Nextcloud core,
# we will install from their github repository.
if [ -n "$version_user_external" ]; then
IFS='.'
read -a checkVer <<< "$version_user_external"
unset IFS
if [ "${checkVer[0]}" -gt 2 ]; then
wget_verify https://github.com/nextcloud-releases/user_external/releases/download/v$version_user_external/user_external-v$version_user_external.tar.gz $hash_user_external /tmp/user_external.tgz
else
wget_verify https://github.com/nextcloud/user_external/releases/download/v$version_user_external/user_external-$version_user_external.tar.gz $hash_user_external /tmp/user_external.tgz
fi
tar -xf /tmp/user_external.tgz -C /usr/local/lib/owncloud/apps/
rm /tmp/user_external.tgz
fi
@ -163,33 +94,25 @@ InstallNextcloud() {
fi
}
# Nextcloud Version to install. Checks are done down below to step through intermediate versions.
nextcloud_ver=20.0.13
nextcloud_hash=a1fe460e3e65753552fb4beb1a47ab09ff277d95
contacts_ver=4.0.3
contacts_hash=5ddd629e72fdb80c5ff80186954f32a464b9dcd1
calendar_ver=2.3.4
calendar_hash=bf4a8e5d40731013a6f971eea3149e852e9fb47c
user_external_ver=1.0.0
user_external_hash=3bf2609061d7214e7f0f69dd8883e55c4ec8f50a
# Current Nextcloud Version, #1623
# Checking /usr/local/lib/owncloud/version.php shows version of the Nextcloud application, not the DB
# $STORAGE_ROOT/owncloud is kept together even during a backup. It is better to rely on config.php than
# version.php since the restore procedure can leave the system in a state where you have a newer Nextcloud
# application version than the database.
# If config.php exists, get version number, otherwise CURRENT_NEXTCLOUD_VER is empty.
#
# Config unlocking, power-mailinabox#86
# If a configuration file already exists, remove the "readonly" tag before starting the upgrade. This is
# necessary (otherwise upgrades will fail).
#
# The lock will be re-applied further down the line when it's safe to do so.
CONFIG_TEMP=$(/bin/mktemp)
if [ -f "$STORAGE_ROOT/owncloud/config.php" ]; then
CURRENT_NEXTCLOUD_VER=$(php -r "include(\"$STORAGE_ROOT/owncloud/config.php\"); echo(\$CONFIG['version']);")
# Unlock configuration directory for upgrades
php <<EOF > $CONFIG_TEMP && mv $CONFIG_TEMP $STORAGE_ROOT/owncloud/config.php;
<?php
include("$STORAGE_ROOT/owncloud/config.php");
\$CONFIG['config_is_read_only'] = false;
echo "<?php\n\\\$CONFIG = ";
var_export(\$CONFIG);
echo ";";
?>
EOF
else
CURRENT_NEXTCLOUD_VER=""
fi
@ -247,8 +170,7 @@ if [ ! -d /usr/local/lib/owncloud/ ] || [[ ! ${CURRENT_NEXTCLOUD_VER} =~ ^$nextc
CURRENT_NEXTCLOUD_VER="17.0.6"
fi
if [[ ${CURRENT_NEXTCLOUD_VER} =~ ^17 ]]; then
# Don't exit the install if this column already exists (see #2076)
(echo "ALTER TABLE oc_flow_operations ADD COLUMN entity VARCHAR;" | sqlite3 $STORAGE_ROOT/owncloud/owncloud.db 2>/dev/null) || true
echo "ALTER TABLE oc_flow_operations ADD COLUMN entity VARCHAR;" | sqlite3 $STORAGE_ROOT/owncloud/owncloud.db
InstallNextcloud 18.0.10 39c0021a8b8477c3f1733fddefacfa5ebf921c68 3.4.1 aee680a75e95f26d9285efd3c1e25cf7f3bfd27e 2.0.3 9d9717b29337613b72c74e9914c69b74b346c466 1.0.0 3bf2609061d7214e7f0f69dd8883e55c4ec8f50a
CURRENT_NEXTCLOUD_VER="18.0.10"
fi
@ -256,28 +178,12 @@ if [ ! -d /usr/local/lib/owncloud/ ] || [[ ! ${CURRENT_NEXTCLOUD_VER} =~ ^$nextc
InstallNextcloud 19.0.4 01e98791ba12f4860d3d4047b9803f97a1b55c60 3.4.1 aee680a75e95f26d9285efd3c1e25cf7f3bfd27e 2.0.3 9d9717b29337613b72c74e9914c69b74b346c466 1.0.0 3bf2609061d7214e7f0f69dd8883e55c4ec8f50a
CURRENT_NEXTCLOUD_VER="19.0.4"
fi
if [[ ${CURRENT_NEXTCLOUD_VER} =~ ^19 ]]; then
InstallNextcloud 20.0.14 92cac708915f51ee2afc1787fd845476fd090c81 4.0.8 9f368bb2be98c5555b7118648f4cc9fa51e8cb30 3.0.6 ca49bb1ce23f20e10911e39055fd59d7f7a84c30 1.0.0 3bf2609061d7214e7f0f69dd8883e55c4ec8f50a
# Nextcloud 20 needs to have some optional columns added
sudo -u www-data php /usr/local/lib/owncloud/occ db:add-missing-columns
CURRENT_NEXTCLOUD_VER="20.0.14"
fi
if [[ ${CURRENT_NEXTCLOUD_VER} =~ ^20 ]]; then
InstallNextcloud 21.0.9 cf8785107c3c079a1f450743558f4f13c85f37a8 4.1.0 38653b507bd7d953816bbc5e8bea7855867eb1cd 3.2.2 54e9a836adc739be4a2a9301b8d6d2e9d88e02f4 2.1.0 6e5afe7f36f398f864bfdce9cad72200e70322aa
CURRENT_NEXTCLOUD_VER="21.0.9"
fi
if [[ ${CURRENT_NEXTCLOUD_VER} =~ ^21 ]]; then
InstallNextcloud 22.2.6 9d39741f051a8da42ff7df46ceef2653a1dc70d9 4.1.0 38653b507bd7d953816bbc5e8bea7855867eb1cd 3.2.2 54e9a836adc739be4a2a9301b8d6d2e9d88e02f4 3.0.0 0df781b261f55bbde73d8c92da3f99397000972f
CURRENT_NEXTCLOUD_VER="22.2.6"
fi
if [[ ${CURRENT_NEXTCLOUD_VER} =~ ^22 ]]; then
InstallNextcloud 23.0.4 87afec0bf90b3c66289e6fedd851867bc5a58f01 4.1.0 38653b507bd7d953816bbc5e8bea7855867eb1cd 3.2.2 54e9a836adc739be4a2a9301b8d6d2e9d88e02f4 3.0.0 0df781b261f55bbde73d8c92da3f99397000972f
CURRENT_NEXTCLOUD_VER="23.0.4"
fi
fi
InstallNextcloud $nextcloud_ver $nextcloud_hash $contacts_ver $contacts_hash $calendar_ver $calendar_hash $user_external_ver $user_external_hash
# Nextcloud 20 needs to have some optional columns added
sudo -u www-data php /usr/local/lib/owncloud/occ db:add-missing-columns
fi
# ### Configuring Nextcloud
@ -303,9 +209,9 @@ if [ ! -f $STORAGE_ROOT/owncloud/owncloud.db ]; then
'overwrite.cli.url' => '/cloud',
'user_backends' => array(
array(
'class' => '\OCA\UserExternal\IMAP',
'class' => 'OC_User_IMAP',
'arguments' => array(
'127.0.0.1', 143, null, null, false, false
'127.0.0.1', 143, null
),
),
),
@ -333,7 +239,6 @@ EOF
# storage/database
'directory' => '$STORAGE_ROOT/owncloud',
'dbtype' => 'sqlite3',
'dbname' => 'owncloud',
# create an administrator account with a random password so that
# the user does not have to enter anything on first load of Nextcloud
@ -364,12 +269,11 @@ fi
# the correct domain name if the domain is being change from the previous setup.
# Use PHP to read the settings file, modify it, and write out the new settings array.
TIMEZONE=$(cat /etc/timezone)
CONFIG_TEMP=$(/bin/mktemp)
php <<EOF > $CONFIG_TEMP && mv $CONFIG_TEMP $STORAGE_ROOT/owncloud/config.php;
<?php
include("$STORAGE_ROOT/owncloud/config.php");
\$CONFIG['config_is_read_only'] = true;
\$CONFIG['trusted_domains'] = array('$PRIMARY_HOSTNAME');
\$CONFIG['memcache.local'] = '\OC\Memcache\APCu';
@ -381,14 +285,7 @@ include("$STORAGE_ROOT/owncloud/config.php");
\$CONFIG['mail_domain'] = '$PRIMARY_HOSTNAME';
\$CONFIG['user_backends'] = array(
array(
'class' => '\OCA\UserExternal\IMAP',
'arguments' => array(
'127.0.0.1', 143, null, null, false, false
),
),
);
\$CONFIG['user_backends'] = array(array('class' => 'OC_User_IMAP','arguments' => array('127.0.0.1', 143, null),),);
echo "<?php\n\\\$CONFIG = ";
var_export(\$CONFIG);
@ -437,11 +334,11 @@ management/editconf.py /etc/php/$(php_version)/cli/conf.d/10-opcache.ini -c ';'
opcache.save_comments=1 \
opcache.revalidate_freq=1
# Migrate users_external data from <0.6.0 to version 3.0.0 (see https://github.com/nextcloud/user_external).
# This version was probably in use in Mail-in-a-Box v0.41 (February 26, 2019) and earlier.
# We moved to v0.6.3 in 193763f8. Ignore errors - maybe there are duplicated users with the
# correct backend already.
sqlite3 $STORAGE_ROOT/owncloud/owncloud.db "UPDATE oc_users_external SET backend='127.0.0.1';" || /bin/true
# If apc is explicitly disabled we need to enable it
if grep -q apc.enabled=0 /etc/php/$(php_version)/mods-available/apcu.ini; then
management/editconf.py /etc/php/$(php_version)/mods-available/apcu.ini -c ';' \
apc.enabled=1
fi
# Set up a cron job for Nextcloud.
cat > /etc/cron.d/mailinabox-nextcloud << EOF;
@ -451,6 +348,9 @@ cat > /etc/cron.d/mailinabox-nextcloud << EOF;
EOF
chmod +x /etc/cron.d/mailinabox-nextcloud
# Remove previous hourly cronjob
rm -f /etc/cron.hourly/mailinabox-owncloud
# There's nothing much of interest that a user could do as an admin for Nextcloud,
# and there's a lot they could mess up, so we don't make any users admins of Nextcloud.
# But if we wanted to, we would do this:

View file

@ -9,33 +9,19 @@ if [[ $EUID -ne 0 ]]; then
exit 1
fi
# Check that we are running on Debian GNU/Linux, or Ubuntu 20.04/22.04
case $(get_os_code) in
$OS_UNSUPPORTED)
echo "This version of Power Mail-in-a-Box only supports being installed on one of these operating systems:"
# echo "* Debian 10 (buster)"
# Check that we are running on Debian GNU/Linux, or Ubuntu 20.04
if [ $(get_os_code) = $OS_UNSUPPORTED ]; then
echo "Mail-in-a-Box only supports being installed on one of these operating systems:"
echo "* Debian 10 (buster)"
echo "* Debian 11 (bullseye)"
echo "* Ubuntu 20.04 LTS (Focal Fossa)"
echo "* Ubuntu 22.04 LTS (Jammy Jellyfish)"
echo
echo "You're running:"
lsb_release -ds
echo
echo "We can't write scripts that run on every possible setup, sorry."
exit 1
;;
$OS_DEBIAN_10)
echo "You're trying to install Power Mail-in-a-Box on Debian 10 (buster), which is no longer supported."
echo "You can install the latest version of Power Mail-in-a-Box supporting Debian 10 by running the following command:"
echo
echo "curl -L https://power-mailinabox.net/setup.sh | sudo bash"
echo
echo "Then upgrade to Debian 11 (bullseye). A short guide on how to do so is available here:"
echo "https://power-mailinabox.net/buster-eol"
exit 1
;;
esac
fi
# Check that we have enough memory.
#

View file

@ -49,12 +49,12 @@ fi
# Put a start script in a global location. We tell the user to run 'mailinabox'
# in the first dialog prompt, so we should do this before that starts.
cat > /usr/local/sbin/mailinabox << EOF;
cat > /usr/local/bin/mailinabox << EOF;
#!/bin/bash
cd $(pwd)
source setup/start.sh
EOF
chmod 744 /usr/local/sbin/mailinabox
chmod +x /usr/local/bin/mailinabox
# Ask the user for the PRIMARY_HOSTNAME, PUBLIC_IP, and PUBLIC_IPV6,
# if values have not already been set in environment variables. When running
@ -72,10 +72,6 @@ fi
fi
# Create the STORAGE_USER and STORAGE_ROOT directory if they don't already exist.
#
# Set the directory and all of its parent directories' permissions to world
# readable since it holds files owned by different processes.
#
# If the STORAGE_ROOT is missing the mailinabox.version file that lists a
# migration (schema) number for the files stored there, assume this is a fresh
# installation to that directory and write the file to contain the current
@ -86,15 +82,11 @@ fi
if [ ! -d $STORAGE_ROOT ]; then
mkdir -p $STORAGE_ROOT
fi
f=$STORAGE_ROOT
while [[ $f != / ]]; do chmod a+rx "$f"; f=$(dirname "$f"); done;
if [ ! -f $STORAGE_ROOT/mailinabox.version ]; then
setup/migrate.py --current > $STORAGE_ROOT/mailinabox.version
chown $STORAGE_USER.$STORAGE_USER $STORAGE_ROOT/mailinabox.version
fi
chmod 751 $STORAGE_ROOT
# Save the global options in /etc/mailinabox.conf so that standalone
# tools know where to look for data. The default MTA_STS_MODE setting
# is blank unless set by an environment variable, but see web.sh for
@ -129,14 +121,6 @@ source setup/zpush.sh
source setup/management.sh
source setup/munin.sh
# Create a shorthand alias for the cli interface
cat > /usr/local/sbin/miabadm << EOF;
#!/bin/bash
cd $(pwd)
/usr/bin/env python3 management/cli.py \$@
EOF
chmod 744 /usr/local/sbin/miabadm
# Wait for the management daemon to start...
until nc -z -w 4 127.0.0.1 10222
do

View file

@ -14,15 +14,6 @@ source setup/functions.sh # load our functions
echo $PRIMARY_HOSTNAME > /etc/hostname
hostname $PRIMARY_HOSTNAME
# ### Enable IPv6 at Kernel Level
# This doesn't mean that the cloud provider must provide IPv6 connectivity. We just want
# the loopback interface to also work on IPv6 (that is, we want :: to be available). This
# is required because apparently nsd expects this to exist.
management/editconf.py /etc/sysctl.conf "net.ipv6.conf.lo.disable_ipv6 = 0"
hide_output sysctl --system
# ### Fix permissions
# The default Ubuntu Bionic image on Scaleway throws warnings during setup about incorrect
@ -84,12 +75,7 @@ then
fi
fi
# ### Set log retention policy.
# Set the systemd journal log retention from infinite to 10 days,
# since over time the logs take up a large amount of space.
# (See https://discourse.mailinabox.email/t/journalctl-reclaim-space-on-small-mailinabox/6728/11.)
management/editconf.py /etc/systemd/journald.conf MaxRetentionSec=10day
# Certbot doesn't require a PPA in Debian
# ### Update Packages
@ -111,6 +97,9 @@ apt_get_quiet autoremove
# Install basic utilities.
#
# * haveged: Provides extra entropy to /dev/random so it doesn't stall
# when generating random numbers for private keys (e.g. during
# ldns-keygen).
# * unattended-upgrades: Apt tool to install security updates automatically.
# * cron: Runs background processes periodically.
# * ntp: keeps the system time correct
@ -124,8 +113,8 @@ apt_get_quiet autoremove
echo Installing system packages...
apt_install python3 python3-dev python3-pip python3-setuptools \
netcat-openbsd wget curl git sudo coreutils bc file \
pollinate openssh-client unzip \
netcat-openbsd wget curl git sudo coreutils bc \
haveged pollinate openssh-client unzip \
unattended-upgrades cron ntp fail2ban rsyslog
# ### Suppress Upgrade Prompts
@ -220,11 +209,7 @@ dd if=/dev/random of=/dev/urandom bs=1 count=32 2> /dev/null
# is really any good on virtualized systems, we'll also seed from Ubuntu's
# pollinate servers:
if ! pollinate -q -r --strict 2> /dev/null; then
# In the case pollinate is ill-configured (e.g. server is example.com), try using a server we know that works
# Even if this fails - don't bail and carry on.
pollinate -q -r -s entropy.ubuntu.com 2> /dev/null
fi
pollinate -q -r
# Between these two, we really ought to be all set.
@ -254,10 +239,6 @@ if [ -z "${DISABLE_FIREWALL:-}" ]; then
# Install `ufw` which provides a simple firewall configuration.
apt_install ufw
# Check if we have got an SSH server installed.
# It's not critical for us to have one, so if it isn't installed,
# no need to open the port
if [ -x "$(command -v sshd)" ]; then
# Allow incoming connections to SSH.
ufw_limit ssh;
@ -267,9 +248,10 @@ if [ -z "${DISABLE_FIREWALL:-}" ]; then
SSH_PORT=$(sshd -T 2>/dev/null | grep "^port " | sed "s/port //") #NODOC
if [ ! -z "$SSH_PORT" ]; then
if [ "$SSH_PORT" != "22" ]; then
echo Opening alternate SSH port $SSH_PORT. #NODOC
ufw_limit $SSH_PORT #NODOC
fi
fi
fi
@ -360,7 +342,6 @@ systemctl restart systemd-resolved
rm -f /etc/fail2ban/jail.local # we used to use this file but don't anymore
rm -f /etc/fail2ban/jail.d/defaults-debian.conf # removes default config so we can manage all of fail2ban rules in one config
cat conf/fail2ban/jails.conf \
| sed "s/PUBLIC_IPV6/$PUBLIC_IPV6/g" \
| sed "s/PUBLIC_IP/$PUBLIC_IP/g" \
| sed "s#STORAGE_ROOT#$STORAGE_ROOT#" \
> /etc/fail2ban/jail.d/mailinabox.conf

View file

@ -160,6 +160,3 @@ restart_service php$(php_version)-fpm
# Open ports.
ufw_allow http
ufw_allow https
# Allow the webserver to access directories group-owned by user-data
usermod -a -G user-data www-data

View file

@ -28,19 +28,13 @@ apt_install \
# Install Roundcube from source if it is not already present or if it is out of date.
# Combine the Roundcube version number with the commit hash of plugins to track
# whether we have the latest version of everything.
# For the latest versions, see:
# https://github.com/roundcube/roundcubemail/releases
# https://github.com/mfreiholz/persistent_login/
# https://github.com/stremlau/html5_notifier/
# https://github.com/mstilkerich/rcmcarddav/releases
# The easiest way to get the package hashes is to run this script and get the hash from
# the error message.
VERSION=1.6.0
HASH=fd84b4fac74419bb73e7a3bcae1978d5589c52de
PERSISTENT_LOGIN_VERSION=version-5.3.0
VERSION=1.5.0
HASH=2a9d11d9c10c8e8756120606c47eef702f00fe6d
PERSISTENT_LOGIN_VERSION=327362e7615e9192ea7a8871e5a0230b8ea6930a # version 5.2.0 + chinese localization
HTML5_NOTIFIER_VERSION=68d9ca194212e15b3c7225eb6085dbcf02fd13d7 # version 0.6.4+
CARDDAV_VERSION=4.4.4
CARDDAV_HASH=743fd6925b775f821aa8860982d2bdeec05f5d7b
CARDDAV_VERSION=4.2.0
CARDDAV_HASH=d412a038bb698eeee631ec20e8b1118baeb2e554
UPDATE_KEY=$VERSION:$PERSISTENT_LOGIN_VERSION:$HTML5_NOTIFIER_VERSION:$CARDDAV_VERSION
@ -83,13 +77,13 @@ if [ $needs_update == 1 ]; then
# download and verify the full release of the carddav plugin
wget_verify \
https://github.com/mstilkerich/rcmcarddav/releases/download/v${CARDDAV_VERSION}/carddav-v${CARDDAV_VERSION}.tar.gz \
https://github.com/blind-coder/rcmcarddav/releases/download/v${CARDDAV_VERSION}/carddav-v${CARDDAV_VERSION}.tar.gz \
$CARDDAV_HASH \
/tmp/carddav.tar.gz
/tmp/carddav.tgz
# unzip and cleanup
tar -C ${RCM_PLUGIN_DIR} -zxf /tmp/carddav.tar.gz
rm -f /tmp/carddav.tar.gz
tar xf /tmp/carddav.tgz -C ${RCM_PLUGIN_DIR}
rm -f /tmp/carddav.tgz
# record the version we've installed
echo $UPDATE_KEY > ${RCM_DIR}/version
@ -115,7 +109,8 @@ cat > $RCM_CONFIG <<EOF;
\$config['log_dir'] = '/var/log/roundcubemail/';
\$config['temp_dir'] = '/var/tmp/roundcubemail/';
\$config['db_dsnw'] = 'sqlite:///$STORAGE_ROOT/mail/roundcube/roundcube.sqlite?mode=0640';
\$config['imap_host'] = 'ssl://localhost:993';
\$config['default_host'] = 'ssl://localhost';
\$config['default_port'] = 993;
\$config['imap_conn_options'] = array(
'ssl' => array(
'verify_peer' => false,
@ -123,14 +118,14 @@ cat > $RCM_CONFIG <<EOF;
),
);
\$config['imap_timeout'] = 15;
\$config['smtp_host'] = 'tls://127.0.0.1:587';
\$config['smtp_server'] = 'tls://127.0.0.1';
\$config['smtp_conn_options'] = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
),
);
\$config['support_url'] = 'https://power-mailinabox.net/';
\$config['support_url'] = 'https://mailinabox.email/';
\$config['product_name'] = '$PRIMARY_HOSTNAME Webmail';
\$config['plugins'] = array('html5_notifier', 'archive', 'zipdownload', 'password', 'managesieve', 'jqueryui', 'persistent_login', 'carddav', 'enigma');
\$config['cipher_method'] = 'AES-256-CBC'; # persistent login cookie and potentially other things
@ -140,11 +135,6 @@ cat > $RCM_CONFIG <<EOF;
\$config['login_username_filter'] = 'email';
\$config['password_charset'] = 'UTF-8';
\$config['junk_mbox'] = 'Spam';
/* ensure roudcube session id's aren't leaked to other parts of the server */
\$config['session_path'] = '/mail/';
/* prevent CSRF, requires php 7.3+ */
\$config['session_samesite'] = 'Strict';
\$config['quota_zero_as_unlimited'] = true;
EOF
@ -187,7 +177,7 @@ cat > ${RCM_PLUGIN_DIR}/carddav/config.inc.php <<EOF;
'name' => 'ownCloud',
'username' => '%u', // login username
'password' => '%p', // login password
'url' => 'https://${PRIMARY_HOSTNAME}/cloud/remote.php/dav/addressbooks/users/%u/contacts/',
'url' => 'https://${PRIMARY_HOSTNAME}/cloud/remote.php/carddav/addressbooks/%u/contacts',
'active' => true,
'readonly' => false,
'refresh_time' => '02:00:00',
@ -211,12 +201,13 @@ sudo -u www-data touch /var/log/roundcubemail/errors.log
cp ${RCM_PLUGIN_DIR}/password/config.inc.php.dist \
${RCM_PLUGIN_DIR}/password/config.inc.php
management/editconf.py ${RCM_PLUGIN_DIR}/password/config.inc.php -c "//" \
"\$config['password_driver'] = 'miab';" \
management/editconf.py ${RCM_PLUGIN_DIR}/password/config.inc.php \
"\$config['password_minimum_length']=8;" \
"\$config['password_miab_url'] = 'http://127.0.0.1:10222/';" \
"\$config['password_miab_user'] = '';" \
"\$config['password_miab_pass'] = '';"
"\$config['password_db_dsn']='sqlite:///$STORAGE_ROOT/mail/users.sqlite';" \
"\$config['password_query']='UPDATE users SET password=%D WHERE email=%u';" \
"\$config['password_dovecotpw']='/usr/bin/doveadm pw';" \
"\$config['password_dovecotpw_method']='SHA512-CRYPT';" \
"\$config['password_dovecotpw_with_method']=true;"
# so PHP can use doveadm, for the password changing plugin
usermod -a -G dovecot www-data
@ -234,7 +225,7 @@ chown -f -R root.www-data ${RCM_PLUGIN_DIR}/carddav
chmod -R 774 ${RCM_PLUGIN_DIR}/carddav
# Run Roundcube database migration script (database is created if it does not exist)
php ${RCM_DIR}/bin/updatedb.sh --dir ${RCM_DIR}/SQL --package roundcube
${RCM_DIR}/bin/updatedb.sh --dir ${RCM_DIR}/SQL --package roundcube
chown www-data:www-data $STORAGE_ROOT/mail/roundcube/roundcube.sqlite
chmod 664 $STORAGE_ROOT/mail/roundcube/roundcube.sqlite

View file

@ -17,7 +17,7 @@ source /etc/mailinabox.conf # load global vars
echo "Installing Z-Push (Exchange/ActiveSync server)..."
apt_install \
php-soap php-imap libawl-php php-xml
php-soap php-imap libawl-php php-xsl
phpenmod -v php imap
@ -42,6 +42,8 @@ if [ $needs_update == 1 ]; then
rm -rf /tmp/z-push.zip /tmp/z-push
rm -f /usr/sbin/z-push-{admin,top}
ln -s /usr/local/lib/z-push/z-push-admin.php /usr/sbin/z-push-admin
ln -s /usr/local/lib/z-push/z-push-top.php /usr/sbin/z-push-top
echo $VERSION > /usr/local/lib/z-push/version
fi
@ -104,4 +106,4 @@ restart_service php$(php_version)-fpm
# Fix states after upgrade
hide_output php /usr/local/lib/z-push/z-push-admin.php -a fixstates
hide_output z-push-admin -a fixstates

View file

@ -30,7 +30,7 @@ def test(server, description):
(hostname, "TXT", "\"v=spf1 mx -all\""),
("mail._domainkey." + hostname, "TXT", "\"v=DKIM1; k=rsa; s=email; \" \"p=__KEY__\""),
#("_adsp._domainkey." + hostname, "TXT", "\"dkim=all\""),
("_dmarc." + hostname, "TXT", "\"v=DMARC1; p=quarantine;\""),
("_dmarc." + hostname, "TXT", "\"v=DMARC1; p=quarantine\""),
]
return test2(tests, server, description)
@ -48,7 +48,7 @@ def test2(tests, server, description):
for qname, rtype, expected_answer in tests:
# do the query and format the result as a string
try:
response = dns.resolver.resolve(qname, rtype)
response = dns.resolver.query(qname, rtype)
except dns.resolver.NoNameservers:
# host did not have an answer for this query
print("Could not connect to %s for DNS query." % server)

View file

@ -48,7 +48,7 @@ server = smtplib.SMTP_SSL(host)
ipaddr = socket.gethostbyname(host) # IPv4 only!
reverse_ip = dns.reversename.from_address(ipaddr) # e.g. "1.0.0.127.in-addr.arpa."
try:
reverse_dns = dns.resolver.resolve(reverse_ip, 'PTR')[0].target.to_text(omit_final_dot=True) # => hostname
reverse_dns = dns.resolver.query(reverse_ip, 'PTR')[0].target.to_text(omit_final_dot=True) # => hostname
except dns.resolver.NXDOMAIN:
print("Reverse DNS lookup failed for %s. SMTP EHLO name check skipped." % ipaddr)
reverse_dns = None

3
tools/mail.py Executable file
View file

@ -0,0 +1,3 @@
#!/bin/bash
# This script has moved.
management/cli.py "$@"

View file

@ -8,7 +8,7 @@
source /etc/mailinabox.conf # load global vars
ADMIN=$(management/cli.py user admins | head -n 1)
ADMIN=$(./mail.py user admins | head -n 1)
test -z "$1" || ADMIN=$1
echo I am going to unlock admin features for $ADMIN.
@ -20,4 +20,4 @@ echo
echo Press enter to continue.
read
sudo -u www-data php /usr/local/lib/owncloud/occ group:adduser admin "$ADMIN" && echo Done.
sudo -u www-data php /usr/local/lib/owncloud/occ group:adduser admin $ADMIN && echo Done.

View file

@ -413,7 +413,7 @@ class BashScript(Grammar):
result = parser.parse_string(string)
v = "<div class='row'><div class='col-xs-12 sourcefile'>view the bash source for the following section at <a href=\"%s\">%s</a></div></div>\n" \
% ("https://github.com/ddavness/power-mailinabox/tree/main/" + fn, fn)
% ("https://github.com/mail-in-a-box/mailinabox/tree/master/" + fn, fn)
mode = 0
for item in result.value():