Add some level of style guidance, reformat files
This commit is contained in:
parent
14534fd0cb
commit
a8f5a78518
35 changed files with 6396 additions and 4609 deletions
|
@ -4,30 +4,23 @@
|
|||
|
||||
root = true
|
||||
|
||||
[*]
|
||||
[Vagrantfile]
|
||||
indent_style = space
|
||||
indent_size = 4
|
||||
indent_size = 2
|
||||
|
||||
[*.rb]
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
|
||||
[**.html]
|
||||
indent_style = tab
|
||||
|
||||
[**.py]
|
||||
indent_style = tab
|
||||
|
||||
[**]
|
||||
indent_style = tab
|
||||
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
|
||||
|
||||
|
|
3
.style.yapf
Normal file
3
.style.yapf
Normal file
|
@ -0,0 +1,3 @@
|
|||
[style]
|
||||
based_on_style = pep8
|
||||
use_tabs = True
|
|
@ -1,4 +1,9 @@
|
|||
import base64, os, os.path, hmac, json, secrets
|
||||
import base64
|
||||
import os
|
||||
import os.path
|
||||
import hmac
|
||||
import json
|
||||
import secrets
|
||||
from datetime import timedelta
|
||||
|
||||
from expiringdict import ExpiringDict
|
||||
|
@ -7,17 +12,21 @@ import utils
|
|||
from mailconfig import get_mail_password, get_mail_user_privileges
|
||||
from mfa import get_hash_mfa_state, validate_auth_mfa
|
||||
|
||||
DEFAULT_KEY_PATH = '/var/lib/mailinabox/api.key'
|
||||
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"""
|
||||
|
@ -26,7 +35,8 @@ class AuthService:
|
|||
# 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')
|
||||
return os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT, mode),
|
||||
'w')
|
||||
finally:
|
||||
os.umask(old_umask)
|
||||
|
||||
|
@ -46,8 +56,10 @@ 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)
|
||||
|
@ -59,12 +71,15 @@ 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.
|
||||
|
@ -72,7 +87,8 @@ 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:
|
||||
|
@ -96,7 +112,8 @@ 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)
|
||||
|
@ -120,10 +137,13 @@ 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.
|
||||
raise ValueError("Incorrect email address or password.")
|
||||
|
@ -141,7 +161,8 @@ 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')
|
||||
|
@ -152,15 +173,21 @@ 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
|
||||
|
|
|
@ -7,14 +7,23 @@
|
|||
# 4) The stopped services are restarted.
|
||||
# 5) STORAGE_ROOT/backup/after-backup is executed if it exists.
|
||||
|
||||
import os, os.path, shutil, glob, re, datetime, sys
|
||||
import dateutil.parser, dateutil.relativedelta, dateutil.tz
|
||||
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 rtyaml
|
||||
from exclusiveprocess import Lock, CannotAcquireLock
|
||||
|
||||
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):
|
||||
|
||||
def rsync_ssh_options(port=22, direct=False):
|
||||
# Just in case we pass a string
|
||||
try:
|
||||
port = int(port)
|
||||
|
@ -29,30 +38,39 @@ def rsync_ssh_options(port = 22, direct = False):
|
|||
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.
|
||||
config = get_backup_config(env)
|
||||
if config["target"] == "off":
|
||||
return { }
|
||||
return {}
|
||||
|
||||
# Query duplicity to get a list of all full and incremental
|
||||
# backups available.
|
||||
|
||||
backups = { }
|
||||
backups = {}
|
||||
now = datetime.datetime.now(dateutil.tz.tzlocal())
|
||||
backup_root = os.path.join(env["STORAGE_ROOT"], 'backup')
|
||||
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.
|
||||
|
@ -64,24 +82,31 @@ def backup_status(env):
|
|||
"date_str": date.strftime("%Y-%m-%d %X") + " " + now.tzname(),
|
||||
"date_delta": reldate(date, now, "the future?"),
|
||||
"full": keys[0] == "full",
|
||||
"size": 0, # collection-status doesn't give us the size
|
||||
"volumes": int(keys[2]), # number of archive volumes for this backup (not really helpful)
|
||||
"size": 0, # collection-status doesn't give us the size
|
||||
# number of archive volumes for this backup (not really helpful)
|
||||
"volumes": int(keys[2]),
|
||||
}
|
||||
|
||||
code, collection_status = shell('check_output', [
|
||||
"/usr/bin/duplicity",
|
||||
"collection-status",
|
||||
"--archive-dir", backup_cache_dir,
|
||||
"--gpg-options", "--cipher-algo=AES256",
|
||||
"--log-fd", "1",
|
||||
config["target"],
|
||||
] + rsync_ssh_options(port = config["target_rsync_port"]),
|
||||
code, collection_status = shell(
|
||||
'check_output',
|
||||
[
|
||||
"/usr/bin/duplicity",
|
||||
"collection-status",
|
||||
"--archive-dir",
|
||||
backup_cache_dir,
|
||||
"--gpg-options",
|
||||
"--cipher-algo=AES256",
|
||||
"--log-fd",
|
||||
"1",
|
||||
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)
|
||||
|
@ -94,8 +119,11 @@ 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
|
||||
|
@ -104,7 +132,7 @@ def backup_status(env):
|
|||
|
||||
# Ensure the rows are sorted reverse chronologically.
|
||||
# This is relied on by should_force_full() and the next step.
|
||||
backups = sorted(backups.values(), key = lambda b : b["date"], reverse=True)
|
||||
backups = sorted(backups.values(), key=lambda b: b["date"], reverse=True)
|
||||
|
||||
# Get the average size of incremental backups, the size of the
|
||||
# most recent full backup, and the date of the most recent
|
||||
|
@ -133,16 +161,23 @@ 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
|
||||
|
@ -158,7 +193,11 @@ 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 {
|
||||
|
@ -166,6 +205,7 @@ 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
|
||||
|
@ -181,9 +221,11 @@ def should_force_full(config, env):
|
|||
# Return if we should to a full backup, which is based
|
||||
# on the size of the increments relative to the full
|
||||
# backup, as well as the age of the full backup.
|
||||
if inc_size > .5*bak["size"]:
|
||||
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:
|
||||
|
@ -191,6 +233,7 @@ 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.
|
||||
|
@ -201,14 +244,16 @@ 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_env(env):
|
||||
config = get_backup_config(env)
|
||||
|
||||
env = { "PASSPHRASE" : get_passphrase(env) }
|
||||
env = {"PASSPHRASE": get_passphrase(env)}
|
||||
|
||||
if get_target_type(config) == 's3':
|
||||
env["AWS_ACCESS_KEY_ID"] = config["target_user"]
|
||||
|
@ -216,10 +261,12 @@ def get_env(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"
|
||||
|
@ -235,7 +282,7 @@ def perform_backup(full_backup, user_initiated=False):
|
|||
return "Another backup is already being done!"
|
||||
else:
|
||||
lock.forever()
|
||||
|
||||
|
||||
config = get_backup_config(env)
|
||||
backup_root = os.path.join(env["STORAGE_ROOT"], 'backup')
|
||||
backup_cache_dir = os.path.join(backup_root, 'cache')
|
||||
|
@ -260,7 +307,10 @@ 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:
|
||||
|
@ -284,18 +334,12 @@ def perform_backup(full_backup, user_initiated=False):
|
|||
# after the first backup. See #396.
|
||||
try:
|
||||
shell('check_call', [
|
||||
"/usr/bin/duplicity",
|
||||
"full" if full_backup else "incr",
|
||||
"--verbosity", "warning", "--no-print-statistics",
|
||||
"--archive-dir", backup_cache_dir,
|
||||
"--exclude", backup_root,
|
||||
"--volsize", "250",
|
||||
"--gpg-options", "--cipher-algo=AES256",
|
||||
env["STORAGE_ROOT"],
|
||||
config["target"],
|
||||
"--allow-source-mismatch"
|
||||
] + rsync_ssh_options(port = config["target_rsync_port"]),
|
||||
get_env(env))
|
||||
"/usr/bin/duplicity", "full" if full_backup else "incr",
|
||||
"--verbosity", "warning", "--no-print-statistics", "--archive-dir",
|
||||
backup_cache_dir, "--exclude", backup_root, "--volsize", "250",
|
||||
"--gpg-options", "--cipher-algo=AES256", env["STORAGE_ROOT"],
|
||||
config["target"], "--allow-source-mismatch"
|
||||
] + rsync_ssh_options(port=config["target_rsync_port"]), get_env(env))
|
||||
finally:
|
||||
# Start services again.
|
||||
service_command("dovecot", "start", quit=False)
|
||||
|
@ -305,15 +349,10 @@ 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/bin/duplicity",
|
||||
"remove-older-than",
|
||||
"%dD" % config["min_age_in_days"],
|
||||
"--verbosity", "error",
|
||||
"--archive-dir", backup_cache_dir,
|
||||
"--force",
|
||||
config["target"]
|
||||
] + rsync_ssh_options(port = config["target_rsync_port"]),
|
||||
get_env(env))
|
||||
"/usr/bin/duplicity", "remove-older-than",
|
||||
"%dD" % config["min_age_in_days"], "--verbosity", "error",
|
||||
"--archive-dir", backup_cache_dir, "--force", 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
|
||||
|
@ -321,19 +360,15 @@ 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/bin/duplicity",
|
||||
"cleanup",
|
||||
"--verbosity", "error",
|
||||
"--archive-dir", backup_cache_dir,
|
||||
"--force",
|
||||
config["target"]
|
||||
] + rsync_ssh_options(port = config["target_rsync_port"]),
|
||||
get_env(env))
|
||||
"/usr/bin/duplicity", "cleanup", "--verbosity", "error",
|
||||
"--archive-dir", backup_cache_dir, "--force", 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
|
||||
|
@ -356,6 +391,7 @@ 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')
|
||||
|
@ -364,14 +400,18 @@ def run_duplicity_verification():
|
|||
|
||||
shell('check_call', [
|
||||
"/usr/bin/duplicity",
|
||||
"--verbosity", "info",
|
||||
"--verbosity",
|
||||
"info",
|
||||
"verify",
|
||||
"--compare-data",
|
||||
"--archive-dir", backup_cache_dir,
|
||||
"--exclude", backup_root,
|
||||
"--archive-dir",
|
||||
backup_cache_dir,
|
||||
"--exclude",
|
||||
backup_root,
|
||||
config["target"],
|
||||
env["STORAGE_ROOT"],
|
||||
] + rsync_ssh_options(port = config["target_rsync_port"]), get_env(env))
|
||||
] + rsync_ssh_options(port=config["target_rsync_port"]), get_env(env))
|
||||
|
||||
|
||||
def run_duplicity_restore(args):
|
||||
env = load_environment()
|
||||
|
@ -380,10 +420,12 @@ def run_duplicity_restore(args):
|
|||
shell('check_call', [
|
||||
"/usr/bin/duplicity",
|
||||
"restore",
|
||||
"--archive-dir", backup_cache_dir,
|
||||
"--archive-dir",
|
||||
backup_cache_dir,
|
||||
config["target"],
|
||||
] + rsync_ssh_options(port = config["target_rsync_port"]) + args,
|
||||
get_env(env))
|
||||
] + rsync_ssh_options(port=config["target_rsync_port"]) + args,
|
||||
get_env(env))
|
||||
|
||||
|
||||
def list_target_files(config):
|
||||
import urllib.parse
|
||||
|
@ -393,7 +435,8 @@ 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'.* ([^ ]*) [^ ]* [^ ]* (.*)')
|
||||
|
@ -405,23 +448,24 @@ def list_target_files(config):
|
|||
if target_path.startswith('/'):
|
||||
target_path = target_path[1:]
|
||||
|
||||
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)
|
||||
]
|
||||
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:
|
||||
|
@ -429,18 +473,21 @@ 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))
|
||||
"Please check running 'management/backup.py --verify' " \
|
||||
"from mailinabox sources to debug the issue."
|
||||
raise ValueError(
|
||||
"Connection to rsync host failed: {}".format(reason))
|
||||
|
||||
elif target.scheme == "s3":
|
||||
# match to a Region
|
||||
fix_boto() # must call prior to importing boto
|
||||
fix_boto() # must call prior to importing boto
|
||||
import boto.s3
|
||||
from boto.exception import BotoServerError
|
||||
custom_region = False
|
||||
|
@ -457,7 +504,9 @@ def list_target_files(config):
|
|||
# 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)
|
||||
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 == '/':
|
||||
|
@ -468,7 +517,8 @@ def list_target_files(config):
|
|||
|
||||
# connect to the region & bucket
|
||||
try:
|
||||
conn = region.connect(aws_access_key_id=config["target_user"], aws_secret_access_key=config["target_pass"])
|
||||
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:
|
||||
|
@ -479,7 +529,8 @@ def list_target_files(config):
|
|||
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)]
|
||||
return [(key.name[len(path):], key.size)
|
||||
for key in bucket.list(prefix=path)]
|
||||
elif target.scheme == 'b2':
|
||||
InMemoryAccountInfo = None
|
||||
B2Api = None
|
||||
|
@ -497,30 +548,35 @@ def list_target_files(config):
|
|||
|
||||
info = InMemoryAccountInfo()
|
||||
b2_api = B2Api(info)
|
||||
|
||||
|
||||
# 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_bucket = target.netloc[target.netloc.index('@')+1:]
|
||||
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:
|
||||
raise ValueError(config["target"])
|
||||
|
||||
|
||||
def backup_set_custom(env, target, target_user, target_pass, target_rsync_port, min_age):
|
||||
def backup_set_custom(env, target, target_user, target_pass, target_rsync_port,
|
||||
min_age):
|
||||
config = get_backup_config(env, for_save=True)
|
||||
|
||||
# min_age must be an int
|
||||
if isinstance(min_age, str):
|
||||
min_age = int(min_age)
|
||||
|
||||
|
||||
if isinstance(target_rsync_port, str):
|
||||
try:
|
||||
target_rsync_port = int(target_rsync_port)
|
||||
|
@ -546,20 +602,19 @@ 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
|
||||
|
@ -587,11 +642,13 @@ 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":
|
||||
|
@ -601,7 +658,8 @@ 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":
|
||||
|
|
|
@ -6,7 +6,14 @@
|
|||
# root API key. This file is readable only by root, so this
|
||||
# tool can only be used as root.
|
||||
|
||||
import sys, getpass, urllib.request, urllib.error, json, re, csv
|
||||
import sys
|
||||
import getpass
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
import json
|
||||
import re
|
||||
import csv
|
||||
|
||||
|
||||
def mgmt(cmd, data=None, is_json=False):
|
||||
# The base URL for the management daemon. (Listens on IPv4 only.)
|
||||
|
@ -14,7 +21,9 @@ 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:
|
||||
|
@ -23,70 +32,74 @@ 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: ')
|
||||
if len(first) < 8:
|
||||
print("Passwords must be at least eight characters.")
|
||||
continue
|
||||
second = getpass.getpass(' (again): ')
|
||||
if first != second:
|
||||
print("Passwords not the same. Try again.")
|
||||
continue
|
||||
break
|
||||
return first
|
||||
while True:
|
||||
first = getpass.getpass('password: ')
|
||||
if len(first) < 8:
|
||||
print("Passwords must be at least eight characters.")
|
||||
continue
|
||||
second = getpass.getpass(' (again): ')
|
||||
if first != second:
|
||||
print("Passwords not the same. Try again.")
|
||||
continue
|
||||
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',
|
||||
uri=mgmt_uri,
|
||||
user=key,
|
||||
passwd='')
|
||||
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)
|
||||
{cli} user (lists users)
|
||||
{cli} user add user@domain.com [password]
|
||||
{cli} user password user@domain.com [password]
|
||||
{cli} user remove user@domain.com
|
||||
{cli} user make-admin user@domain.com
|
||||
{cli} user quota user@domain [new-quota]
|
||||
{cli} user remove-admin user@domain.com
|
||||
{cli} user admins (lists admins)
|
||||
{cli} user mfa show user@domain.com (shows MFA devices for user, if any)
|
||||
{cli} user mfa disable user@domain.com [id] (disables MFA for user)
|
||||
{cli} alias (lists aliases)
|
||||
{cli} alias add incoming.name@domain.com sent.to@other.domain.com
|
||||
{cli} alias add incoming.name@domain.com 'sent.to@other.domain.com, multiple.people@other.domain.com'
|
||||
{cli} alias remove incoming.name@domain.com
|
||||
{cli} system default-quota [new default] (set default quota for system)
|
||||
{cli} user (lists users)
|
||||
{cli} user add user@domain.com [password]
|
||||
{cli} user password user@domain.com [password]
|
||||
{cli} user remove user@domain.com
|
||||
{cli} user make-admin user@domain.com
|
||||
{cli} user quota user@domain [new-quota]
|
||||
{cli} user remove-admin user@domain.com
|
||||
{cli} user admins (lists admins)
|
||||
{cli} user mfa show user@domain.com (shows MFA devices for user, if any)
|
||||
{cli} user mfa disable user@domain.com [id] (disables MFA for user)
|
||||
{cli} alias (lists aliases)
|
||||
{cli} alias add incoming.name@domain.com sent.to@other.domain.com
|
||||
{cli} alias add incoming.name@domain.com 'sent.to@other.domain.com, multiple.people@other.domain.com'
|
||||
{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='')
|
||||
|
@ -107,19 +120,25 @@ elif sys.argv[1] == "user" and sys.argv[2] in ("add", "password"):
|
|||
email, pw = sys.argv[3:5]
|
||||
|
||||
if sys.argv[2] == "add":
|
||||
print(mgmt("/mail/users/add", { "email": email, "password": pw }))
|
||||
print(mgmt("/mail/users/add", {"email": email, "password": pw}))
|
||||
elif sys.argv[2] == "password":
|
||||
print(mgmt("/mail/users/password", { "email": email, "password": pw }))
|
||||
print(mgmt("/mail/users/password", {"email": email, "password": pw}))
|
||||
|
||||
elif sys.argv[1] == "user" and sys.argv[2] == "remove" and len(sys.argv) == 4:
|
||||
print(mgmt("/mail/users/remove", { "email": sys.argv[3] }))
|
||||
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.
|
||||
|
@ -135,36 +154,51 @@ 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)
|
||||
status = mgmt("/mfa/status", {"user": sys.argv[4]}, is_json=True)
|
||||
W = csv.writer(sys.stdout)
|
||||
W.writerow(["id", "type", "label"])
|
||||
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] }))
|
||||
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:
|
||||
print(mgmt("/system/default-quota", { "default_quota": sys.argv[3]}))
|
||||
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
|
@ -24,9 +24,17 @@
|
|||
|
||||
# create the new config file in memory
|
||||
|
||||
import sys, re
|
||||
import sys
|
||||
import re
|
||||
|
||||
def edit_conf(filename, settings, delimiter_re, delimiter, comment_char, folded_lines = False, testing = 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+"))
|
||||
|
@ -45,25 +53,26 @@ def edit_conf(filename, settings, delimiter_re, delimiter, comment_char, folded_
|
|||
# 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, 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
|
||||
|
@ -97,11 +106,14 @@ def edit_conf(filename, settings, delimiter_re, delimiter, comment_char, folded_
|
|||
# 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
|
||||
|
@ -140,4 +152,5 @@ 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)
|
||||
edit_conf(filename, settings, delimiter_re, delimiter, comment_char,
|
||||
folded_lines, testing)
|
||||
|
|
|
@ -39,24 +39,26 @@ 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'))
|
||||
|
||||
# In Python 3.6:
|
||||
#msg.set_content(content)
|
||||
# msg.set_content(content)
|
||||
#msg.add_alternative(content_html, "html")
|
||||
|
||||
# send
|
||||
smtpclient = smtplib.SMTP('127.0.0.1', 25)
|
||||
smtpclient.ehlo()
|
||||
smtpclient.sendmail(
|
||||
noreply, # MAIL FROM
|
||||
admin_addr, # RCPT TO
|
||||
msg.as_string())
|
||||
noreply, # MAIL FROM
|
||||
admin_addr, # RCPT TO
|
||||
msg.as_string())
|
||||
smtpclient.quit()
|
||||
|
|
File diff suppressed because it is too large
Load diff
|
@ -9,11 +9,16 @@
|
|||
# Python 3 in setup/questions.sh to validate the email
|
||||
# address entered by the user.
|
||||
|
||||
import subprocess, shutil, os, sqlite3, re
|
||||
import subprocess
|
||||
import shutil
|
||||
import os
|
||||
import sqlite3
|
||||
import 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
|
||||
|
@ -29,10 +34,9 @@ def validate_email(email, mode=None):
|
|||
# Check the syntax of the address.
|
||||
try:
|
||||
validate_email_(email,
|
||||
allow_smtputf8=False,
|
||||
check_deliverability=False,
|
||||
allow_empty_local=(mode=="alias")
|
||||
)
|
||||
allow_smtputf8=False,
|
||||
check_deliverability=False,
|
||||
allow_empty_local=(mode == "alias"))
|
||||
except EmailNotValidError:
|
||||
return False
|
||||
|
||||
|
@ -45,13 +49,15 @@ 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 ---
|
||||
|
@ -72,6 +78,7 @@ 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.
|
||||
|
@ -84,13 +91,17 @@ 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:
|
||||
|
@ -98,15 +109,17 @@ 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)
|
||||
c.execute('SELECT email FROM users')
|
||||
users = [ row[0] for row in c.fetchall() ]
|
||||
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']:
|
||||
for unit in ['', 'K', 'M', 'G', 'T']:
|
||||
if abs(num) < 1024.0:
|
||||
if abs(num) > 99:
|
||||
return "%3.0f%s" % (num, unit)
|
||||
|
@ -117,6 +130,7 @@ 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.
|
||||
|
@ -150,7 +164,9 @@ 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():
|
||||
|
@ -175,10 +191,11 @@ def get_mail_users_ex(env, with_archived=False):
|
|||
user = {
|
||||
"email": email,
|
||||
"privileges": parse_privs(privileges),
|
||||
"quota": quota,
|
||||
"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",
|
||||
}
|
||||
|
@ -192,39 +209,41 @@ 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": [],
|
||||
"status": "inactive",
|
||||
"mailbox": mbox,
|
||||
"box_count": '?',
|
||||
"box_size": '?',
|
||||
"box_quota": '?',
|
||||
"percent": '?',
|
||||
"box_count": '?',
|
||||
"box_size": '?',
|
||||
"box_quota": '?',
|
||||
"percent": '?',
|
||||
}
|
||||
users.append(user)
|
||||
|
||||
# Group by domain.
|
||||
domains = { }
|
||||
domains = {}
|
||||
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()
|
||||
|
@ -234,16 +253,23 @@ 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')
|
||||
aliases = { row[0]: row for row in c.fetchall() } # make dict
|
||||
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.
|
||||
|
@ -268,7 +294,8 @@ 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)
|
||||
|
@ -280,28 +307,42 @@ 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.
|
||||
# Mail sent to these addresses is automatically bounced with a customized message..
|
||||
c = open_database(env)
|
||||
c.execute('SELECT email FROM noreply')
|
||||
return set( row[0] for row in c.fetchall() )
|
||||
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
|
||||
|
@ -316,6 +357,7 @@ 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)
|
||||
|
@ -328,18 +370,28 @@ 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):
|
||||
|
||||
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() == "":
|
||||
|
@ -347,12 +399,16 @@ 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)
|
||||
|
@ -364,7 +420,8 @@ 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()
|
||||
|
@ -382,7 +439,8 @@ 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)
|
||||
|
@ -395,6 +453,7 @@ 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)
|
||||
|
@ -410,16 +469,19 @@ 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):
|
||||
conn, c = open_database(env, with_connection=True)
|
||||
c.execute("SELECT quota FROM users WHERE email=?", (email,))
|
||||
c.execute("SELECT quota FROM users WHERE email=?", (email, ))
|
||||
rows = c.fetchall()
|
||||
if len(rows) != 1:
|
||||
return ("That's not a user (%s)." % email, 400)
|
||||
|
@ -442,6 +504,7 @@ 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
|
||||
|
@ -452,10 +515,12 @@ 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()
|
||||
|
@ -463,28 +528,31 @@ 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.
|
||||
# http://wiki2.dovecot.org/Authentication/PasswordSchemes
|
||||
# update the database
|
||||
c = open_database(env)
|
||||
c.execute('SELECT password FROM users WHERE email=?', (email,))
|
||||
c.execute('SELECT password FROM users WHERE email=?', (email, ))
|
||||
rows = c.fetchall()
|
||||
if len(rows) != 1:
|
||||
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)
|
||||
c.execute("DELETE FROM users WHERE email=?", (email,))
|
||||
c.execute("DELETE FROM users WHERE email=?", (email, ))
|
||||
if c.rowcount != 1:
|
||||
return ("That's not a user (%s)." % email, 400)
|
||||
conn.commit()
|
||||
|
@ -492,32 +560,39 @@ 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,))
|
||||
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":
|
||||
|
@ -530,14 +605,21 @@ 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)
|
||||
|
||||
|
@ -574,17 +656,23 @@ def add_mail_alias(address, forwards_to, permitted_senders, env, update_if_exist
|
|||
for line in forwards_to.split("\n"):
|
||||
for email in line.split(","):
|
||||
email = email.strip()
|
||||
if email == "": continue
|
||||
email = sanitize_idn_email_address(email) # Unicode => IDNA
|
||||
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)
|
||||
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
|
||||
|
@ -597,14 +685,19 @@ def add_mail_alias(address, forwards_to, permitted_senders, env, update_if_exist
|
|||
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
|
||||
|
||||
|
@ -617,13 +710,17 @@ def add_mail_alias(address, forwards_to, permitted_senders, env, update_if_exist
|
|||
|
||||
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()
|
||||
|
@ -632,13 +729,14 @@ def add_mail_alias(address, forwards_to, permitted_senders, env, update_if_exist
|
|||
# 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)
|
||||
|
||||
# remove
|
||||
conn, c = open_database(env, with_connection=True)
|
||||
c.execute("DELETE FROM aliases WHERE source=?", (address,))
|
||||
c.execute("DELETE FROM aliases WHERE source=?", (address, ))
|
||||
if c.rowcount != 1:
|
||||
return ("That's not an alias (%s)." % address, 400)
|
||||
conn.commit()
|
||||
|
@ -647,16 +745,21 @@ 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()
|
||||
|
@ -669,13 +772,11 @@ 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.
|
||||
|
@ -689,6 +790,7 @@ def get_required_aliases(env):
|
|||
|
||||
return aliases
|
||||
|
||||
|
||||
def add_noreply_address(env, address, do_kick=True):
|
||||
email = sanitize_idn_email_address(address)
|
||||
# validate email
|
||||
|
@ -702,29 +804,30 @@ def add_noreply_address(env, address, do_kick=True):
|
|||
return ("This address is already an user.", 400)
|
||||
elif email in get_mail_aliases(env):
|
||||
return ("This address is already an alias.", 400)
|
||||
|
||||
|
||||
ret = ""
|
||||
|
||||
# Add the address
|
||||
conn, c = open_database(env, with_connection=True)
|
||||
try:
|
||||
c.execute("INSERT INTO noreply (email) VALUES (?)", (email,))
|
||||
c.execute("INSERT INTO noreply (email) VALUES (?)", (email, ))
|
||||
if do_kick:
|
||||
ret = kick(env, "No-reply address (%s) added" % address)
|
||||
else:
|
||||
ret = "No-reply address (%s) added" % address
|
||||
except sqlite3.IntegrityError:
|
||||
return ("This noreply (%s) already exists." % address, 400)
|
||||
|
||||
|
||||
conn.commit()
|
||||
return ret
|
||||
|
||||
|
||||
def remove_noreply_address(env, address, do_kick=True):
|
||||
email = sanitize_idn_email_address(address)
|
||||
|
||||
# yeet yeet deleet
|
||||
conn, c = open_database(env, with_connection=True)
|
||||
c.execute("DELETE FROM noreply WHERE email=?", (email,))
|
||||
c.execute("DELETE FROM noreply WHERE email=?", (email, ))
|
||||
if c.rowcount != 1:
|
||||
return ("That's not a noreply (%s)." % address, 400)
|
||||
conn.commit()
|
||||
|
@ -733,8 +836,10 @@ 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'] }
|
||||
return {"noreply-daemon@" + env['PRIMARY_HOSTNAME']}
|
||||
|
||||
|
||||
def kick(env, mail_result=None):
|
||||
results = []
|
||||
|
@ -744,7 +849,7 @@ def kick(env, mail_result=None):
|
|||
if mail_result is not None:
|
||||
results.append(mail_result + "\n")
|
||||
|
||||
auto_aliases = { }
|
||||
auto_aliases = {}
|
||||
|
||||
# Mape required aliases to the administrator alias (which should be created manually).
|
||||
administrator = get_system_administrator(env)
|
||||
|
@ -752,18 +857,20 @@ 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
|
||||
auto_aliases[alias] = administrator
|
||||
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
|
||||
|
||||
|
||||
add_auto_aliases(auto_aliases, env)
|
||||
for address in required_noreply - existing_noreply:
|
||||
add_noreply_address(env, address, do_kick=False)
|
||||
|
@ -774,22 +881,25 @@ def kick(env, mail_result=None):
|
|||
for address, forwards_to, permitted_senders, auto in get_mail_aliases(env):
|
||||
user, domain = address.split("@")
|
||||
if user in ("postmaster", "admin", "abuse") \
|
||||
and address not in required_aliases \
|
||||
and forwards_to == get_system_administrator(env) \
|
||||
and not auto:
|
||||
and address not in required_aliases \
|
||||
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.
|
||||
|
||||
from dns_update import do_dns_update
|
||||
results.append( do_dns_update(env) )
|
||||
results.append(do_dns_update(env))
|
||||
|
||||
from web_update import do_web_update
|
||||
results.append( do_web_update(env) )
|
||||
results.append(do_web_update(env))
|
||||
|
||||
return "".join(s for s in results if s != "")
|
||||
|
||||
|
||||
def validate_password(pw):
|
||||
# validate password
|
||||
if pw.strip() == "":
|
||||
|
@ -797,6 +907,7 @@ 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":
|
||||
|
|
|
@ -7,33 +7,46 @@ import qrcode
|
|||
|
||||
from mailconfig import open_database
|
||||
|
||||
|
||||
def get_user_id(email, c):
|
||||
c.execute('SELECT id FROM users WHERE email=?', (email,))
|
||||
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":
|
||||
|
@ -46,41 +59,48 @@ 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:
|
||||
# Disable all MFA for a user.
|
||||
c.execute('DELETE FROM mfa WHERE user_id=?', (get_user_id(email, c),))
|
||||
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')
|
||||
validate_totp_secret(secret) # sanity check
|
||||
validate_totp_secret(secret) # sanity check
|
||||
|
||||
# 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)
|
||||
|
@ -88,11 +108,8 @@ 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
|
||||
|
|
|
@ -1,7 +1,11 @@
|
|||
#!/usr/local/lib/mailinabox/env/bin/python
|
||||
# Tools to manipulate PGP keys
|
||||
|
||||
import gpg, utils, datetime, shutil, tempfile
|
||||
import gpg
|
||||
import utils
|
||||
import datetime
|
||||
import shutil
|
||||
import tempfile
|
||||
|
||||
env = utils.load_environment()
|
||||
|
||||
|
@ -11,50 +15,73 @@ 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
|
||||
key_rep = {
|
||||
"master_fpr": key.fpr,
|
||||
"revoked": key.revoked != 0,
|
||||
"ids": [],
|
||||
if key is None:
|
||||
return None
|
||||
key_rep = {
|
||||
"master_fpr": key.fpr,
|
||||
"revoked": key.revoked != 0,
|
||||
"ids": [],
|
||||
"ids_emails": {},
|
||||
"subkeys": []
|
||||
}
|
||||
"subkeys": []
|
||||
}
|
||||
|
||||
now = datetime.datetime.utcnow()
|
||||
key_rep["ids"] = [ id.uid 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
|
||||
} for skey in key.subkeys ]
|
||||
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["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
|
||||
} for skey in key.subkeys]
|
||||
|
||||
return key_rep
|
||||
|
||||
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:
|
||||
result = tmp.key_import(imports)
|
||||
try:
|
||||
return result.secret_read != 0
|
||||
except AttributeError:
|
||||
raise ValueError("Import is not a valid PGP key block!")
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
with gpg.Context(home_dir=tmpdir, armor=True) as tmp:
|
||||
result = tmp.key_import(imports)
|
||||
try:
|
||||
return result.secret_read != 0
|
||||
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):
|
||||
|
||||
|
||||
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:
|
||||
|
@ -65,15 +92,18 @@ 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)
|
||||
|
||||
return wrapped
|
||||
|
||||
|
||||
def get_key(fingerprint, context = default_context):
|
||||
def get_key(fingerprint, context=default_context):
|
||||
try:
|
||||
return context.get_key(fingerprint, secret=False)
|
||||
except KeyError:
|
||||
|
@ -81,57 +111,68 @@ 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)
|
||||
)
|
||||
)
|
||||
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 import_key(key, context = default_context):
|
||||
data = str.encode(key)
|
||||
if contains_private_keys(data):
|
||||
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
|
||||
return context.key_export(pattern=fingerprint) # Key does exist, export it!
|
||||
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)))
|
||||
|
||||
|
||||
def import_key(key, context=default_context):
|
||||
data = str.encode(key)
|
||||
if contains_private_keys(data):
|
||||
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)
|
||||
|
||||
|
||||
def delete_key(fingerprint, context=default_context):
|
||||
key = get_key(fingerprint)
|
||||
if fingerprint == daemon_key_fpr:
|
||||
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)
|
||||
return True
|
||||
|
||||
def delete_key(fingerprint, context = default_context):
|
||||
key = get_key(fingerprint)
|
||||
if fingerprint == daemon_key_fpr:
|
||||
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)
|
||||
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)
|
||||
return signed_data
|
||||
|
||||
|
||||
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)
|
||||
return signed_data
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys, utils
|
||||
# Check if we should renew the key
|
||||
import sys
|
||||
import utils
|
||||
# Check if we should renew the key
|
||||
|
||||
daemon_key = get_daemon_key()
|
||||
daemon_key = get_daemon_key()
|
||||
|
||||
exp = daemon_key.subkeys[0].expires
|
||||
now = datetime.datetime.utcnow()
|
||||
days_left = (datetime.datetime.utcfromtimestamp(exp) - now).days
|
||||
if days_left > 14:
|
||||
sys.exit(0)
|
||||
else:
|
||||
utils.shell("check_output", ["management/pgp_renew.sh"])
|
||||
exp = daemon_key.subkeys[0].expires
|
||||
now = datetime.datetime.utcnow()
|
||||
days_left = (datetime.datetime.utcfromtimestamp(exp) - now).days
|
||||
if days_left > 14:
|
||||
sys.exit(0)
|
||||
else:
|
||||
utils.shell("check_output", ["management/pgp_renew.sh"])
|
||||
|
|
|
@ -1,13 +1,19 @@
|
|||
#!/usr/local/lib/mailinabox/env/bin/python
|
||||
# Utilities for installing and selecting SSL certificates.
|
||||
|
||||
import os, os.path, re, shutil, subprocess, tempfile
|
||||
import os
|
||||
import os.path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import 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
|
||||
|
@ -44,8 +50,8 @@ def get_ssl_certificates(env):
|
|||
yield fn1
|
||||
|
||||
# Remember stuff.
|
||||
private_keys = { }
|
||||
certificates = [ ]
|
||||
private_keys = {}
|
||||
certificates = []
|
||||
|
||||
# Scan each of the files to find private keys and certificates.
|
||||
# We must load all of the private keys first before processing
|
||||
|
@ -70,7 +76,7 @@ def get_ssl_certificates(env):
|
|||
certificates.append(pem)
|
||||
|
||||
# Process the certificates.
|
||||
domains = { }
|
||||
domains = {}
|
||||
for cert in certificates:
|
||||
# What domains is this certificate good for?
|
||||
cert_domains, primary_domain = get_certificate_domains(cert)
|
||||
|
@ -87,7 +93,8 @@ def get_ssl_certificates(env):
|
|||
# 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)
|
||||
|
@ -95,62 +102,71 @@ def get_ssl_certificates(env):
|
|||
# Sort the certificates to prefer good ones.
|
||||
import datetime
|
||||
now = datetime.datetime.utcnow()
|
||||
ret = { }
|
||||
ret = {}
|
||||
for domain, cert_list in domains.items():
|
||||
#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.not_valid_before <= now <= cert.not_valid_after,
|
||||
cert_list.sort(
|
||||
key=lambda cert: (
|
||||
# must be valid NOW
|
||||
cert.not_valid_before <= now <= cert.not_valid_after,
|
||||
|
||||
# prefer one that is not self-signed
|
||||
cert.issuer != cert.subject,
|
||||
# prefer one that is not self-signed
|
||||
cert.issuer != cert.subject,
|
||||
|
||||
###########################################################
|
||||
# The above lines ensure that valid certificates are chosen
|
||||
# over invalid certificates. The lines below choose between
|
||||
# multiple valid certificates available for this domain.
|
||||
###########################################################
|
||||
###########################################################
|
||||
# The above lines ensure that valid certificates are chosen
|
||||
# over invalid certificates. The lines below choose between
|
||||
# multiple valid certificates available for this domain.
|
||||
###########################################################
|
||||
|
||||
# prefer one with the expiration furthest into the future so
|
||||
# that we can easily rotate to new certs as we get them
|
||||
cert.not_valid_after,
|
||||
# prefer one with the expiration furthest into the future so
|
||||
# that we can easily rotate to new certs as we get them
|
||||
cert.not_valid_after,
|
||||
|
||||
###########################################################
|
||||
# We always choose the certificate that is good for the
|
||||
# longest period of time. This is important for how we
|
||||
# provision certificates for Let's Encrypt. To ensure that
|
||||
# we don't re-provision every night, we have to ensure that
|
||||
# if we choose to provison a certificate that it will
|
||||
# *actually* be used so the provisioning logic knows it
|
||||
# doesn't still need to provision a certificate for the
|
||||
# domain.
|
||||
###########################################################
|
||||
###########################################################
|
||||
# We always choose the certificate that is good for the
|
||||
# longest period of time. This is important for how we
|
||||
# provision certificates for Let's Encrypt. To ensure that
|
||||
# we don't re-provision every night, we have to ensure that
|
||||
# if we choose to provison a certificate that it will
|
||||
# *actually* be used so the provisioning logic knows it
|
||||
# doesn't still need to provision a certificate for the
|
||||
# domain.
|
||||
###########################################################
|
||||
|
||||
# in case a certificate is installed in multiple paths,
|
||||
# prefer the... lexicographically last one?
|
||||
cert._filename,
|
||||
|
||||
), reverse=True)
|
||||
# in case a certificate is installed in multiple paths,
|
||||
# prefer the... lexicographically last one?
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
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:
|
||||
|
@ -174,7 +190,10 @@ def get_domain_ssl_files(domain, ssl_certificates, env, allow_missing_cert=False
|
|||
|
||||
# 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:
|
||||
|
@ -192,7 +211,7 @@ def get_certificates_to_provision(env, limit_domains=None, show_valid_certs=True
|
|||
actual_web_domains = get_web_domains(env)
|
||||
|
||||
domains_to_provision = set()
|
||||
domains_cant_provision = { }
|
||||
domains_cant_provision = {}
|
||||
|
||||
for domain in plausible_web_domains:
|
||||
# Skip domains that the user doesn't want to provision now.
|
||||
|
@ -201,7 +220,8 @@ def get_certificates_to_provision(env, limit_domains=None, show_valid_certs=True
|
|||
|
||||
# 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:
|
||||
|
@ -211,41 +231,53 @@ def get_certificates_to_provision(env, limit_domains=None, show_valid_certs=True
|
|||
# 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))
|
||||
|
||||
if bad_dns:
|
||||
domains_cant_provision[domain] = "The domain name does not resolve to this machine: " \
|
||||
+ (", ".join(bad_dns)) \
|
||||
+ "."
|
||||
+ (", ".join(bad_dns)) \
|
||||
+ "."
|
||||
|
||||
else:
|
||||
# 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(
|
||||
existing_cert_check[1],
|
||||
existing_cert['certificate'],
|
||||
existing_cert['private-key'])
|
||||
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'])
|
||||
continue
|
||||
|
||||
domains_to_provision.add(domain)
|
||||
|
||||
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 = []
|
||||
|
@ -267,7 +299,7 @@ def provision_certificates(env, limit_domains):
|
|||
# entry in each list (unless we overflow beyond 100) which ends up as the
|
||||
# primary domain listed in each certificate.
|
||||
from dns_update import get_dns_zones
|
||||
certs = { }
|
||||
certs = {}
|
||||
for zone, zonefile in get_dns_zones(env):
|
||||
certs[zone] = [[]]
|
||||
for domain in sort_domains(domains, env):
|
||||
|
@ -308,7 +340,8 @@ 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
|
||||
|
@ -326,12 +359,18 @@ 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))
|
||||
|
||||
|
@ -340,27 +379,40 @@ 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([
|
||||
"certbot",
|
||||
"certonly",
|
||||
#"-v", # just enough to see ACME errors
|
||||
"--non-interactive", # will fail if user hasn't registered during Mail-in-a-Box setup
|
||||
"--agree-tos", # Automatically agrees to Let's Encrypt TOS
|
||||
"--register-unsafely-without-email", # The daemon takes care of renewals
|
||||
print("Provisioning TLS certificates for " +
|
||||
", ".join(domain_list) + ".")
|
||||
certbotret = subprocess.check_output(
|
||||
[
|
||||
"certbot",
|
||||
"certonly",
|
||||
# "-v", # just enough to see ACME errors
|
||||
"--non-interactive", # will fail if user hasn't registered during Mail-in-a-Box setup
|
||||
"--agree-tos", # Automatically agrees to Let's Encrypt TOS
|
||||
"--register-unsafely-without-email", # The daemon takes care of renewals
|
||||
|
||||
"-d", ",".join(domain_list), # first will be main domain
|
||||
# first will be main domain
|
||||
"-d",
|
||||
",".join(domain_list),
|
||||
|
||||
"--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")
|
||||
# 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,
|
||||
# "--staging",
|
||||
],
|
||||
stderr=subprocess.STDOUT).decode("utf8")
|
||||
install_cert_copy_file(cert_file, env)
|
||||
|
||||
ret[-1]["log"].append(certbotret)
|
||||
|
@ -378,6 +430,7 @@ 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
|
||||
|
@ -414,12 +467,13 @@ 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.
|
||||
|
@ -430,8 +484,10 @@ 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."
|
||||
|
@ -445,7 +501,8 @@ 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)
|
||||
|
||||
|
||||
|
@ -457,11 +514,15 @@ 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" % (
|
||||
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))
|
||||
# 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
|
||||
)
|
||||
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)
|
||||
|
@ -473,16 +534,21 @@ 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")
|
||||
|
@ -501,13 +567,20 @@ def post_install_func(env):
|
|||
|
||||
# Update the web configuration so nginx picks up the new certificate file.
|
||||
from web_update import do_web_update
|
||||
ret.append( do_web_update(env) )
|
||||
ret.append(do_web_update(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.
|
||||
|
||||
|
@ -520,9 +593,11 @@ def check_certificate(domain, ssl_certificate, ssl_private_key, warn_if_expiring
|
|||
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.
|
||||
|
@ -534,21 +609,27 @@ def check_certificate(domain, ssl_certificate, ssl_private_key, warn_if_expiring
|
|||
# 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".
|
||||
|
@ -569,8 +650,10 @@ def check_certificate(domain, ssl_certificate, ssl_private_key, warn_if_expiring
|
|||
# certificate are 'naive' and in UTC. We need to get the current time in UTC.
|
||||
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)
|
||||
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)
|
||||
|
||||
# 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
|
||||
|
@ -579,11 +662,17 @@ def check_certificate(domain, ssl_certificate, ssl_private_key, warn_if_expiring
|
|||
|
||||
# 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', [
|
||||
"openssl",
|
||||
"verify", "-verbose",
|
||||
"-purpose", "sslserver", "-policy_check",]
|
||||
+ ([] if len(ssl_cert_chain) == 1 else ["-untrusted", "/proc/self/fd/0"])
|
||||
retcode, verifyoutput = shell(
|
||||
'check_output',
|
||||
[
|
||||
"openssl",
|
||||
"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)
|
||||
|
@ -594,10 +683,13 @@ def check_certificate(domain, ssl_certificate, ssl_private_key, warn_if_expiring
|
|||
|
||||
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
|
||||
|
@ -605,13 +697,15 @@ def check_certificate(domain, ssl_certificate, ssl_private_key, warn_if_expiring
|
|||
|
||||
# But is it expiring soon?
|
||||
cert_expiration_date = cert.not_valid_after
|
||||
ndays = (cert_expiration_date-now).days
|
||||
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
|
||||
|
@ -621,17 +715,19 @@ def check_certificate(domain, ssl_certificate, ssl_private_key, warn_if_expiring
|
|||
# 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.
|
||||
re_pem = rb"(-+BEGIN (?:.+)-+[\r\n]+(?:[A-Za-z0-9+/=]{1,64}[\r\n]+)+-+END (?:.+)-+[\r\n]+)"
|
||||
with open(pemfile, "rb") as f:
|
||||
pem = f.read() + b"\n" # ensure trailing newline
|
||||
pem = f.read() + b"\n" # ensure trailing newline
|
||||
pemblocks = re.findall(re_pem, pem)
|
||||
if len(pemblocks) == 0:
|
||||
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.
|
||||
|
@ -643,10 +739,14 @@ 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
|
||||
|
@ -675,7 +775,8 @@ 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:
|
||||
|
@ -683,6 +784,7 @@ def get_certificate_domains(cert):
|
|||
|
||||
return names, cn
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Provision certificates.
|
||||
provision_certificates_cmdline()
|
||||
|
|
File diff suppressed because it is too large
Load diff
|
@ -1,125 +1,149 @@
|
|||
<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 .alias-auto .actions>* {
|
||||
display: none
|
||||
}
|
||||
|
||||
#addalias-form .hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.btn.btn-xs {
|
||||
padding: .1rem .3rem;
|
||||
font-size: .75rem;
|
||||
border-radius: .2rem;
|
||||
}
|
||||
</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 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>
|
||||
</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>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<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>
|
||||
</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>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-lg-9 mb-3">
|
||||
<div class="input-group">
|
||||
<label for="addaliasAddress" class="input-group-text">Alias</label>
|
||||
<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 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>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-lg-9 mb-3">
|
||||
<div class="input-group">
|
||||
<label for="addaliasAddress" class="input-group-text">Alias</label>
|
||||
<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>
|
||||
|
||||
<h4>Permitted Senders</h4>
|
||||
<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 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>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-lg-9 mb-3">
|
||||
<div class="mb-3">
|
||||
<div class="mb-3">
|
||||
<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>.
|
||||
</label>
|
||||
</div>
|
||||
<div class="radio">
|
||||
<label>
|
||||
<input id="addaliasForwardsToAdvanced" name="addaliasForwardsToDivToggle" type="radio" id="addaliasForwardsToDivShower" onclick="$('#addaliasForwardsToDiv').toggle(true)">
|
||||
I’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>
|
||||
</div>
|
||||
</div>
|
||||
<button id="add-alias-button" type="submit" class="btn btn-primary">Add Alias</button>
|
||||
<h4>Permitted Senders</h4>
|
||||
|
||||
<div class="col-lg-9 mb-3">
|
||||
<div class="mb-3">
|
||||
<div class="mb-3">
|
||||
<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>.
|
||||
</label>
|
||||
</div>
|
||||
<div class="radio">
|
||||
<label>
|
||||
<input id="addaliasForwardsToAdvanced" name="addaliasForwardsToDivToggle" type="radio"
|
||||
id="addaliasForwardsToDivShower" onclick="$('#addaliasForwardsToDiv').toggle(true)">
|
||||
I’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>
|
||||
</div>
|
||||
</div>
|
||||
<button id="add-alias-button" type="submit" class="btn btn-primary">Add Alias</button>
|
||||
</form>
|
||||
|
||||
<h3>Existing mail aliases</h3>
|
||||
<table id="alias_table" class="table">
|
||||
<caption></caption>
|
||||
<thead>
|
||||
<tr>
|
||||
<th></th>
|
||||
<th>Alias<br></th>
|
||||
<th>Forwards To</th>
|
||||
<th>Permitted Senders</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
</tbody>
|
||||
<caption></caption>
|
||||
<thead>
|
||||
<tr>
|
||||
<th></th>
|
||||
<th>Alias<br></th>
|
||||
<th>Forwards To</th>
|
||||
<th>Permitted Senders</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
</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>
|
||||
<td class='address'> </td>
|
||||
<td class='forwardsTo'> </td>
|
||||
<td class='senders'> </td>
|
||||
</tr>
|
||||
</table>
|
||||
<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>
|
||||
<td class='address'> </td>
|
||||
<td class='forwardsTo'> </td>
|
||||
<td class='senders'> </td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<h3>Mail aliases API (advanced)</h3>
|
||||
|
||||
<p>Use your box’s mail aliases API to add and remove mail aliases from the command-line or custom services you build.</p>
|
||||
<p>Use your box’s mail aliases API to add and remove mail aliases from the command-line or custom services you
|
||||
build.</p>
|
||||
|
||||
<p>Usage:</p>
|
||||
|
||||
|
@ -132,16 +156,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>
|
||||
<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>
|
||||
<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>
|
||||
</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
|
||||
|
@ -155,157 +198,157 @@ curl -X POST -d "address=new_alias@mydomail.com" https://{{hostname}}/admin/mail
|
|||
|
||||
|
||||
<script>
|
||||
function show_aliases() {
|
||||
$('#alias_table tbody').html("<tr><td colspan='2' class='text-muted'>Loading...</td></tr>")
|
||||
api(
|
||||
"/mail/aliases",
|
||||
"GET",
|
||||
{ format: 'json' },
|
||||
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>");
|
||||
hdr.find('th').text(r[i].domain);
|
||||
$('#alias_table tbody').append(hdr);
|
||||
function show_aliases() {
|
||||
$('#alias_table tbody').html("<tr><td colspan='2' class='text-muted'>Loading...</td></tr>")
|
||||
api(
|
||||
"/mail/aliases",
|
||||
"GET",
|
||||
{ format: 'json' },
|
||||
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>");
|
||||
hdr.find('th').text(r[i].domain);
|
||||
$('#alias_table tbody').append(hdr);
|
||||
|
||||
for (var k = 0; k < r[i].aliases.length; k++) {
|
||||
var alias = r[i].aliases[k];
|
||||
for (var k = 0; k < r[i].aliases.length; k++) {
|
||||
var alias = r[i].aliases[k];
|
||||
|
||||
var n = $("#alias-template").clone();
|
||||
n.attr('id', '');
|
||||
var n = $("#alias-template").clone();
|
||||
n.attr('id', '');
|
||||
|
||||
if (alias.auto) n.addClass('alias-auto');
|
||||
n.attr('data-address', alias.address_display); // this is decoded from IDNA, but will get re-coded to IDNA on the backend
|
||||
n.find('td.address').text(alias.address_display)
|
||||
for (var j = 0; j < alias.forwards_to.length; j++)
|
||||
n.find('td.forwardsTo').append($("<div></div>").text(alias.forwards_to[j]))
|
||||
for (var j = 0; j < (alias.permitted_senders ? alias.permitted_senders.length : 0); j++)
|
||||
n.find('td.senders').append($("<div></div>").text(alias.permitted_senders[j]))
|
||||
$('#alias_table tbody').append(n);
|
||||
}
|
||||
}
|
||||
})
|
||||
if (alias.auto) n.addClass('alias-auto');
|
||||
n.attr('data-address', alias.address_display); // this is decoded from IDNA, but will get re-coded to IDNA on the backend
|
||||
n.find('td.address').text(alias.address_display)
|
||||
for (var j = 0; j < alias.forwards_to.length; j++)
|
||||
n.find('td.forwardsTo').append($("<div></div>").text(alias.forwards_to[j]))
|
||||
for (var j = 0; j < (alias.permitted_senders ? alias.permitted_senders.length : 0); j++)
|
||||
n.find('td.senders').append($("<div></div>").text(alias.permitted_senders[j]))
|
||||
$('#alias_table tbody').append(n);
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
$('#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)');
|
||||
$('#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)');
|
||||
$('#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)');
|
||||
$('#alias_mode_info').slideDown();
|
||||
$('#addalias-form .domainalias').removeClass('hidden');
|
||||
}
|
||||
})
|
||||
$('#alias_type_buttons button[data-mode="regular"]').click(); // init
|
||||
}
|
||||
$('#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)');
|
||||
$('#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)');
|
||||
$('#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)');
|
||||
$('#alias_mode_info').slideDown();
|
||||
$('#addalias-form .domainalias').removeClass('hidden');
|
||||
}
|
||||
})
|
||||
$('#alias_type_buttons button[data-mode="regular"]').click(); // init
|
||||
}
|
||||
|
||||
var is_alias_add_update = false;
|
||||
function do_add_alias() {
|
||||
var title = (!is_alias_add_update) ? "Add Alias" : "Update Alias";
|
||||
var form_address = $("#addaliasAddress").val();
|
||||
var form_forwardsto = $("#addaliasForwardsTo").val();
|
||||
var form_senders = ($('#addaliasForwardsToAdvanced').prop('checked') ? $("#addaliasSenders").val() : '');
|
||||
if ($('#addaliasForwardsToAdvanced').prop('checked') && !/\S/.exec($("#addaliasSenders").val())) {
|
||||
show_modal_error(title, "You did not enter any permitted senders.");
|
||||
return false;
|
||||
}
|
||||
api(
|
||||
"/mail/aliases/add",
|
||||
"POST",
|
||||
{
|
||||
update_if_exists: is_alias_add_update ? '1' : '0',
|
||||
address: form_address,
|
||||
forwards_to: form_forwardsto,
|
||||
permitted_senders: form_senders
|
||||
},
|
||||
function(r) {
|
||||
// Responses are multiple lines of pre-formatted text.
|
||||
show_modal_error(title, $("<pre/>").text(r));
|
||||
show_aliases()
|
||||
aliases_reset_form();
|
||||
},
|
||||
function(r) {
|
||||
show_modal_error(title, r);
|
||||
});
|
||||
return false;
|
||||
}
|
||||
var is_alias_add_update = false;
|
||||
function do_add_alias() {
|
||||
var title = (!is_alias_add_update) ? "Add Alias" : "Update Alias";
|
||||
var form_address = $("#addaliasAddress").val();
|
||||
var form_forwardsto = $("#addaliasForwardsTo").val();
|
||||
var form_senders = ($('#addaliasForwardsToAdvanced').prop('checked') ? $("#addaliasSenders").val() : '');
|
||||
if ($('#addaliasForwardsToAdvanced').prop('checked') && !/\S/.exec($("#addaliasSenders").val())) {
|
||||
show_modal_error(title, "You did not enter any permitted senders.");
|
||||
return false;
|
||||
}
|
||||
api(
|
||||
"/mail/aliases/add",
|
||||
"POST",
|
||||
{
|
||||
update_if_exists: is_alias_add_update ? '1' : '0',
|
||||
address: form_address,
|
||||
forwards_to: form_forwardsto,
|
||||
permitted_senders: form_senders
|
||||
},
|
||||
function (r) {
|
||||
// Responses are multiple lines of pre-formatted text.
|
||||
show_modal_error(title, $("<pre/>").text(r));
|
||||
show_aliases()
|
||||
aliases_reset_form();
|
||||
},
|
||||
function (r) {
|
||||
show_modal_error(title, r);
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
function aliases_reset_form() {
|
||||
$("#addaliasAddress").prop('disabled', false);
|
||||
$("#addaliasAddress").val('')
|
||||
$("#addaliasForwardsTo").val('')
|
||||
$("#addaliasSenders").val('')
|
||||
$('#alias-cancel').addClass('hidden');
|
||||
$('#add-alias-button').text('Add Alias');
|
||||
is_alias_add_update = false;
|
||||
}
|
||||
function aliases_reset_form() {
|
||||
$("#addaliasAddress").prop('disabled', false);
|
||||
$("#addaliasAddress").val('')
|
||||
$("#addaliasForwardsTo").val('')
|
||||
$("#addaliasSenders").val('')
|
||||
$('#alias-cancel').addClass('hidden');
|
||||
$('#add-alias-button').text('Add Alias');
|
||||
is_alias_add_update = false;
|
||||
}
|
||||
|
||||
function aliases_edit(elem) {
|
||||
var address = $(elem).parents('tr').attr('data-address');
|
||||
var receiverdivs = $(elem).parents('tr').find('.forwardsTo div');
|
||||
var senderdivs = $(elem).parents('tr').find('.senders div');
|
||||
var forwardsTo = "";
|
||||
for (var i = 0; i < receiverdivs.length; i++)
|
||||
forwardsTo += $(receiverdivs[i]).text() + "\n";
|
||||
var senders = "";
|
||||
for (var i = 0; i < senderdivs.length; i++)
|
||||
senders += $(senderdivs[i]).text() + "\n";
|
||||
if (address.charAt(0) == '@' && forwardsTo.charAt(0) == '@')
|
||||
$('#alias_type_buttons button[data-mode="domainalias"]').click();
|
||||
else if (address.charAt(0) == '@')
|
||||
$('#alias_type_buttons button[data-mode="catchall"]').click();
|
||||
else
|
||||
$('#alias_type_buttons button[data-mode="regular"]').click();
|
||||
$('#alias-cancel').removeClass('hidden');
|
||||
$("#addaliasAddress").prop('disabled', true);
|
||||
$("#addaliasAddress").val(address);
|
||||
$("#addaliasForwardsTo").val(forwardsTo);
|
||||
$('#addaliasForwardsToAdvanced').prop('checked', senders != "");
|
||||
$('#addaliasForwardsToNotAdvanced').prop('checked', senders == "");
|
||||
$("#addaliasSenders").val(senders);
|
||||
$('#add-alias-button').text('Update');
|
||||
$('body').animate({ scrollTop: 0 })
|
||||
is_alias_add_update = true;
|
||||
}
|
||||
function aliases_edit(elem) {
|
||||
var address = $(elem).parents('tr').attr('data-address');
|
||||
var receiverdivs = $(elem).parents('tr').find('.forwardsTo div');
|
||||
var senderdivs = $(elem).parents('tr').find('.senders div');
|
||||
var forwardsTo = "";
|
||||
for (var i = 0; i < receiverdivs.length; i++)
|
||||
forwardsTo += $(receiverdivs[i]).text() + "\n";
|
||||
var senders = "";
|
||||
for (var i = 0; i < senderdivs.length; i++)
|
||||
senders += $(senderdivs[i]).text() + "\n";
|
||||
if (address.charAt(0) == '@' && forwardsTo.charAt(0) == '@')
|
||||
$('#alias_type_buttons button[data-mode="domainalias"]').click();
|
||||
else if (address.charAt(0) == '@')
|
||||
$('#alias_type_buttons button[data-mode="catchall"]').click();
|
||||
else
|
||||
$('#alias_type_buttons button[data-mode="regular"]').click();
|
||||
$('#alias-cancel').removeClass('hidden');
|
||||
$("#addaliasAddress").prop('disabled', true);
|
||||
$("#addaliasAddress").val(address);
|
||||
$("#addaliasForwardsTo").val(forwardsTo);
|
||||
$('#addaliasForwardsToAdvanced').prop('checked', senders != "");
|
||||
$('#addaliasForwardsToNotAdvanced').prop('checked', senders == "");
|
||||
$("#addaliasSenders").val(senders);
|
||||
$('#add-alias-button').text('Update');
|
||||
$('body').animate({ scrollTop: 0 })
|
||||
is_alias_add_update = true;
|
||||
}
|
||||
|
||||
function aliases_remove(elem) {
|
||||
var row_address = $(elem).parents('tr').attr('data-address');
|
||||
show_modal_confirm(
|
||||
"Remove Alias",
|
||||
"Remove " + row_address + "?",
|
||||
"Remove",
|
||||
function() {
|
||||
api(
|
||||
"/mail/aliases/remove",
|
||||
"POST",
|
||||
{
|
||||
address: row_address
|
||||
},
|
||||
function(r) {
|
||||
// Responses are multiple lines of pre-formatted text.
|
||||
show_modal_error("Remove Alias", $("<pre/>").text(r));
|
||||
show_aliases();
|
||||
});
|
||||
});
|
||||
}
|
||||
function aliases_remove(elem) {
|
||||
var row_address = $(elem).parents('tr').attr('data-address');
|
||||
show_modal_confirm(
|
||||
"Remove Alias",
|
||||
"Remove " + row_address + "?",
|
||||
"Remove",
|
||||
function () {
|
||||
api(
|
||||
"/mail/aliases/remove",
|
||||
"POST",
|
||||
{
|
||||
address: row_address
|
||||
},
|
||||
function (r) {
|
||||
// Responses are multiple lines of pre-formatted text.
|
||||
show_modal_error("Remove Alias", $("<pre/>").text(r));
|
||||
show_aliases();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function scroll_top() {
|
||||
$('html, body').animate({
|
||||
scrollTop: $("#panel_aliases").offset().top
|
||||
}, 1000);
|
||||
}
|
||||
function scroll_top() {
|
||||
$('html, body').animate({
|
||||
scrollTop: $("#panel_aliases").offset().top
|
||||
}, 1000);
|
||||
}
|
||||
</script>
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
<style>
|
||||
#custom-dns-current td.long {
|
||||
word-break: break-all;
|
||||
}
|
||||
#custom-dns-current td.long {
|
||||
word-break: break-all;
|
||||
}
|
||||
</style>
|
||||
|
||||
<h2>Custom DNS</h2>
|
||||
|
@ -12,93 +12,123 @@
|
|||
|
||||
<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>
|
||||
<input type="text" class="form-control" id="customdnsQname" placeholder="subdomain">
|
||||
<label class="input-group-text">.</label>
|
||||
<select id="customdnsZone" class="form-select"></select>
|
||||
</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 "letsencrypt.org")">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>
|
||||
</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>
|
||||
<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">
|
||||
</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>
|
||||
<div class="col-lg-10 col-xl-7 mb-3">
|
||||
<div class="input-group">
|
||||
<label class="input-group-text">Name</label>
|
||||
<input type="text" class="form-control" id="customdnsQname" placeholder="subdomain">
|
||||
<label class="input-group-text">.</label>
|
||||
<select id="customdnsZone" class="form-select"></select>
|
||||
</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 "letsencrypt.org")">
|
||||
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>
|
||||
</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>
|
||||
<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">
|
||||
</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>
|
||||
<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>
|
||||
<table id="custom-dns-current" class="table col-12" style="display: none; margin-top: 0;">
|
||||
<caption></caption>
|
||||
<thead>
|
||||
<th>Domain Name</th>
|
||||
<th>Record Type</th>
|
||||
<th>Value</th>
|
||||
<th>TTL</th>
|
||||
<th></th>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr><td colspan="5">Loading...</td></tr>
|
||||
</tbody>
|
||||
<caption></caption>
|
||||
<thead>
|
||||
<th>Domain Name</th>
|
||||
<th>Record Type</th>
|
||||
<th>Value</th>
|
||||
<th>TTL</th>
|
||||
<th></th>
|
||||
</thead>
|
||||
<tbody>
|
||||
<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 “slave”) 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 “slave”) 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>
|
||||
<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>.
|
||||
</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.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<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>
|
||||
<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>.
|
||||
</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.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn btn-primary">Update</button>
|
||||
<button type="submit" class="btn btn-primary">Update</button>
|
||||
</form>
|
||||
|
||||
|
||||
<h3>Custom DNS API</h3>
|
||||
|
||||
<p>Use your box’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’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>
|
||||
|
||||
|
@ -109,31 +139,83 @@
|
|||
<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>
|
||||
<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>
|
||||
</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’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 — don’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’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>
|
||||
<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’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 — don’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’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
|
||||
|
@ -155,138 +237,138 @@ curl -X DELETE -d "some text here" https://{{hostname}}/admin/dns/custom/foo.myd
|
|||
</pre>
|
||||
|
||||
<script>
|
||||
function show_custom_dns() {
|
||||
api(
|
||||
"/dns/secondary-nameserver",
|
||||
"GET",
|
||||
{ },
|
||||
function(data) {
|
||||
$('#secondarydnsHostname').val(data.hostnames.join(' '));
|
||||
$('#secondarydns-clear-instructions').toggle(data.hostnames.length > 0);
|
||||
});
|
||||
function show_custom_dns() {
|
||||
api(
|
||||
"/dns/secondary-nameserver",
|
||||
"GET",
|
||||
{},
|
||||
function (data) {
|
||||
$('#secondarydnsHostname').val(data.hostnames.join(' '));
|
||||
$('#secondarydns-clear-instructions').toggle(data.hostnames.length > 0);
|
||||
});
|
||||
|
||||
api(
|
||||
"/dns/zones",
|
||||
"GET",
|
||||
{ },
|
||||
function(data) {
|
||||
$('#customdnsZone').text('');
|
||||
for (var i = 0; i < data.length; i++) {
|
||||
$('#customdnsZone').append($('<option/>').text(data[i]));
|
||||
}
|
||||
});
|
||||
api(
|
||||
"/dns/zones",
|
||||
"GET",
|
||||
{},
|
||||
function (data) {
|
||||
$('#customdnsZone').text('');
|
||||
for (var i = 0; i < data.length; i++) {
|
||||
$('#customdnsZone').append($('<option/>').text(data[i]));
|
||||
}
|
||||
});
|
||||
|
||||
show_current_custom_dns();
|
||||
show_customdns_rtype_hint();
|
||||
}
|
||||
show_current_custom_dns();
|
||||
show_customdns_rtype_hint();
|
||||
}
|
||||
|
||||
function show_current_custom_dns() {
|
||||
api(
|
||||
"/dns/custom",
|
||||
"GET",
|
||||
{ },
|
||||
function(data) {
|
||||
if (data.length > 0)
|
||||
$('#custom-dns-current').fadeIn();
|
||||
else
|
||||
$('#custom-dns-current').fadeOut();
|
||||
window.miab_custom_dns_data = data;
|
||||
show_current_custom_dns_update_after_sort();
|
||||
});
|
||||
}
|
||||
function show_current_custom_dns() {
|
||||
api(
|
||||
"/dns/custom",
|
||||
"GET",
|
||||
{},
|
||||
function (data) {
|
||||
if (data.length > 0)
|
||||
$('#custom-dns-current').fadeIn();
|
||||
else
|
||||
$('#custom-dns-current').fadeOut();
|
||||
window.miab_custom_dns_data = data;
|
||||
show_current_custom_dns_update_after_sort();
|
||||
});
|
||||
}
|
||||
|
||||
function show_current_custom_dns_update_after_sort() {
|
||||
var data = window.miab_custom_dns_data;
|
||||
var sort_key = window.miab_custom_dns_data_sort_order || "qname";
|
||||
function show_current_custom_dns_update_after_sort() {
|
||||
var data = window.miab_custom_dns_data;
|
||||
var sort_key = window.miab_custom_dns_data_sort_order || "qname";
|
||||
|
||||
data.sort(function(a, b) { return a["sort-order"][sort_key] - b["sort-order"][sort_key] });
|
||||
data.sort(function (a, b) { return a["sort-order"][sort_key] - b["sort-order"][sort_key] });
|
||||
|
||||
var tbody = $('#custom-dns-current').find("tbody");
|
||||
tbody.text('');
|
||||
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>");
|
||||
r.find("th").text(data[i].zone);
|
||||
tbody.append(r);
|
||||
last_zone = data[i].zone;
|
||||
}
|
||||
var tbody = $('#custom-dns-current').find("tbody");
|
||||
tbody.text('');
|
||||
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>");
|
||||
r.find("th").text(data[i].zone);
|
||||
tbody.append(r);
|
||||
last_zone = data[i].zone;
|
||||
}
|
||||
|
||||
var tr = $("<tr/>");
|
||||
tbody.append(tr);
|
||||
tr.attr('data-qname', data[i].qname);
|
||||
tr.attr('data-rtype', data[i].rtype);
|
||||
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));
|
||||
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>'));
|
||||
}
|
||||
}
|
||||
var tr = $("<tr/>");
|
||||
tbody.append(tr);
|
||||
tr.attr('data-qname', data[i].qname);
|
||||
tr.attr('data-rtype', data[i].rtype);
|
||||
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));
|
||||
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>'));
|
||||
}
|
||||
}
|
||||
|
||||
function delete_custom_dns_record(elem) {
|
||||
var qname = $(elem).parents('tr').attr('data-qname');
|
||||
var rtype = $(elem).parents('tr').attr('data-rtype');
|
||||
var value = $(elem).parents('tr').attr('data-value');
|
||||
do_set_custom_dns(qname, rtype, value, "DELETE");
|
||||
return false;
|
||||
}
|
||||
function delete_custom_dns_record(elem) {
|
||||
var qname = $(elem).parents('tr').attr('data-qname');
|
||||
var rtype = $(elem).parents('tr').attr('data-rtype');
|
||||
var value = $(elem).parents('tr').attr('data-value');
|
||||
do_set_custom_dns(qname, rtype, value, "DELETE");
|
||||
return false;
|
||||
}
|
||||
|
||||
function do_set_secondary_dns() {
|
||||
api(
|
||||
"/dns/secondary-nameserver",
|
||||
"POST",
|
||||
{
|
||||
hostnames: $('#secondarydnsHostname').val()
|
||||
},
|
||||
function(data) {
|
||||
if (data == "") return; // nothing updated
|
||||
show_modal_error("Secondary DNS", $("<pre/>").text(data));
|
||||
$('#secondarydns-clear-instructions').slideDown();
|
||||
},
|
||||
function(err) {
|
||||
show_modal_error("Secondary DNS", $("<pre/>").text(err));
|
||||
});
|
||||
}
|
||||
function do_set_secondary_dns() {
|
||||
api(
|
||||
"/dns/secondary-nameserver",
|
||||
"POST",
|
||||
{
|
||||
hostnames: $('#secondarydnsHostname').val()
|
||||
},
|
||||
function (data) {
|
||||
if (data == "") return; // nothing updated
|
||||
show_modal_error("Secondary DNS", $("<pre/>").text(data));
|
||||
$('#secondarydns-clear-instructions').slideDown();
|
||||
},
|
||||
function (err) {
|
||||
show_modal_error("Secondary DNS", $("<pre/>").text(err));
|
||||
});
|
||||
}
|
||||
|
||||
function do_set_custom_dns(qname, rtype, value, method) {
|
||||
if (!qname) {
|
||||
if ($('#customdnsQname').val() != '')
|
||||
qname = $('#customdnsQname').val() + '.' + $('#customdnsZone').val();
|
||||
else
|
||||
qname = $('#customdnsZone').val();
|
||||
rtype = $('#customdnsType').val();
|
||||
value = {
|
||||
value: $('#customdnsValue').val(),
|
||||
ttl: $('#customdnsTtl').val()
|
||||
};
|
||||
method = 'POST';
|
||||
} else {
|
||||
value = {
|
||||
value: value
|
||||
}
|
||||
}
|
||||
function do_set_custom_dns(qname, rtype, value, method) {
|
||||
if (!qname) {
|
||||
if ($('#customdnsQname').val() != '')
|
||||
qname = $('#customdnsQname').val() + '.' + $('#customdnsZone').val();
|
||||
else
|
||||
qname = $('#customdnsZone').val();
|
||||
rtype = $('#customdnsType').val();
|
||||
value = {
|
||||
value: $('#customdnsValue').val(),
|
||||
ttl: $('#customdnsTtl').val()
|
||||
};
|
||||
method = 'POST';
|
||||
} else {
|
||||
value = {
|
||||
value: value
|
||||
}
|
||||
}
|
||||
|
||||
api(
|
||||
"/dns/custom/" + qname + "/" + rtype,
|
||||
method,
|
||||
value,
|
||||
function(data) {
|
||||
if (data == "") return; // nothing updated
|
||||
show_modal_error("Custom DNS", $("<pre/>").text(data));
|
||||
show_current_custom_dns();
|
||||
},
|
||||
function(err) {
|
||||
show_modal_error("Custom DNS (Error)", $("<pre/>").text(err));
|
||||
});
|
||||
}
|
||||
api(
|
||||
"/dns/custom/" + qname + "/" + rtype,
|
||||
method,
|
||||
value,
|
||||
function (data) {
|
||||
if (data == "") return; // nothing updated
|
||||
show_modal_error("Custom DNS", $("<pre/>").text(data));
|
||||
show_current_custom_dns();
|
||||
},
|
||||
function (err) {
|
||||
show_modal_error("Custom DNS (Error)", $("<pre/>").text(err));
|
||||
});
|
||||
}
|
||||
|
||||
function show_customdns_rtype_hint() {
|
||||
$('#customdnsTypeHint').text($("#customdnsType").find('option:selected').attr('data-hint'));
|
||||
}
|
||||
function show_customdns_rtype_hint() {
|
||||
$('#customdnsTypeHint').text($("#customdnsType").find('option:selected').attr('data-hint'));
|
||||
}
|
||||
</script>
|
||||
|
|
|
@ -1,57 +1,66 @@
|
|||
<style>
|
||||
#external_dns_settings .domain-header {
|
||||
margin-top: 0.5em;
|
||||
margin-bottom: 0.5em;
|
||||
}
|
||||
#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 {
|
||||
padding-top: .5em;
|
||||
padding-bottom: .75em;
|
||||
font-style: italic;
|
||||
color: #777;
|
||||
}
|
||||
#external_dns_settings .domain-header {
|
||||
margin-top: 0.5em;
|
||||
margin-bottom: 0.5em;
|
||||
}
|
||||
|
||||
#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 {
|
||||
padding-top: .5em;
|
||||
padding-bottom: .75em;
|
||||
font-style: italic;
|
||||
color: #777;
|
||||
}
|
||||
</style>
|
||||
|
||||
<h2>External DNS</h2>
|
||||
|
||||
<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 — such as in the DNS control panel provided by your domain name registrar or virtual cloud provider — by copying the DNS zone information shown in the table below into your external DNS server’s control panel.</p>
|
||||
<p>Although your box is configured to serve its own DNS, it is possible to host your DNS elsewhere — such as in
|
||||
the DNS control panel provided by your domain name registrar or virtual cloud provider — by copying the DNS
|
||||
zone information shown in the table below into your external DNS server’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>
|
||||
</div>
|
||||
<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>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn btn-primary">Download</button>
|
||||
<button type="submit" class="btn btn-primary">Download</button>
|
||||
</form>
|
||||
|
||||
<h3>Records</h3>
|
||||
|
||||
<table id="external_dns_settings" class="table">
|
||||
<caption></caption>
|
||||
<caption></caption>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>QName</th>
|
||||
|
@ -64,59 +73,59 @@
|
|||
</table>
|
||||
|
||||
<script>
|
||||
function show_external_dns() {
|
||||
api(
|
||||
"/dns/zones",
|
||||
"GET",
|
||||
{ },
|
||||
function(data) {
|
||||
var zones = $('#downloadZonefile');
|
||||
zones.text('');
|
||||
for (var j = 0; j < data.length; j++) {
|
||||
zones.append($('<option/>').text(data[j]));
|
||||
}
|
||||
});
|
||||
function show_external_dns() {
|
||||
api(
|
||||
"/dns/zones",
|
||||
"GET",
|
||||
{},
|
||||
function (data) {
|
||||
var zones = $('#downloadZonefile');
|
||||
zones.text('');
|
||||
for (var j = 0; j < data.length; j++) {
|
||||
zones.append($('<option/>').text(data[j]));
|
||||
}
|
||||
});
|
||||
|
||||
$('#external_dns_settings tbody').html("<tr><td colspan='2' class='text-muted'>Loading...</td></tr>")
|
||||
api(
|
||||
"/dns/dump",
|
||||
"GET",
|
||||
{ },
|
||||
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]);
|
||||
$('#external_dns_settings tbody').append(h);
|
||||
$('#external_dns_settings tbody').html("<tr><td colspan='2' class='text-muted'>Loading...</td></tr>")
|
||||
api(
|
||||
"/dns/dump",
|
||||
"GET",
|
||||
{},
|
||||
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]);
|
||||
$('#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>");
|
||||
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 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>");
|
||||
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);
|
||||
$('#external_dns_settings tbody').append(n);
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
var n = $("<tr class='explanation'><td colspan='3'/><small/></tr>");
|
||||
n.find('td small').text(r[i].explanation);
|
||||
$('#external_dns_settings tbody').append(n);
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function do_download_zonefile() {
|
||||
var zone = $('#downloadZonefile').val();
|
||||
function do_download_zonefile() {
|
||||
var zone = $('#downloadZonefile').val();
|
||||
|
||||
api(
|
||||
"/dns/zonefile/"+ zone,
|
||||
"GET",
|
||||
{},
|
||||
function(data) {
|
||||
show_modal_error("Download Zonefile", $("<pre/>").text(data));
|
||||
},
|
||||
function(err) {
|
||||
show_modal_error("Download Zonefile (Error)", $("<pre/>").text(err));
|
||||
});
|
||||
}
|
||||
api(
|
||||
"/dns/zonefile/" + zone,
|
||||
"GET",
|
||||
{},
|
||||
function (data) {
|
||||
show_modal_error("Download Zonefile", $("<pre/>").text(data));
|
||||
},
|
||||
function (err) {
|
||||
show_modal_error("Download Zonefile (Error)", $("<pre/>").text(err));
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
|
File diff suppressed because it is too large
Load diff
|
@ -1,198 +1,201 @@
|
|||
<style>
|
||||
.title {
|
||||
margin: 0.5em;
|
||||
text-align: center;
|
||||
}
|
||||
.title {
|
||||
margin: 0.5em;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
margin: 1em;
|
||||
text-align: center;
|
||||
}
|
||||
.subtitle {
|
||||
margin: 1em;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.login {
|
||||
margin: 0 auto;
|
||||
max-width: 32em;
|
||||
}
|
||||
.login {
|
||||
margin: 0 auto;
|
||||
max-width: 32em;
|
||||
}
|
||||
|
||||
.login #loginOtp {
|
||||
display: none;
|
||||
}
|
||||
.login #loginOtp {
|
||||
display: none;
|
||||
}
|
||||
|
||||
#loginForm.is-twofactor #loginOtp {
|
||||
display: block
|
||||
}
|
||||
#loginForm.is-twofactor #loginOtp {
|
||||
display: block
|
||||
}
|
||||
</style>
|
||||
|
||||
<h1 class="title">{{hostname}}</h1>
|
||||
|
||||
{% if no_users_exist or no_admins_exist %}
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<hr>
|
||||
{% 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>
|
||||
<pre>cd mailinabox
|
||||
<div class="col-12">
|
||||
<hr>
|
||||
{% 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>
|
||||
<pre>cd mailinabox
|
||||
sudo management/cli.py user add me@{{hostname}}
|
||||
sudo management/cli.py user make-admin me@{{hostname}}</pre>
|
||||
{% else %}
|
||||
<p class="text-danger">There are no administrative 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>
|
||||
<pre>cd mailinabox
|
||||
{% else %}
|
||||
<p class="text-danger">There are no administrative 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>
|
||||
<pre>cd mailinabox
|
||||
sudo management/cli.py user make-admin me@{{hostname}}</pre>
|
||||
{% endif %}
|
||||
<hr>
|
||||
</div>
|
||||
{% endif %}
|
||||
<hr>
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<p class="subtitle">Log in here for your Mail-in-a-Box control panel.</p>
|
||||
|
||||
<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>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<div class="container-fluid">
|
||||
<button type="submit" class="btn btn-primary col-12">Sign in</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
<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>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<div class="container-fluid">
|
||||
<button type="submit" class="btn btn-primary col-12">Sign in</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function do_login() {
|
||||
if ($('#loginEmail').val() == "") {
|
||||
show_modal_error("Login Failed", "Enter your email address.", function() {
|
||||
$('#loginEmail').focus();
|
||||
});
|
||||
return false;
|
||||
}
|
||||
function do_login() {
|
||||
if ($('#loginEmail').val() == "") {
|
||||
show_modal_error("Login Failed", "Enter your email address.", function () {
|
||||
$('#loginEmail').focus();
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($('#loginPassword').val() == "") {
|
||||
show_modal_error("Login Failed", "Enter your email password.", function() {
|
||||
$('#loginPassword').focus();
|
||||
});
|
||||
return false;
|
||||
}
|
||||
if ($('#loginPassword').val() == "") {
|
||||
show_modal_error("Login Failed", "Enter your email password.", function () {
|
||||
$('#loginPassword').focus();
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
// Exchange the email address & password for an API key.
|
||||
api_credentials = { username: $('#loginEmail').val(), session_key: $('#loginPassword').val() }
|
||||
// Exchange the email address & password for an API key.
|
||||
api_credentials = { username: $('#loginEmail').val(), session_key: $('#loginPassword').val() }
|
||||
|
||||
api(
|
||||
"/login",
|
||||
"POST",
|
||||
{},
|
||||
function(response) {
|
||||
// This API call always succeeds. It returns a JSON object indicating
|
||||
// whether the request was authenticated or not.
|
||||
if (response.status != 'ok') {
|
||||
if (response.status === 'missing-totp-token' || (response.status === 'invalid' && response.reason == 'invalid-totp-token')) {
|
||||
$('#loginForm').addClass('is-twofactor');
|
||||
if (response.reason === "invalid-totp-token") {
|
||||
show_modal_error("Login Failed", "Incorrect two factor authentication token.");
|
||||
} else {
|
||||
setTimeout(() => {
|
||||
$('#loginOtpInput').focus();
|
||||
});
|
||||
}
|
||||
} else {
|
||||
$('#loginForm').removeClass('is-twofactor');
|
||||
api(
|
||||
"/login",
|
||||
"POST",
|
||||
{},
|
||||
function (response) {
|
||||
// This API call always succeeds. It returns a JSON object indicating
|
||||
// whether the request was authenticated or not.
|
||||
if (response.status != 'ok') {
|
||||
if (response.status === 'missing-totp-token' || (response.status === 'invalid' && response.reason == 'invalid-totp-token')) {
|
||||
$('#loginForm').addClass('is-twofactor');
|
||||
if (response.reason === "invalid-totp-token") {
|
||||
show_modal_error("Login Failed", "Incorrect two factor authentication token.");
|
||||
} else {
|
||||
setTimeout(() => {
|
||||
$('#loginOtpInput').focus();
|
||||
});
|
||||
}
|
||||
} else {
|
||||
$('#loginForm').removeClass('is-twofactor');
|
||||
|
||||
// Show why the login failed.
|
||||
show_modal_error("Login Failed", response.reason)
|
||||
// Show why the login failed.
|
||||
show_modal_error("Login Failed", response.reason)
|
||||
|
||||
// Reset any saved credentials.
|
||||
do_logout();
|
||||
}
|
||||
} else if (!("api_key" in response)) {
|
||||
// Login succeeded but user might not be authorized!
|
||||
show_modal_error("Login Failed", "You are not an administrator on this system.")
|
||||
// Reset any saved credentials.
|
||||
do_logout();
|
||||
}
|
||||
} else if (!("api_key" in response)) {
|
||||
// Login succeeded but user might not be authorized!
|
||||
show_modal_error("Login Failed", "You are not an administrator on this system.")
|
||||
|
||||
// Reset any saved credentials.
|
||||
do_logout();
|
||||
// Reset any saved credentials.
|
||||
do_logout();
|
||||
|
||||
} else {
|
||||
// Login succeeded.
|
||||
} else {
|
||||
// Login succeeded.
|
||||
|
||||
// Save the new credentials.
|
||||
api_credentials = { username: response.email,
|
||||
session_key: response.api_key,
|
||||
privileges: response.privileges };
|
||||
// Save the new credentials.
|
||||
api_credentials = {
|
||||
username: response.email,
|
||||
session_key: response.api_key,
|
||||
privileges: response.privileges
|
||||
};
|
||||
|
||||
// Try to wipe the username/password information.
|
||||
$('#loginEmail').val('');
|
||||
$('#loginPassword').val('');
|
||||
$('#loginOtpInput').val('');
|
||||
$('#loginForm').removeClass('is-twofactor');
|
||||
// Try to wipe the username/password information.
|
||||
$('#loginEmail').val('');
|
||||
$('#loginPassword').val('');
|
||||
$('#loginOtpInput').val('');
|
||||
$('#loginForm').removeClass('is-twofactor');
|
||||
|
||||
// Remember the credentials.
|
||||
if (typeof localStorage != 'undefined' && typeof sessionStorage != 'undefined') {
|
||||
if ($('#loginRemember').val()) {
|
||||
localStorage.setItem("miab-cp-credentials", JSON.stringify(api_credentials));
|
||||
sessionStorage.removeItem("miab-cp-credentials");
|
||||
} else {
|
||||
localStorage.removeItem("miab-cp-credentials");
|
||||
sessionStorage.setItem("miab-cp-credentials", JSON.stringify(api_credentials));
|
||||
}
|
||||
}
|
||||
// Remember the credentials.
|
||||
if (typeof localStorage != 'undefined' && typeof sessionStorage != 'undefined') {
|
||||
if ($('#loginRemember').val()) {
|
||||
localStorage.setItem("miab-cp-credentials", JSON.stringify(api_credentials));
|
||||
sessionStorage.removeItem("miab-cp-credentials");
|
||||
} else {
|
||||
localStorage.removeItem("miab-cp-credentials");
|
||||
sessionStorage.setItem("miab-cp-credentials", JSON.stringify(api_credentials));
|
||||
}
|
||||
}
|
||||
|
||||
// Toggle menus.
|
||||
show_hide_menus();
|
||||
// Toggle menus.
|
||||
show_hide_menus();
|
||||
|
||||
// Open the next panel the user wants to go to. Do this after the XHR response
|
||||
// is over so that we don't start a new XHR request while this one is finishing,
|
||||
// which confuses the loading indicator.
|
||||
setTimeout(function() { show_panel(!switch_back_to_panel || switch_back_to_panel == "login" ? 'welcome' : switch_back_to_panel) }, 300);
|
||||
}
|
||||
},
|
||||
undefined,
|
||||
{
|
||||
'x-auth-token': $('#loginOtpInput').val()
|
||||
});
|
||||
}
|
||||
// Open the next panel the user wants to go to. Do this after the XHR response
|
||||
// is over so that we don't start a new XHR request while this one is finishing,
|
||||
// which confuses the loading indicator.
|
||||
setTimeout(function () { show_panel(!switch_back_to_panel || switch_back_to_panel == "login" ? 'welcome' : switch_back_to_panel) }, 300);
|
||||
}
|
||||
},
|
||||
undefined,
|
||||
{
|
||||
'x-auth-token': $('#loginOtpInput').val()
|
||||
});
|
||||
}
|
||||
|
||||
function show_login() {
|
||||
$('#loginForm').removeClass('is-twofactor');
|
||||
$('#loginOtpInput').val('');
|
||||
$('#loginEmail,#loginPassword').each(function() {
|
||||
var input = $(this);
|
||||
if (!$.trim(input.val())) {
|
||||
input.focus();
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
function show_login() {
|
||||
$('#loginForm').removeClass('is-twofactor');
|
||||
$('#loginOtpInput').val('');
|
||||
$('#loginEmail,#loginPassword').each(function () {
|
||||
var input = $(this);
|
||||
if (!$.trim(input.val())) {
|
||||
input.focus();
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function show_hide_menus() {
|
||||
var is_logged_in = (api_credentials != null);
|
||||
var privs = api_credentials ? api_credentials.privileges : [];
|
||||
$('.if-logged-in').toggle(is_logged_in);
|
||||
$('.if-logged-in-admin, .if-logged-in-not-admin').toggle(false);
|
||||
if (is_logged_in) {
|
||||
$('.if-logged-in-not-admin').toggle(true);
|
||||
privs.forEach(function(priv) {
|
||||
$('.if-logged-in-' + priv).toggle(true);
|
||||
$('.if-logged-in-not-' + priv).toggle(false);
|
||||
});
|
||||
}
|
||||
$('.if-not-logged-in').toggle(!is_logged_in);
|
||||
}
|
||||
function show_hide_menus() {
|
||||
var is_logged_in = (api_credentials != null);
|
||||
var privs = api_credentials ? api_credentials.privileges : [];
|
||||
$('.if-logged-in').toggle(is_logged_in);
|
||||
$('.if-logged-in-admin, .if-logged-in-not-admin').toggle(false);
|
||||
if (is_logged_in) {
|
||||
$('.if-logged-in-not-admin').toggle(true);
|
||||
privs.forEach(function (priv) {
|
||||
$('.if-logged-in-' + priv).toggle(true);
|
||||
$('.if-logged-in-not-' + priv).toggle(false);
|
||||
});
|
||||
}
|
||||
$('.if-not-logged-in').toggle(!is_logged_in);
|
||||
}
|
||||
</script>
|
||||
|
|
|
@ -1,4 +1,9 @@
|
|||
<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>
|
||||
|
@ -8,67 +13,121 @@
|
|||
<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>
|
||||
|
||||
|
||||
<h3>Mobile/desktop apps</h3>
|
||||
|
||||
<h4>Automatic configuration</h4>
|
||||
<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>
|
||||
|
||||
<h4>Manual 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>Use the following settings when you set up your email on your phone, desktop, or other device:</p>
|
||||
<h4>Manual configuration</h4>
|
||||
|
||||
<table class="table">
|
||||
<caption></caption>
|
||||
<thead>
|
||||
<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>
|
||||
</table>
|
||||
<p>Use the following settings when you set up your email on your phone, desktop, or other device:</p>
|
||||
|
||||
<p>In addition to setting up your email, you’ll also need to set up <a href="#sync_guide" onclick="return show_panel(this);">contacts and calendar synchronization</a> separately.</p>
|
||||
<table class="table">
|
||||
<caption></caption>
|
||||
<thead>
|
||||
<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>
|
||||
</table>
|
||||
|
||||
<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>In addition to setting up your email, you’ll also need to set up <a href="#sync_guide"
|
||||
onclick="return show_panel(this);">contacts and calendar synchronization</a> separately.</p>
|
||||
|
||||
<h4>Exchange/ActiveSync settings</h4>
|
||||
<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>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’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>
|
||||
<h4>Exchange/ActiveSync settings</h4>
|
||||
|
||||
<table class="table">
|
||||
<tr><th>Server</th> <td>{{hostname}}</td></tr>
|
||||
<tr><th>Options</th> <td>Secure Connection</td></tr>
|
||||
</table>
|
||||
<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’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>Your device should also provide a contacts list and calendar that syncs to this box when you use this method.</p>
|
||||
<table class="table">
|
||||
<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>
|
||||
</div>
|
||||
|
||||
<div class="col-sm-5">
|
||||
<div class="panel panel-default">
|
||||
<div class="panel-heading">
|
||||
<h3>Other information about mail on your box</h3>
|
||||
</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’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>
|
||||
<div class="panel panel-default">
|
||||
<div class="panel-heading">
|
||||
<h3>Other information about mail on your box</h3>
|
||||
</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’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’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>+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’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>
|
||||
</div>
|
||||
</div>
|
||||
<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>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
@ -1,232 +1,240 @@
|
|||
<style>
|
||||
.twofactor #totp-setup,
|
||||
.twofactor #disable-2fa,
|
||||
.twofactor #output-2fa {
|
||||
display: none;
|
||||
}
|
||||
.twofactor #totp-setup,
|
||||
.twofactor #disable-2fa,
|
||||
.twofactor #output-2fa {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.twofactor.loaded .loading-indicator {
|
||||
display: none;
|
||||
}
|
||||
.twofactor.loaded .loading-indicator {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.twofactor.disabled #disable-2fa,
|
||||
.twofactor.enabled #totp-setup {
|
||||
display: none;
|
||||
}
|
||||
.twofactor.disabled #disable-2fa,
|
||||
.twofactor.enabled #totp-setup {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.twofactor.disabled #totp-setup,
|
||||
.twofactor.enabled #disable-2fa {
|
||||
display: block;
|
||||
}
|
||||
.twofactor.disabled #totp-setup,
|
||||
.twofactor.enabled #disable-2fa {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.twofactor #totp-setup-qr img {
|
||||
display: block;
|
||||
width: 256px;
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
}
|
||||
.twofactor #totp-setup-qr img {
|
||||
display: block;
|
||||
width: 256px;
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
.twofactor #output-2fa.visible {
|
||||
display: block;
|
||||
}
|
||||
.twofactor #output-2fa.visible {
|
||||
display: block;
|
||||
}
|
||||
</style>
|
||||
|
||||
<h2>Two-Factor Authentication</h2>
|
||||
|
||||
<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>
|
||||
authenticator app (usually on your phone) when you log into this control panel.</p>
|
||||
|
||||
<div class="card mb-4">
|
||||
<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
|
||||
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@,
|
||||
webmaster@, abuse@), extra care should be taken to protect the account. <strong>Always use a strong password,
|
||||
and ensure every administrator account for this control panel does the same.</strong>
|
||||
</div>
|
||||
<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
|
||||
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@,
|
||||
webmaster@, abuse@), extra care should be taken to protect the account. <strong>Always use a strong password,
|
||||
and ensure every administrator account for this control panel does the same.</strong>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="twofactor">
|
||||
<div class="loading-indicator">Loading...</div>
|
||||
<div class="loading-indicator">Loading...</div>
|
||||
|
||||
<form id="totp-setup">
|
||||
<h3>Setup Instructions</h3>
|
||||
<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
|
||||
other two-factor authentication app</a> that supports TOTP.</p>
|
||||
<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
|
||||
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="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="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="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>
|
||||
</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>
|
||||
</form>
|
||||
<div class="form-group">
|
||||
<div>
|
||||
<button id="totp-setup-submit" disabled type="submit" class="btn btn-primary">Enable Two-Factor
|
||||
Authentication</button>
|
||||
</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>
|
||||
</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>
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
|
||||
<script>
|
||||
var el = {
|
||||
disableForm: document.getElementById('disable-2fa'),
|
||||
totpSetupForm: document.getElementById('totp-setup'),
|
||||
totpSetupToken: document.getElementById('totp-setup-token'),
|
||||
totpSetupSecret: document.getElementById('totp-setup-secret'),
|
||||
totpSetupLabel: document.getElementById('totp-setup-label'),
|
||||
totpQr: document.getElementById('totp-setup-qr'),
|
||||
totpSetupSubmit: document.querySelector('#totp-setup-submit'),
|
||||
wrapper: document.querySelector('.twofactor')
|
||||
}
|
||||
var el = {
|
||||
disableForm: document.getElementById('disable-2fa'),
|
||||
totpSetupForm: document.getElementById('totp-setup'),
|
||||
totpSetupToken: document.getElementById('totp-setup-token'),
|
||||
totpSetupSecret: document.getElementById('totp-setup-secret'),
|
||||
totpSetupLabel: document.getElementById('totp-setup-label'),
|
||||
totpQr: document.getElementById('totp-setup-qr'),
|
||||
totpSetupSubmit: document.querySelector('#totp-setup-submit'),
|
||||
wrapper: document.querySelector('.twofactor')
|
||||
}
|
||||
|
||||
function update_setup_disabled(evt) {
|
||||
var val = evt.target.value.trim();
|
||||
function update_setup_disabled(evt) {
|
||||
var val = evt.target.value.trim();
|
||||
|
||||
if (
|
||||
typeof val !== 'string' ||
|
||||
typeof el.totpSetupSecret.value !== 'string' ||
|
||||
val.length !== 6 ||
|
||||
el.totpSetupSecret.value.length !== 32 ||
|
||||
!(/^\+?\d+$/.test(val))
|
||||
) {
|
||||
el.totpSetupSubmit.setAttribute('disabled', '');
|
||||
} else {
|
||||
el.totpSetupSubmit.removeAttribute('disabled');
|
||||
}
|
||||
}
|
||||
if (
|
||||
typeof val !== 'string' ||
|
||||
typeof el.totpSetupSecret.value !== 'string' ||
|
||||
val.length !== 6 ||
|
||||
el.totpSetupSecret.value.length !== 32 ||
|
||||
!(/^\+?\d+$/.test(val))
|
||||
) {
|
||||
el.totpSetupSubmit.setAttribute('disabled', '');
|
||||
} else {
|
||||
el.totpSetupSubmit.removeAttribute('disabled');
|
||||
}
|
||||
}
|
||||
|
||||
function render_totp_setup(provisioned_totp) {
|
||||
$('#twofactor-qrimg').attr("src", "data:image/png;base64," + provisioned_totp.qr_code_base64);
|
||||
|
||||
el.totpSetupSecret.val = provisioned_totp.secret;
|
||||
function render_totp_setup(provisioned_totp) {
|
||||
$('#twofactor-qrimg').attr("src", "data:image/png;base64," + provisioned_totp.qr_code_base64);
|
||||
|
||||
el.totpSetupToken.addEventListener('input', update_setup_disabled);
|
||||
el.totpSetupForm.addEventListener('submit', do_enable_totp);
|
||||
el.totpSetupSecret.val = provisioned_totp.secret;
|
||||
|
||||
el.totpSetupSecret.setAttribute('value', provisioned_totp.secret);
|
||||
el.totpSetupToken.addEventListener('input', update_setup_disabled);
|
||||
el.totpSetupForm.addEventListener('submit', do_enable_totp);
|
||||
|
||||
el.wrapper.classList.add('disabled');
|
||||
}
|
||||
el.totpSetupSecret.setAttribute('value', provisioned_totp.secret);
|
||||
|
||||
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()
|
||||
}
|
||||
}
|
||||
el.wrapper.classList.add('disabled');
|
||||
}
|
||||
|
||||
function reset_view() {
|
||||
el.wrapper.classList.remove('loaded', 'disabled', 'enabled');
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
el.disableForm.removeEventListener('submit', do_disable);
|
||||
function reset_view() {
|
||||
el.wrapper.classList.remove('loaded', 'disabled', 'enabled');
|
||||
|
||||
el.totpSetupForm.reset();
|
||||
el.totpSetupForm.removeEventListener('submit', do_enable_totp);
|
||||
el.disableForm.removeEventListener('submit', do_disable);
|
||||
|
||||
el.totpSetupSecret.setAttribute('value', '');
|
||||
el.totpSetupToken.removeEventListener('input', update_setup_disabled);
|
||||
el.totpSetupForm.reset();
|
||||
el.totpSetupForm.removeEventListener('submit', do_enable_totp);
|
||||
|
||||
el.totpSetupSubmit.setAttribute('disabled', '');
|
||||
|
||||
$('#twofactor-qrimg').attr("src", "");
|
||||
$('#totp-setup-secret').attr("value", "");
|
||||
}
|
||||
el.totpSetupSecret.setAttribute('value', '');
|
||||
el.totpSetupToken.removeEventListener('input', update_setup_disabled);
|
||||
|
||||
function show_mfa() {
|
||||
reset_view();
|
||||
el.totpSetupSubmit.setAttribute('disabled', '');
|
||||
|
||||
api(
|
||||
'/mfa/status',
|
||||
'POST',
|
||||
{},
|
||||
function(res) {
|
||||
el.wrapper.classList.add('loaded');
|
||||
$('#twofactor-qrimg').attr("src", "");
|
||||
$('#totp-setup-secret').attr("value", "");
|
||||
}
|
||||
|
||||
var has_mfa = false;
|
||||
res.enabled_mfa.forEach(function(mfa) {
|
||||
if (mfa.type == "totp") {
|
||||
render_disable(mfa);
|
||||
has_mfa = true;
|
||||
}
|
||||
});
|
||||
function show_mfa() {
|
||||
reset_view();
|
||||
|
||||
if (!has_mfa)
|
||||
render_totp_setup(res.new_mfa.totp);
|
||||
}
|
||||
);
|
||||
}
|
||||
api(
|
||||
'/mfa/status',
|
||||
'POST',
|
||||
{},
|
||||
function (res) {
|
||||
el.wrapper.classList.add('loaded');
|
||||
|
||||
function do_disable(evt) {
|
||||
evt.preventDefault();
|
||||
var has_mfa = false;
|
||||
res.enabled_mfa.forEach(function (mfa) {
|
||||
if (mfa.type == "totp") {
|
||||
render_disable(mfa);
|
||||
has_mfa = true;
|
||||
}
|
||||
});
|
||||
|
||||
api(
|
||||
'/mfa/disable',
|
||||
'POST',
|
||||
{ type: 'totp' },
|
||||
function() {
|
||||
do_logout();
|
||||
}
|
||||
);
|
||||
if (!has_mfa)
|
||||
render_totp_setup(res.new_mfa.totp);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
function do_disable(evt) {
|
||||
evt.preventDefault();
|
||||
|
||||
function do_enable_totp(evt) {
|
||||
evt.preventDefault();
|
||||
api(
|
||||
'/mfa/disable',
|
||||
'POST',
|
||||
{ type: 'totp' },
|
||||
function () {
|
||||
do_logout();
|
||||
}
|
||||
);
|
||||
|
||||
api(
|
||||
'/mfa/totp/enable',
|
||||
'POST',
|
||||
{
|
||||
token: $(el.totpSetupToken).val(),
|
||||
secret: $(el.totpSetupSecret).val(),
|
||||
label: $(el.totpSetupLabel).val()
|
||||
},
|
||||
function(res) { do_logout(); },
|
||||
function(res) { show_modal_error("Two-Factor Authentication Setup", res); }
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
function do_enable_totp(evt) {
|
||||
evt.preventDefault();
|
||||
|
||||
api(
|
||||
'/mfa/totp/enable',
|
||||
'POST',
|
||||
{
|
||||
token: $(el.totpSetupToken).val(),
|
||||
secret: $(el.totpSetupSecret).val(),
|
||||
label: $(el.totpSetupLabel).val()
|
||||
},
|
||||
function (res) { do_logout(); },
|
||||
function (res) { show_modal_error("Two-Factor Authentication Setup", res); }
|
||||
);
|
||||
|
||||
return false;
|
||||
}
|
||||
</script>
|
||||
|
|
|
@ -6,15 +6,15 @@
|
|||
<p>Opening munin in a new tab... You may need to allow pop-ups for this site.</p>
|
||||
|
||||
<script>
|
||||
function show_munin() {
|
||||
// Set the cookie.
|
||||
api(
|
||||
"/munin",
|
||||
"GET",
|
||||
{ },
|
||||
function(r) {
|
||||
// Redirect.
|
||||
window.open("/admin/munin/index.html", "_blank");
|
||||
});
|
||||
}
|
||||
function show_munin() {
|
||||
// Set the cookie.
|
||||
api(
|
||||
"/munin",
|
||||
"GET",
|
||||
{},
|
||||
function (r) {
|
||||
// Redirect.
|
||||
window.open("/admin/munin/index.html", "_blank");
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
|
|
@ -1,9 +1,9 @@
|
|||
<style>
|
||||
#pgp_keyring_config .icon {
|
||||
#pgp_keyring_config .icon {
|
||||
min-width: 2em;
|
||||
}
|
||||
|
||||
.inline {
|
||||
.inline {
|
||||
display: inline;
|
||||
}
|
||||
</style>
|
||||
|
@ -11,60 +11,60 @@
|
|||
<h2>PGP Keyring Management</h2>
|
||||
|
||||
<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;">
|
||||
<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>
|
||||
</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>
|
||||
</tr>
|
||||
<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;">
|
||||
<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>
|
||||
</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>
|
||||
</tr>
|
||||
</template>
|
||||
|
||||
<div id="pgp_keyring_config">
|
||||
<h3>Daemon's Private Key</h3>
|
||||
<table id="privatekey" class="container">
|
||||
</table>
|
||||
<h3>Daemon's Private Key</h3>
|
||||
<table id="privatekey" class="container">
|
||||
</table>
|
||||
|
||||
<h3>Imported Public Keys</h3>
|
||||
<table id="pubkeys" class="container">
|
||||
</table>
|
||||
<h3>Imported Public Keys</h3>
|
||||
<table id="pubkeys" class="container">
|
||||
</table>
|
||||
|
||||
<h3>Import Key</h3>
|
||||
<p>
|
||||
You can upload your <b>public</b> key/keychain here. Keys <b>must</b> be submitted in ASCII-armored format.
|
||||
<br>
|
||||
If you're using <code>gpg</code>, you can export your public key by following this example:
|
||||
<pre>
|
||||
<h3>Import Key</h3>
|
||||
<p>
|
||||
You can upload your <b>public</b> key/keychain here. Keys <b>must</b> be submitted in ASCII-armored format.
|
||||
<br>
|
||||
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>
|
||||
/home/you/.gnupg/pubring.kbx
|
||||
|
@ -86,201 +86,202 @@ $ <b>gpg --export --armor 52661092E5CD9EEFD7796B19E85F540C9318B69F</b>
|
|||
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-----
stuff here
-----END PGP PUBLIC KEY BLOCK-----"></textarea>
|
||||
<label for="pgp_paste_key">Paste your PGP public key here</label>
|
||||
</div>
|
||||
<button class="btn btn-primary" onclick="importkey()">Import Key</button>
|
||||
</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-----
stuff here
-----END PGP PUBLIC KEY BLOCK-----"></textarea>
|
||||
<label for="pgp_paste_key">Paste your PGP public key here</label>
|
||||
</div>
|
||||
<button class="btn btn-primary" onclick="importkey()">Import Key</button>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function pretty_fpr(fpr) {
|
||||
let pfpr = ""
|
||||
for (let n = 0; n < 2; ++n) {
|
||||
for (let i = 0; i < 5; ++i) {
|
||||
pfpr += `${fpr.substring(n * 20 + i * 4, n * 20 + (i + 1) * 4)} `
|
||||
}
|
||||
pfpr += " "
|
||||
}
|
||||
function pretty_fpr(fpr) {
|
||||
let pfpr = ""
|
||||
for (let n = 0; n < 2; ++n) {
|
||||
for (let i = 0; i < 5; ++i) {
|
||||
pfpr += `${fpr.substring(n * 20 + i * 4, n * 20 + (i + 1) * 4)} `
|
||||
}
|
||||
pfpr += " "
|
||||
}
|
||||
|
||||
return pfpr.substring(0, pfpr.length - 2)
|
||||
}
|
||||
return pfpr.substring(0, pfpr.length - 2)
|
||||
}
|
||||
|
||||
function key_html(key, darken_bg, daemon) {
|
||||
let keyrep = $("#pgpkey-template").html()
|
||||
console.log(keyrep)
|
||||
keyrep = $(keyrep)
|
||||
keyrep.attr("id", key.master_fpr)
|
||||
function key_html(key, darken_bg, daemon) {
|
||||
let keyrep = $("#pgpkey-template").html()
|
||||
console.log(keyrep)
|
||||
keyrep = $(keyrep)
|
||||
keyrep.attr("id", key.master_fpr)
|
||||
|
||||
// Main key config
|
||||
if (darken_bg) {
|
||||
keyrep.addClass("bg-light")
|
||||
}
|
||||
// Main key config
|
||||
if (darken_bg) {
|
||||
keyrep.addClass("bg-light")
|
||||
}
|
||||
|
||||
let rev = keyrep.find("#isrevoked")
|
||||
let rev = keyrep.find("#isrevoked")
|
||||
|
||||
if (key.revoked) {
|
||||
rev.text("This key was revoked by it's owner.")
|
||||
rev.addClass(".status-error")
|
||||
} else {
|
||||
rev.text("Key is not revoked.")
|
||||
}
|
||||
if (key.revoked) {
|
||||
rev.text("This key was revoked by it's owner.")
|
||||
rev.addClass(".status-error")
|
||||
} else {
|
||||
rev.text("Key is not revoked.")
|
||||
}
|
||||
|
||||
let uids = keyrep.find("#uids")
|
||||
let uidtemplate = $(uids.html())
|
||||
uids.find("#uid-template").remove()
|
||||
if (daemon) {
|
||||
uidtemplate.find(".icon").addClass("fa-robot")
|
||||
} else {
|
||||
uidtemplate.find(".icon").addClass("fa-user")
|
||||
}
|
||||
let uids = keyrep.find("#uids")
|
||||
let uidtemplate = $(uids.html())
|
||||
uids.find("#uid-template").remove()
|
||||
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)
|
||||
});
|
||||
key.ids.forEach(id => {
|
||||
let thisuid = uidtemplate.clone()
|
||||
thisuid.attr("id", "")
|
||||
thisuid.find("#id").text(id)
|
||||
thisuid.appendTo(uids)
|
||||
});
|
||||
|
||||
// Subkeys
|
||||
const keyflags = ["sign", "cert", "encr", "auth"]
|
||||
let subkeys = keyrep.find("#subkeys")
|
||||
let subkeytemplate = subkeys.html()
|
||||
keyrep.find("#subkey-template").remove()
|
||||
key.subkeys.forEach(skey => {
|
||||
let skeyrep = $(subkeytemplate)
|
||||
skeyrep.attr("id", `sub${skey.fpr}`)
|
||||
|
||||
let statusclass
|
||||
let expiration = skeyrep.find("#expiration")
|
||||
let exptxt = expiration.find(".status-text")
|
||||
// Subkeys
|
||||
const keyflags = ["sign", "cert", "encr", "auth"]
|
||||
let subkeys = keyrep.find("#subkeys")
|
||||
let subkeytemplate = subkeys.html()
|
||||
keyrep.find("#subkey-template").remove()
|
||||
key.subkeys.forEach(skey => {
|
||||
let skeyrep = $(subkeytemplate)
|
||||
skeyrep.attr("id", `sub${skey.fpr}`)
|
||||
|
||||
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")
|
||||
}
|
||||
let statusclass
|
||||
let expiration = skeyrep.find("#expiration")
|
||||
let exptxt = expiration.find(".status-text")
|
||||
|
||||
expiration.addClass(statusclass)
|
||||
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")
|
||||
}
|
||||
|
||||
// Master key?
|
||||
if (skey.master) {
|
||||
skeyrep.find("#ismaster").addClass("fas fa-key")
|
||||
}
|
||||
expiration.addClass(statusclass)
|
||||
|
||||
// Usage flags
|
||||
keyflags.forEach(flag => {
|
||||
skeyrep.find(`#${flag}`).addClass(skey[flag] ? statusclass : "status-na")
|
||||
});
|
||||
// Master key?
|
||||
if (skey.master) {
|
||||
skeyrep.find("#ismaster").addClass("fas fa-key")
|
||||
}
|
||||
|
||||
// Algorithm and fingerprint
|
||||
let algo = skeyrep.find("#algo")
|
||||
algo.addClass(statusclass)
|
||||
algo.find(".status-text").html(`${skey.algorithm}, ${skey.bits} bits`)
|
||||
// Usage flags
|
||||
keyflags.forEach(flag => {
|
||||
skeyrep.find(`#${flag}`).addClass(skey[flag] ? statusclass : "status-na")
|
||||
});
|
||||
|
||||
let fpr = skeyrep.find("#fpr")
|
||||
fpr.addClass(statusclass)
|
||||
fpr.find(".status-text").html(pretty_fpr(skey.fpr))
|
||||
// Algorithm and fingerprint
|
||||
let algo = skeyrep.find("#algo")
|
||||
algo.addClass(statusclass)
|
||||
algo.find(".status-text").html(`${skey.algorithm}, ${skey.bits} bits`)
|
||||
|
||||
skeyrep.appendTo(subkeys)
|
||||
});
|
||||
let fpr = skeyrep.find("#fpr")
|
||||
fpr.addClass(statusclass)
|
||||
fpr.find(".status-text").html(pretty_fpr(skey.fpr))
|
||||
|
||||
// Options
|
||||
if (daemon) {
|
||||
keyrep.find("#options").html(`<button class="btn btn-primary col-12" 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>`)
|
||||
}
|
||||
skeyrep.appendTo(subkeys)
|
||||
});
|
||||
|
||||
return keyrep
|
||||
}
|
||||
// Options
|
||||
if (daemon) {
|
||||
keyrep.find("#options").html(`<button class="btn btn-primary col-12" 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>`)
|
||||
}
|
||||
|
||||
function show_pgp_keyring() {
|
||||
$('#privatekey').html("<tr><td class='text-muted'>Loading...</td></tr>")
|
||||
$('#pubkeys').html("<tr><td class='text-muted'>Loading...</td></tr>")
|
||||
api(
|
||||
"/system/pgp/",
|
||||
"GET",
|
||||
{},
|
||||
function(r) {
|
||||
$('#privatekey').html("")
|
||||
$('#pubkeys').html("")
|
||||
key_html(r.daemon, true, true).appendTo("#privatekey")
|
||||
let pendulum = 1
|
||||
r.imported.forEach(k => {
|
||||
key_html(k, pendulum > 0, false).appendTo("#pubkeys")
|
||||
pendulum *= -1
|
||||
});
|
||||
}
|
||||
)
|
||||
}
|
||||
return keyrep
|
||||
}
|
||||
|
||||
function exportkey(fpr) {
|
||||
api(
|
||||
`/system/pgp/${fpr}/export`,
|
||||
"GET",
|
||||
{},
|
||||
function(r) {
|
||||
show_modal_error("PGP Key", `Key export for <b>${fpr}</b>:<br><br><pre>${r}</pre>`)
|
||||
},
|
||||
function(_ ,xhr) {
|
||||
if (xhr.status == 404) {
|
||||
show_modal_error("Error", `The key you asked for (<b>${fpr}</b>) does not exist!`)
|
||||
} else {
|
||||
// Fallback to the default error modal
|
||||
show_modal_error("Error", "Something went wrong, sorry.")
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
function show_pgp_keyring() {
|
||||
$('#privatekey').html("<tr><td class='text-muted'>Loading...</td></tr>")
|
||||
$('#pubkeys').html("<tr><td class='text-muted'>Loading...</td></tr>")
|
||||
api(
|
||||
"/system/pgp/",
|
||||
"GET",
|
||||
{},
|
||||
function (r) {
|
||||
$('#privatekey').html("")
|
||||
$('#pubkeys').html("")
|
||||
key_html(r.daemon, true, true).appendTo("#privatekey")
|
||||
let pendulum = 1
|
||||
r.imported.forEach(k => {
|
||||
key_html(k, pendulum > 0, false).appendTo("#pubkeys")
|
||||
pendulum *= -1
|
||||
});
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
function rmkey(fpr) {
|
||||
show_modal_confirm("Delete key", `Are you sure you wish to remove the key with the fingerprint ${pretty_fpr(fpr)}?`, "Yes, remove it", () => {
|
||||
api(
|
||||
`/system/pgp/${fpr}`,
|
||||
"DELETE",
|
||||
{},
|
||||
function(r) {
|
||||
if (r.length == 0) {
|
||||
show_modal_error("Delete key", "OK", show_pgp_keyring)
|
||||
} else {
|
||||
wkd_info = "OK. <b>The following entries were removed from WKD:</b><ul>"
|
||||
r.forEach(email => {
|
||||
wkd_info += `<li>${email}</li>`
|
||||
});
|
||||
wkd_info += "</ul>"
|
||||
function exportkey(fpr) {
|
||||
api(
|
||||
`/system/pgp/${fpr}/export`,
|
||||
"GET",
|
||||
{},
|
||||
function (r) {
|
||||
show_modal_error("PGP Key", `Key export for <b>${fpr}</b>:<br><br><pre>${r}</pre>`)
|
||||
},
|
||||
function (_, xhr) {
|
||||
if (xhr.status == 404) {
|
||||
show_modal_error("Error", `The key you asked for (<b>${fpr}</b>) does not exist!`)
|
||||
} else {
|
||||
// Fallback to the default error modal
|
||||
show_modal_error("Error", "Something went wrong, sorry.")
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
show_modal_error("Delete key", wkd_info, show_pgp_keyring)
|
||||
}
|
||||
},
|
||||
function(r) {
|
||||
show_modal_error("Key deletion error", r)
|
||||
}
|
||||
)
|
||||
}, ()=>{})
|
||||
}
|
||||
function rmkey(fpr) {
|
||||
show_modal_confirm("Delete key", `Are you sure you wish to remove the key with the fingerprint ${pretty_fpr(fpr)}?`, "Yes, remove it", () => {
|
||||
api(
|
||||
`/system/pgp/${fpr}`,
|
||||
"DELETE",
|
||||
{},
|
||||
function (r) {
|
||||
if (r.length == 0) {
|
||||
show_modal_error("Delete key", "OK", show_pgp_keyring)
|
||||
} else {
|
||||
wkd_info = "OK. <b>The following entries were removed from WKD:</b><ul>"
|
||||
r.forEach(email => {
|
||||
wkd_info += `<li>${email}</li>`
|
||||
});
|
||||
wkd_info += "</ul>"
|
||||
|
||||
function importkey() {
|
||||
api(
|
||||
"/system/pgp/import",
|
||||
"POST",
|
||||
{
|
||||
key: $("#pgp_paste_key").val()
|
||||
},
|
||||
function(r) {
|
||||
show_modal_error("Import Results", `<ul>
|
||||
show_modal_error("Delete key", wkd_info, show_pgp_keyring)
|
||||
}
|
||||
},
|
||||
function (r) {
|
||||
show_modal_error("Key deletion error", r)
|
||||
}
|
||||
)
|
||||
}, () => { })
|
||||
}
|
||||
|
||||
function importkey() {
|
||||
api(
|
||||
"/system/pgp/import",
|
||||
"POST",
|
||||
{
|
||||
key: $("#pgp_paste_key").val()
|
||||
},
|
||||
function (r) {
|
||||
show_modal_error("Import Results", `<ul>
|
||||
<li><b>Keys read:</b> ${r.keys_read}</li>
|
||||
<li><b>Keys added:</b> ${r.keys_added}</li>
|
||||
<li><b>Keys not changed:</b> ${r.keys_unchanged}</li>
|
||||
|
@ -288,10 +289,10 @@ copy and paste this block in the area below
|
|||
<li><b>Signatures added:</b> ${r.sigs_added}</li>
|
||||
<li><b>Revocations added:</b> ${r.revs_added}</li>
|
||||
</ul>`, show_pgp_keyring)
|
||||
},
|
||||
function(r) {
|
||||
show_modal_error("Import Error", r)
|
||||
}
|
||||
)
|
||||
}
|
||||
},
|
||||
function (r) {
|
||||
show_modal_error("Import Error", r)
|
||||
}
|
||||
)
|
||||
}
|
||||
</script>
|
||||
|
|
|
@ -21,7 +21,8 @@
|
|||
<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();">
|
||||
<input type="checkbox" role="switch" id="use_relay" class="form-check-input" value=false
|
||||
onclick="checkfields();">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
@ -31,7 +32,7 @@
|
|||
<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)">
|
||||
<input type="number" class="form-control" id="relay_port" placeholder="Port (465)">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
@ -45,7 +46,8 @@
|
|||
<label class="input-group-text">Password/Key</label>
|
||||
<input type="password" class="form-control" id="relay_auth_pass" placeholder="">
|
||||
</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>
|
||||
<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>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
|
|
@ -1,297 +1,309 @@
|
|||
<style>
|
||||
.code-white > code {
|
||||
color: #ffffff
|
||||
}
|
||||
.code-white>code {
|
||||
color: #ffffff
|
||||
}
|
||||
|
||||
#ssl_provision_result > div > div {
|
||||
white-space: pre;
|
||||
}
|
||||
#ssl_provision_result>div>div {
|
||||
white-space: pre;
|
||||
}
|
||||
|
||||
#ssl_domains .icon {
|
||||
#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’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’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>
|
||||
<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’s Encrypt</a>, a free TLS certificate provider, for:</p>
|
||||
<ul class="text-primary"></ul>
|
||||
<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’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’re agreeing to the <a href="https://letsencrypt.org/repository">Let’s Encrypt Subscriber Agreement</a>.</b></label>
|
||||
</div>
|
||||
</div>
|
||||
<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’re agreeing to the <a
|
||||
href="https://letsencrypt.org/repository">Let’s Encrypt Subscriber Agreement</a>.</b></label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="ssl_provision_result" class="mt-4"></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’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’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>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Domain</th>
|
||||
<th>Certificate Status</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
</tbody>
|
||||
<caption></caption>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Domain</th>
|
||||
<th>Certificate Status</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
|
||||
<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 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><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>
|
||||
|
||||
<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">
|
||||
<option value="">(Select)</option>
|
||||
{% for code, name in csr_country_codes %}
|
||||
<option value="{{code}}">{{name}}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<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">
|
||||
<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>
|
||||
<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>
|
||||
|
||||
<div id="csr_info" style="display: none;">
|
||||
<p>You will need to provide the certificate provider this Certificate Signing Request (CSR):</p>
|
||||
<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>
|
||||
<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>
|
||||
|
||||
<button class="btn btn-sm btn-secondary">Copy it!</button>
|
||||
<hr>
|
||||
<small>The CSR is safe to share. It can only be used in combination with a secret key stored on this machine.</small>
|
||||
<button class="btn btn-sm btn-secondary">Copy it!</button>
|
||||
<hr>
|
||||
<small>The CSR is safe to share. It can only be used in combination with a secret key stored on this machine.</small>
|
||||
|
||||
<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-----
stuff here
-----END CERTIFICATE-----"></textarea>
|
||||
<label for="ssl_paste_cert" class="ms-3">TLS/SSL Certificate</label>
|
||||
</div>
|
||||
<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-----
stuff here
-----END CERTIFICATE-----"></textarea>
|
||||
<label for="ssl_paste_cert" class="ms-3">TLS/SSL Certificate</label>
|
||||
</div>
|
||||
|
||||
<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-----
stuff here
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
more stuff here
-----END CERTIFICATE-----"></textarea>
|
||||
<label for="ssl_paste_chain" class="ms-3">TLS/SSL intermediate Chain (if provided)</label>
|
||||
</div>
|
||||
</div>
|
||||
<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-----
stuff here
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
more stuff here
-----END CERTIFICATE-----"></textarea>
|
||||
<label for="ssl_paste_chain" class="ms-3">TLS/SSL intermediate Chain (if provided)</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<br>
|
||||
<br>
|
||||
|
||||
<button class="btn btn-primary" onclick="install_cert()">Install</button>
|
||||
<button class="btn btn-primary" onclick="install_cert()">Install</button>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function show_tls(keep_provisioning_shown) {
|
||||
api(
|
||||
"/ssl/status",
|
||||
"GET",
|
||||
{
|
||||
},
|
||||
function(res) {
|
||||
// provisioning status
|
||||
function show_tls(keep_provisioning_shown) {
|
||||
api(
|
||||
"/ssl/status",
|
||||
"GET",
|
||||
{
|
||||
},
|
||||
function (res) {
|
||||
// provisioning status
|
||||
|
||||
$("#ssl_provision_p ul").html("")
|
||||
if (!keep_provisioning_shown)
|
||||
$('#ssl_provision').toggle(res.can_provision.length > 0)
|
||||
$("#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))
|
||||
});
|
||||
}
|
||||
$('#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))
|
||||
});
|
||||
}
|
||||
|
||||
// certificate status
|
||||
var domains = res.status;
|
||||
var tb = $('#ssl_domains tbody');
|
||||
tb.text('');
|
||||
$('#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>");
|
||||
tb.append(row);
|
||||
row.attr('data-domain', domains[i].domain);
|
||||
row.find('th').text(domains[i].domain);
|
||||
if (domains[i].status == "not-applicable") {
|
||||
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.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;
|
||||
}
|
||||
let txt = row.find(".status")
|
||||
txt.addClass(statusclass);
|
||||
txt.find(".fas").addClass(faclass)
|
||||
txt.find("span").text(domains[i].text);
|
||||
// certificate status
|
||||
var domains = res.status;
|
||||
var tb = $('#ssl_domains tbody');
|
||||
tb.text('');
|
||||
$('#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>");
|
||||
tb.append(row);
|
||||
row.attr('data-domain', domains[i].domain);
|
||||
row.find('th').text(domains[i].domain);
|
||||
if (domains[i].status == "not-applicable") {
|
||||
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.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;
|
||||
}
|
||||
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));
|
||||
}
|
||||
});
|
||||
}
|
||||
$('#ssldomain').append($('<option>').text(domains[i].domain));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function ssl_install(elem) {
|
||||
var domain = $(elem).parents('tr').attr('data-domain');
|
||||
$('#ssldomain').val(domain);
|
||||
show_csr();
|
||||
$('html, body').animate({ scrollTop: $('#ssl_install_header').offset().top - $('.navbar-fixed-top').height() - 20 })
|
||||
return false;
|
||||
}
|
||||
function ssl_install(elem) {
|
||||
var domain = $(elem).parents('tr').attr('data-domain');
|
||||
$('#ssldomain').val(domain);
|
||||
show_csr();
|
||||
$('html, body').animate({ scrollTop: $('#ssl_install_header').offset().top - $('.navbar-fixed-top').height() - 20 })
|
||||
return false;
|
||||
}
|
||||
|
||||
function show_csr() {
|
||||
// Can't show a CSR until both inputs are entered.
|
||||
if ($('#ssldomain').val() == "") return;
|
||||
if ($('#sslcc').val() == "") return;
|
||||
function show_csr() {
|
||||
// Can't show a CSR until both inputs are entered.
|
||||
if ($('#ssldomain').val() == "") return;
|
||||
if ($('#sslcc').val() == "") return;
|
||||
|
||||
// Scroll to it and fetch.
|
||||
$('#csr_info').slideDown();
|
||||
$('#ssl_csr').text('Loading...');
|
||||
api(
|
||||
"/ssl/csr/" + $('#ssldomain').val(),
|
||||
"POST",
|
||||
{
|
||||
countrycode: $('#sslcc').val()
|
||||
},
|
||||
function(data) {
|
||||
$('#ssl_csr').text(data);
|
||||
});
|
||||
}
|
||||
// Scroll to it and fetch.
|
||||
$('#csr_info').slideDown();
|
||||
$('#ssl_csr').text('Loading...');
|
||||
api(
|
||||
"/ssl/csr/" + $('#ssldomain').val(),
|
||||
"POST",
|
||||
{
|
||||
countrycode: $('#sslcc').val()
|
||||
},
|
||||
function (data) {
|
||||
$('#ssl_csr').text(data);
|
||||
});
|
||||
}
|
||||
|
||||
function install_cert() {
|
||||
api(
|
||||
"/ssl/install",
|
||||
"POST",
|
||||
{
|
||||
domain: $('#ssldomain').val(),
|
||||
cert: $('#ssl_paste_cert').val(),
|
||||
chain: $('#ssl_paste_chain').val()
|
||||
},
|
||||
function(status) {
|
||||
if (/^OK($|\n)/.test(status)) {
|
||||
console.log(status)
|
||||
show_modal_error("TLS Certificate Installation", "Certificate has been installed. Check that you have no connection problems to the domain.", function() { show_ssl(); $('#csr_info').slideUp(); });
|
||||
} else {
|
||||
show_modal_error("TLS Certificate Installation", status);
|
||||
}
|
||||
});
|
||||
}
|
||||
function install_cert() {
|
||||
api(
|
||||
"/ssl/install",
|
||||
"POST",
|
||||
{
|
||||
domain: $('#ssldomain').val(),
|
||||
cert: $('#ssl_paste_cert').val(),
|
||||
chain: $('#ssl_paste_chain').val()
|
||||
},
|
||||
function (status) {
|
||||
if (/^OK($|\n)/.test(status)) {
|
||||
console.log(status)
|
||||
show_modal_error("TLS Certificate Installation", "Certificate has been installed. Check that you have no connection problems to the domain.", function () { show_ssl(); $('#csr_info').slideUp(); });
|
||||
} else {
|
||||
show_modal_error("TLS Certificate Installation", status);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function provision_tls_cert() {
|
||||
// Automatically provision any certs.
|
||||
$('#ssl_provision_p .btn').attr('disabled', '1'); // prevent double-clicks
|
||||
api(
|
||||
"/ssl/provision",
|
||||
"POST",
|
||||
{ },
|
||||
function(status) {
|
||||
// Clear last attempt.
|
||||
$('#ssl_provision_result').html("");
|
||||
may_reenable_provision_button = true;
|
||||
function provision_tls_cert() {
|
||||
// Automatically provision any certs.
|
||||
$('#ssl_provision_p .btn').attr('disabled', '1'); // prevent double-clicks
|
||||
api(
|
||||
"/ssl/provision",
|
||||
"POST",
|
||||
{},
|
||||
function (status) {
|
||||
// Clear last attempt.
|
||||
$('#ssl_provision_result').html("");
|
||||
may_reenable_provision_button = true;
|
||||
|
||||
// Nothing was done. There might also be problem domains, but we've already displayed those.
|
||||
if (status.requests.length == 0) {
|
||||
show_modal_error("TLS Certificate Provisioning", "There were no domain names to provision certificates for.");
|
||||
// don't return - haven't re-enabled the provision button
|
||||
}
|
||||
// Nothing was done. There might also be problem domains, but we've already displayed those.
|
||||
if (status.requests.length == 0) {
|
||||
show_modal_error("TLS Certificate Provisioning", "There were no domain names to provision certificates for.");
|
||||
// don't return - haven't re-enabled the provision button
|
||||
}
|
||||
|
||||
// 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];
|
||||
// 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];
|
||||
|
||||
if (r.result == "skipped") {
|
||||
// not interested --- this domain wasn't in the table
|
||||
// to begin with
|
||||
continue;
|
||||
}
|
||||
if (r.result == "skipped") {
|
||||
// not interested --- this domain wasn't in the table
|
||||
// to begin with
|
||||
continue;
|
||||
}
|
||||
|
||||
// plain log line
|
||||
if (typeof r === "string") {
|
||||
if (r !== "") {
|
||||
global_logs.append(r)
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// plain log line
|
||||
if (typeof r === "string") {
|
||||
if (r !== "") {
|
||||
global_logs.append(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);
|
||||
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(", ")}`);
|
||||
}
|
||||
if (status.requests.length > 0) {
|
||||
n.find(".card-header").html(`Logs for ${r.domains.map((h) => { return `<code>${h}</code>` }).join(", ")}`);
|
||||
}
|
||||
|
||||
if (r.result == "error") {
|
||||
n.find(".card-header").addClass("bg-danger")
|
||||
} else if (r.result == "installed") {
|
||||
n.find(".card-header").addClass("bg-success")
|
||||
setTimeout("show_tls(true)", 1);
|
||||
}
|
||||
if (r.result == "error") {
|
||||
n.find(".card-header").addClass("bg-danger")
|
||||
} else if (r.result == "installed") {
|
||||
n.find(".card-header").addClass("bg-success")
|
||||
setTimeout("show_tls(true)", 1);
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
// 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);
|
||||
}
|
||||
|
||||
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 (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) {
|
||||
$('#ssl_provision_p .btn').removeAttr("disabled");
|
||||
}
|
||||
});
|
||||
}
|
||||
if (may_reenable_provision_button) {
|
||||
$('#ssl_provision_p .btn').removeAttr("disabled");
|
||||
}
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
|
|
@ -12,39 +12,84 @@
|
|||
<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>
|
||||
<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>
|
||||
</table>
|
||||
|
||||
<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>
|
||||
<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">
|
||||
<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,
|
||||
your contacts and calendar may already appear on your device.</p>
|
||||
<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>
|
||||
<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>
|
||||
</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>
|
||||
|
|
|
@ -1,387 +1,407 @@
|
|||
<style>
|
||||
#backup-status tr.full-backup td { font-weight: bold; }
|
||||
#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 it 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()">
|
||||
<option value="off">Nowhere (Disable Backups)</option>
|
||||
<option value="local">{{hostname}}</option>
|
||||
<option value="rsync">rsync</option>
|
||||
<option value="s3">S3 (Amazon or compatible) </option>
|
||||
<option value="b2">Backblaze B2</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<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()">
|
||||
<option value="off">Nowhere (Disable Backups)</option>
|
||||
<option value="local">{{hostname}}</option>
|
||||
<option value="rsync">rsync</option>
|
||||
<option value="s3">S3 (Amazon or compatible) </option>
|
||||
<option value="b2">Backblaze B2</option>
|
||||
</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’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">
|
||||
<!-- 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’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">
|
||||
|
||||
<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
|
||||
password from <tt class="backup-encpassword-file"></tt> to a safe and
|
||||
secure location. You will need this file to decrypt backup files.</p>
|
||||
<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
|
||||
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>
|
||||
</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>
|
||||
</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="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">
|
||||
{% for name, host in backup_s3_hosts %}
|
||||
<option value="{{host}}">{{name}}</option>
|
||||
{% endfor %}
|
||||
<option value="other">Other (non AWS)</option>
|
||||
</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>
|
||||
</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>
|
||||
</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>
|
||||
</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>
|
||||
</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>
|
||||
</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>
|
||||
</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>
|
||||
</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>
|
||||
</div>
|
||||
<div class="mt-3">
|
||||
<button id="set-s3-backup-button" type="submit" class="btn btn-primary">Save</button>
|
||||
</div>
|
||||
</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>
|
||||
</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>
|
||||
</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="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">
|
||||
{% for name, host in backup_s3_hosts %}
|
||||
<option value="{{host}}">{{name}}</option>
|
||||
{% endfor %}
|
||||
<option value="other">Other (non AWS)</option>
|
||||
</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>
|
||||
</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>
|
||||
</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>
|
||||
</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>
|
||||
</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>
|
||||
</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>
|
||||
</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>
|
||||
</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>
|
||||
</div>
|
||||
<div class="mt-3">
|
||||
<button id="set-s3-backup-button" type="submit" class="btn btn-primary">Save</button>
|
||||
</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>
|
||||
<thead>
|
||||
<th colspan="2">When</th>
|
||||
<th>Type</th>
|
||||
<th>Size</th>
|
||||
<th>Deleted in...</th>
|
||||
</thead>
|
||||
<tbody>
|
||||
</tbody>
|
||||
<caption></caption>
|
||||
<thead>
|
||||
<th colspan="2">When</th>
|
||||
<th>Type</th>
|
||||
<th>Size</th>
|
||||
<th>Deleted in...</th>
|
||||
</thead>
|
||||
<tbody>
|
||||
</tbody>
|
||||
</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>
|
||||
<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>
|
||||
|
||||
<script>
|
||||
|
||||
function toggle_form() {
|
||||
var target_type = $("#backup-target-type").val();
|
||||
$(".backup-target-local, .backup-target-rsync, .backup-target-s3, .backup-target-b2").hide();
|
||||
$(".backup-target-" + target_type).show();
|
||||
function toggle_form() {
|
||||
var target_type = $("#backup-target-type").val();
|
||||
$(".backup-target-local, .backup-target-rsync, .backup-target-s3, .backup-target-b2").hide();
|
||||
$(".backup-target-" + target_type).show();
|
||||
|
||||
init_inputs(target_type);
|
||||
}
|
||||
init_inputs(target_type);
|
||||
}
|
||||
|
||||
function nice_size(bytes) {
|
||||
var powers = ['bytes', 'KB', 'MB', 'GB', 'TB'];
|
||||
while (true) {
|
||||
if (powers.length == 1) break;
|
||||
if (bytes < 1000) break;
|
||||
bytes /= 1024;
|
||||
powers.shift();
|
||||
}
|
||||
// round to have three significant figures but at most one decimal place
|
||||
if (bytes >= 100)
|
||||
bytes = Math.round(bytes)
|
||||
else
|
||||
bytes = Math.round(bytes*10)/10;
|
||||
return bytes + " " + powers[0];
|
||||
}
|
||||
function nice_size(bytes) {
|
||||
var powers = ['bytes', 'KB', 'MB', 'GB', 'TB'];
|
||||
while (true) {
|
||||
if (powers.length == 1) break;
|
||||
if (bytes < 1000) break;
|
||||
bytes /= 1024;
|
||||
powers.shift();
|
||||
}
|
||||
// round to have three significant figures but at most one decimal place
|
||||
if (bytes >= 100)
|
||||
bytes = Math.round(bytes)
|
||||
else
|
||||
bytes = Math.round(bytes * 10) / 10;
|
||||
return bytes + " " + powers[0];
|
||||
}
|
||||
|
||||
function show_system_backup() {
|
||||
show_custom_backup()
|
||||
function show_system_backup() {
|
||||
show_custom_backup()
|
||||
|
||||
$('#backup-status tbody').html("<tr><td colspan='5' class='text-muted'>Loading...</td></tr>")
|
||||
api(
|
||||
"/system/backup/status",
|
||||
"GET",
|
||||
{ },
|
||||
function(r) {
|
||||
if (r.error) {
|
||||
show_modal_error("Backup Error", $("<pre/>").text(r.error));
|
||||
return;
|
||||
}
|
||||
$('#backup-status tbody').html("<tr><td colspan='5' class='text-muted'>Loading...</td></tr>")
|
||||
api(
|
||||
"/system/backup/status",
|
||||
"GET",
|
||||
{},
|
||||
function (r) {
|
||||
if (r.error) {
|
||||
show_modal_error("Backup Error", $("<pre/>").text(r.error));
|
||||
return;
|
||||
}
|
||||
|
||||
$('#backup-status tbody').html("");
|
||||
var total_disk_size = 0;
|
||||
$('#backup-status tbody').html("");
|
||||
var total_disk_size = 0;
|
||||
|
||||
if (typeof r.backups == "undefined") {
|
||||
var tr = $('<tr><td colspan="5">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>');
|
||||
$('#backup-status tbody').append(tr);
|
||||
}
|
||||
if (typeof r.backups == "undefined") {
|
||||
var tr = $('<tr><td colspan="5">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>');
|
||||
$('#backup-status tbody').append(tr);
|
||||
}
|
||||
|
||||
// Backups ARE enabled.
|
||||
$('#create-full-backup-button').css("display","unset")
|
||||
$('#create-incremental-backup-button').css("display","unset")
|
||||
for (var i = 0; i < r.backups.length; i++) {
|
||||
var b = r.backups[i];
|
||||
var tr = $('<tr/>');
|
||||
if (b.full) tr.addClass("full-backup");
|
||||
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)) );
|
||||
if (b.deleted_in)
|
||||
tr.append( $('<td/>').text(b.deleted_in) );
|
||||
else
|
||||
tr.append( $('<td class="text-muted">unknown</td>') );
|
||||
$('#backup-status tbody').append(tr);
|
||||
// Backups ARE enabled.
|
||||
$('#create-full-backup-button').css("display", "unset")
|
||||
$('#create-incremental-backup-button').css("display", "unset")
|
||||
for (var i = 0; i < r.backups.length; i++) {
|
||||
var b = r.backups[i];
|
||||
var tr = $('<tr/>');
|
||||
if (b.full) tr.addClass("full-backup");
|
||||
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)));
|
||||
if (b.deleted_in)
|
||||
tr.append($('<td/>').text(b.deleted_in));
|
||||
else
|
||||
tr.append($('<td class="text-muted">unknown</td>'));
|
||||
$('#backup-status tbody').append(tr);
|
||||
|
||||
total_disk_size += b.size;
|
||||
}
|
||||
total_disk_size += b.size;
|
||||
}
|
||||
|
||||
total_disk_size += r.unmatched_file_size;
|
||||
$('#backup-total-size').text(nice_size(total_disk_size));
|
||||
})
|
||||
}
|
||||
total_disk_size += r.unmatched_file_size;
|
||||
$('#backup-total-size').text(nice_size(total_disk_size));
|
||||
})
|
||||
}
|
||||
|
||||
function show_custom_backup() {
|
||||
$(".backup-target-local, .backup-target-rsync, .backup-target-s3, .backup-target-b2").hide();
|
||||
api(
|
||||
"/system/backup/config",
|
||||
"GET",
|
||||
{ },
|
||||
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);
|
||||
$(".backup-location").text(r.file_target_directory);
|
||||
$(".backup-encpassword-file").text(r.enc_pw_file);
|
||||
$("#ssh-pub-key").val(r.ssh_pub_key);
|
||||
function show_custom_backup() {
|
||||
$(".backup-target-local, .backup-target-rsync, .backup-target-s3, .backup-target-b2").hide();
|
||||
api(
|
||||
"/system/backup/config",
|
||||
"GET",
|
||||
{},
|
||||
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);
|
||||
$(".backup-location").text(r.file_target_directory);
|
||||
$(".backup-encpassword-file").text(r.enc_pw_file);
|
||||
$("#ssh-pub-key").val(r.ssh_pub_key);
|
||||
|
||||
if (r.target == "file://" + r.file_target_directory) {
|
||||
$("#backup-target-type").val("local");
|
||||
} else if (r.target == "off") {
|
||||
$("#backup-target-type").val("off");
|
||||
} else if (r.target.substring(0, 8) == "rsync://") {
|
||||
$("#backup-target-type").val("rsync");
|
||||
let uri = r.target.substring(8)
|
||||
let i = uri.indexOf("/")
|
||||
let path = [uri.slice(0, i), uri.slice(i + 1)];
|
||||
let host_parts = path.shift().split('@');
|
||||
$("#backup-target-rsync-user").val(host_parts[0]);
|
||||
$("#backup-target-rsync-host").val(host_parts[1]);
|
||||
$("#backup-target-rsync-path").val(path[0]);
|
||||
$("#backup-target-rsync-port").val(r.target_rsync_port)
|
||||
} else if (r.target.substring(0, 5) == "s3://") {
|
||||
$("#backup-target-type").val("s3");
|
||||
var hostpath = r.target.substring(5).split('/');
|
||||
var host = hostpath.shift();
|
||||
$("#backup-target-s3-host").val(host);
|
||||
$("#backup-target-s3-path").val(hostpath.join('/'));
|
||||
} else if (r.target.substring(0, 5) == "b2://") {
|
||||
$("#backup-target-type").val("b2");
|
||||
var targetPath = r.target.substring(5);
|
||||
var b2_application_keyid = targetPath.split(':')[0];
|
||||
var b2_applicationkey = targetPath.split(':')[1].split('@')[0];
|
||||
var b2_bucket = targetPath.split('@')[1];
|
||||
$("#backup-target-b2-user").val(b2_application_keyid);
|
||||
$("#backup-target-b2-pass").val(b2_applicationkey);
|
||||
$("#backup-target-b2-bucket").val(b2_bucket);
|
||||
}
|
||||
toggle_form()
|
||||
})
|
||||
}
|
||||
if (r.target == "file://" + r.file_target_directory) {
|
||||
$("#backup-target-type").val("local");
|
||||
} else if (r.target == "off") {
|
||||
$("#backup-target-type").val("off");
|
||||
} else if (r.target.substring(0, 8) == "rsync://") {
|
||||
$("#backup-target-type").val("rsync");
|
||||
let uri = r.target.substring(8)
|
||||
let i = uri.indexOf("/")
|
||||
let path = [uri.slice(0, i), uri.slice(i + 1)];
|
||||
let host_parts = path.shift().split('@');
|
||||
$("#backup-target-rsync-user").val(host_parts[0]);
|
||||
$("#backup-target-rsync-host").val(host_parts[1]);
|
||||
$("#backup-target-rsync-path").val(path[0]);
|
||||
$("#backup-target-rsync-port").val(r.target_rsync_port)
|
||||
} else if (r.target.substring(0, 5) == "s3://") {
|
||||
$("#backup-target-type").val("s3");
|
||||
var hostpath = r.target.substring(5).split('/');
|
||||
var host = hostpath.shift();
|
||||
$("#backup-target-s3-host").val(host);
|
||||
$("#backup-target-s3-path").val(hostpath.join('/'));
|
||||
} else if (r.target.substring(0, 5) == "b2://") {
|
||||
$("#backup-target-type").val("b2");
|
||||
var targetPath = r.target.substring(5);
|
||||
var b2_application_keyid = targetPath.split(':')[0];
|
||||
var b2_applicationkey = targetPath.split(':')[1].split('@')[0];
|
||||
var b2_bucket = targetPath.split('@')[1];
|
||||
$("#backup-target-b2-user").val(b2_application_keyid);
|
||||
$("#backup-target-b2-pass").val(b2_applicationkey);
|
||||
$("#backup-target-b2-bucket").val(b2_bucket);
|
||||
}
|
||||
toggle_form()
|
||||
})
|
||||
}
|
||||
|
||||
function set_custom_backup() {
|
||||
var target_type = $("#backup-target-type").val();
|
||||
var target_user = $("#backup-target-user").val();
|
||||
var target_pass = $("#backup-target-pass").val();
|
||||
let target_port = $("#backup-target-rsync-port").val();
|
||||
function set_custom_backup() {
|
||||
var target_type = $("#backup-target-type").val();
|
||||
var target_user = $("#backup-target-user").val();
|
||||
var target_pass = $("#backup-target-pass").val();
|
||||
let target_port = $("#backup-target-rsync-port").val();
|
||||
|
||||
var target;
|
||||
if (target_type == "local" || target_type == "off")
|
||||
target = target_type;
|
||||
else if (target_type == "s3")
|
||||
target = "s3://" + $("#backup-target-s3-host").val() + "/" + $("#backup-target-s3-path").val();
|
||||
else if (target_type == "rsync") {
|
||||
target = "rsync://" + $("#backup-target-rsync-user").val() + "@" + $("#backup-target-rsync-host").val()
|
||||
+ "/" + $("#backup-target-rsync-path").val();
|
||||
target_user = '';
|
||||
} else if (target_type == "b2") {
|
||||
target = 'b2://' + $('#backup-target-b2-user').val() + ':' + $('#backup-target-b2-pass').val()
|
||||
+ '@' + $('#backup-target-b2-bucket').val()
|
||||
target_user = '';
|
||||
target_pass = '';
|
||||
}
|
||||
var target;
|
||||
if (target_type == "local" || target_type == "off")
|
||||
target = target_type;
|
||||
else if (target_type == "s3")
|
||||
target = "s3://" + $("#backup-target-s3-host").val() + "/" + $("#backup-target-s3-path").val();
|
||||
else if (target_type == "rsync") {
|
||||
target = "rsync://" + $("#backup-target-rsync-user").val() + "@" + $("#backup-target-rsync-host").val()
|
||||
+ "/" + $("#backup-target-rsync-path").val();
|
||||
target_user = '';
|
||||
} else if (target_type == "b2") {
|
||||
target = 'b2://' + $('#backup-target-b2-user').val() + ':' + $('#backup-target-b2-pass').val()
|
||||
+ '@' + $('#backup-target-b2-bucket').val()
|
||||
target_user = '';
|
||||
target_pass = '';
|
||||
}
|
||||
|
||||
var min_age = $("#backup-min-age").val();
|
||||
api(
|
||||
"/system/backup/config",
|
||||
"POST",
|
||||
{
|
||||
target: target,
|
||||
target_user: target_user,
|
||||
target_pass: target_pass,
|
||||
target_rsync_port: target_port,
|
||||
min_age: min_age
|
||||
},
|
||||
function(r) {
|
||||
// use .text() --- it's a text response, not html
|
||||
show_modal_error("Backup configuration", $("<p/>").text(r), function() { if (r == "OK") show_system_backup(); }); // refresh after modal on success
|
||||
},
|
||||
function(r) {
|
||||
// use .text() --- it's a text response, not html
|
||||
show_modal_error("Backup configuration", $("<p/>").text(r));
|
||||
});
|
||||
return false;
|
||||
}
|
||||
var min_age = $("#backup-min-age").val();
|
||||
api(
|
||||
"/system/backup/config",
|
||||
"POST",
|
||||
{
|
||||
target: target,
|
||||
target_user: target_user,
|
||||
target_pass: target_pass,
|
||||
target_rsync_port: target_port,
|
||||
min_age: min_age
|
||||
},
|
||||
function (r) {
|
||||
// use .text() --- it's a text response, not html
|
||||
show_modal_error("Backup configuration", $("<p/>").text(r), function () { if (r == "OK") show_system_backup(); }); // refresh after modal on success
|
||||
},
|
||||
function (r) {
|
||||
// use .text() --- it's a text response, not html
|
||||
show_modal_error("Backup configuration", $("<p/>").text(r));
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
function init_inputs(target_type) {
|
||||
function set_host(host) {
|
||||
if(host !== 'other') {
|
||||
$("#backup-target-s3-host").val(host);
|
||||
} 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());
|
||||
});
|
||||
set_host($('#backup-target-s3-host-select').val());
|
||||
}
|
||||
}
|
||||
function init_inputs(target_type) {
|
||||
function set_host(host) {
|
||||
if (host !== 'other') {
|
||||
$("#backup-target-s3-host").val(host);
|
||||
} 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());
|
||||
});
|
||||
set_host($('#backup-target-s3-host-select').val());
|
||||
}
|
||||
}
|
||||
|
||||
function do_backup(is_full) {
|
||||
let disclaimer = "The backup process will pause some services (such as PHP, Postfix and Dovecot). Depending on the size of the data this can take a while."
|
||||
if (!is_full) {
|
||||
disclaimer += "\nDepending on the amount of incremental backups done after the last full backup, the box may decide to do a full backup instead."
|
||||
}
|
||||
show_modal_confirm("Warning!", disclaimer, "Start Backup", () => {
|
||||
api(
|
||||
"/system/backup/new",
|
||||
"POST",
|
||||
{
|
||||
full: is_full
|
||||
},
|
||||
function(r) {
|
||||
// use .text() --- it's a text response, not html
|
||||
show_modal_error("Backup configuration", $("<p/>").text(r), function() { if (r == "OK") show_system_backup(); }); // refresh after modal on success
|
||||
},
|
||||
function(r) {
|
||||
// use .text() --- it's a text response, not html
|
||||
show_modal_error("Backup configuration", $("<p/>").text(r));
|
||||
});
|
||||
return false;
|
||||
})
|
||||
}
|
||||
function do_backup(is_full) {
|
||||
let disclaimer = "The backup process will pause some services (such as PHP, Postfix and Dovecot). Depending on the size of the data this can take a while."
|
||||
if (!is_full) {
|
||||
disclaimer += "\nDepending on the amount of incremental backups done after the last full backup, the box may decide to do a full backup instead."
|
||||
}
|
||||
show_modal_confirm("Warning!", disclaimer, "Start Backup", () => {
|
||||
api(
|
||||
"/system/backup/new",
|
||||
"POST",
|
||||
{
|
||||
full: is_full
|
||||
},
|
||||
function (r) {
|
||||
// use .text() --- it's a text response, not html
|
||||
show_modal_error("Backup configuration", $("<p/>").text(r), function () { if (r == "OK") show_system_backup(); }); // refresh after modal on success
|
||||
},
|
||||
function (r) {
|
||||
// use .text() --- it's a text response, not html
|
||||
show_modal_error("Backup configuration", $("<p/>").text(r));
|
||||
});
|
||||
return false;
|
||||
})
|
||||
}
|
||||
|
||||
</script>
|
||||
|
|
|
@ -4,9 +4,11 @@
|
|||
#system-checks .message {
|
||||
display: inline;
|
||||
}
|
||||
|
||||
#system-checks .icon {
|
||||
min-width: 2em;
|
||||
}
|
||||
|
||||
#system-checks .heading {
|
||||
font-weight: bold;
|
||||
font-size: 180%;
|
||||
|
@ -21,9 +23,11 @@
|
|||
.status-error .fas {
|
||||
color: rgb(190, 0, 0);
|
||||
}
|
||||
|
||||
.status-error.sym {
|
||||
color: rgb(190, 0, 0);
|
||||
}
|
||||
|
||||
.status-error .status-text {
|
||||
color: rgb(70, 0, 0);
|
||||
}
|
||||
|
@ -31,9 +35,11 @@
|
|||
.status-warning .fas {
|
||||
color: rgb(191, 150, 0);
|
||||
}
|
||||
|
||||
.status-warning.sym {
|
||||
color: rgb(191, 150, 0);
|
||||
}
|
||||
|
||||
.status-warning .status-text {
|
||||
color: rgb(69, 54, 0);
|
||||
}
|
||||
|
@ -41,9 +47,11 @@
|
|||
.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);
|
||||
}
|
||||
|
@ -51,9 +59,11 @@
|
|||
.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);
|
||||
}
|
||||
|
|
|
@ -1,11 +1,27 @@
|
|||
<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;
|
||||
}
|
||||
</style>
|
||||
|
||||
<h3>Add a mail user</h3>
|
||||
|
@ -13,110 +29,117 @@
|
|||
<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">
|
||||
</div>
|
||||
</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="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">
|
||||
</div>
|
||||
</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">
|
||||
<option value="">Normal User</option>
|
||||
<option value="admin">Administrator</option>
|
||||
</select>
|
||||
</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">
|
||||
<option value="">Normal User</option>
|
||||
<option value="admin">Administrator</option>
|
||||
</select>
|
||||
</div>
|
||||
</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>
|
||||
<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>
|
||||
<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>
|
||||
<button type="submit" class="btn btn-primary">Add User</button>
|
||||
</form>
|
||||
|
||||
<h3>Existing mail users</h3>
|
||||
<table id="user_table" class="table col-12">
|
||||
<caption></caption>
|
||||
<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>Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
</tbody>
|
||||
<caption></caption>
|
||||
<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>Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<div style="display: none">
|
||||
<table>
|
||||
<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>
|
||||
<td class='actions'>
|
||||
<span class='privs'>
|
||||
</span>
|
||||
<table>
|
||||
<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>
|
||||
<td class='actions'>
|
||||
<span class='privs'>
|
||||
</span>
|
||||
|
||||
<span class="if_active">
|
||||
<a href="#" onclick="users_set_quota(this); return false;" class='setquota' title="Set Quota">
|
||||
set quota
|
||||
</a>
|
||||
|
|
||||
</span>
|
||||
<span class="if_active">
|
||||
<a href="#" onclick="users_set_quota(this); return false;" class='setquota' title="Set Quota">
|
||||
set quota
|
||||
</a>
|
||||
|
|
||||
</span>
|
||||
|
||||
<span class="if_active">
|
||||
<a href="#" onclick="users_set_password(this); return false;" class='setpw' title="Set Password">
|
||||
set password
|
||||
</a>
|
||||
|
|
||||
</span>
|
||||
<span class="if_active">
|
||||
<a href="#" onclick="users_set_password(this); return false;" class='setpw' title="Set Password">
|
||||
set password
|
||||
</a>
|
||||
|
|
||||
</span>
|
||||
|
||||
<span class='add-privs'>
|
||||
</span>
|
||||
<span class='add-privs'>
|
||||
</span>
|
||||
|
||||
<a href="#" onclick="users_remove(this); return false;" class='if_active' title="Archive Account">
|
||||
archive account
|
||||
</a>
|
||||
</td>
|
||||
</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>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<a href="#" onclick="users_remove(this); return false;" class='if_active' title="Archive Account">
|
||||
archive account
|
||||
</a>
|
||||
</td>
|
||||
</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>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<h3>Mail user API (advanced)</h3>
|
||||
|
@ -134,36 +157,57 @@
|
|||
<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 users. 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 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>Removes a mail user. Required POST-by 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></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>Set the quota for a mail user. Required POST-body parameters are <code>email</code> and <code>quota</code>.</td>
|
||||
</tr>
|
||||
<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 users. 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 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>Removes a mail user. Required POST-by 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>
|
||||
</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>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
|
||||
|
@ -182,228 +226,228 @@ curl -X POST -d "email=new_user@mydomail.com" https://{{hostname}}/admin/mail/us
|
|||
</pre>
|
||||
|
||||
<script>
|
||||
function show_users() {
|
||||
api(
|
||||
"/system/default-quota",
|
||||
"GET",
|
||||
{},
|
||||
function(r) {
|
||||
$('#adduserQuota').val(r['default-quota']);
|
||||
}
|
||||
);
|
||||
function show_users() {
|
||||
api(
|
||||
"/system/default-quota",
|
||||
"GET",
|
||||
{},
|
||||
function (r) {
|
||||
$('#adduserQuota').val(r['default-quota']);
|
||||
}
|
||||
);
|
||||
|
||||
$('#user_table tbody').html("<tr><td colspan='6' class='text-muted'>Loading...</td></tr>")
|
||||
api(
|
||||
"/mail/users",
|
||||
"GET",
|
||||
{ format: 'json' },
|
||||
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>");
|
||||
hdr.find('th').text(r[i].domain);
|
||||
$('#user_table tbody').append(hdr);
|
||||
$('#user_table tbody').html("<tr><td colspan='6' class='text-muted'>Loading...</td></tr>")
|
||||
api(
|
||||
"/mail/users",
|
||||
"GET",
|
||||
{ format: 'json' },
|
||||
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>");
|
||||
hdr.find('th').text(r[i].domain);
|
||||
$('#user_table tbody').append(hdr);
|
||||
|
||||
for (var k = 0; k < r[i].users.length; k++) {
|
||||
var user = r[i].users[k];
|
||||
for (var k = 0; k < r[i].users.length; k++) {
|
||||
var user = r[i].users[k];
|
||||
|
||||
var n = $("#user-template").clone();
|
||||
var n2 = $("#user-extra-template").clone();
|
||||
n.attr('id', '');
|
||||
n2.attr('id', '');
|
||||
$('#user_table tbody').append(n);
|
||||
$('#user_table tbody').append(n2);
|
||||
var n = $("#user-template").clone();
|
||||
var n2 = $("#user-extra-template").clone();
|
||||
n.attr('id', '');
|
||||
n2.attr('id', '');
|
||||
$('#user_table tbody').append(n);
|
||||
$('#user_table tbody').append(n2);
|
||||
|
||||
n.addClass("account_" + user.status);
|
||||
n2.addClass("account_" + user.status);
|
||||
n.addClass("account_" + user.status);
|
||||
n2.addClass("account_" + user.status);
|
||||
|
||||
n.attr('data-email', user.email);
|
||||
n.attr('data-quota', user.quota);
|
||||
n.find('.address').text(user.email);
|
||||
n.find('.box-count').text((user.box_count).toLocaleString('en'));
|
||||
if (user.box_count == '?') {
|
||||
n.find('.box-count').attr('title', 'Message count is unkown')
|
||||
}
|
||||
n.find('.box-size').text(user.box_size);
|
||||
if (user.box_size == '?') {
|
||||
n.find('.box-size').attr('title', 'Mailbox size is unkown')
|
||||
}
|
||||
n.find('.percent').text(user.percent);
|
||||
n.find('.quota').text((user.quota == '0') ? 'unlimited' : user.quota);
|
||||
n2.find('.restore_info tt').text(user.mailbox);
|
||||
n.attr('data-email', user.email);
|
||||
n.attr('data-quota', user.quota);
|
||||
n.find('.address').text(user.email);
|
||||
n.find('.box-count').text((user.box_count).toLocaleString('en'));
|
||||
if (user.box_count == '?') {
|
||||
n.find('.box-count').attr('title', 'Message count is unkown')
|
||||
}
|
||||
n.find('.box-size').text(user.box_size);
|
||||
if (user.box_size == '?') {
|
||||
n.find('.box-size').attr('title', 'Mailbox size is unkown')
|
||||
}
|
||||
n.find('.percent').text(user.percent);
|
||||
n.find('.quota').text((user.quota == '0') ? 'unlimited' : user.quota);
|
||||
n2.find('.restore_info tt').text(user.mailbox);
|
||||
|
||||
if (user.status == 'inactive') continue;
|
||||
if (user.status == 'inactive') continue;
|
||||
|
||||
var add_privs = ["admin"];
|
||||
var add_privs = ["admin"];
|
||||
|
||||
for (var j = 0; j < user.privileges.length; j++) {
|
||||
var p = $("<span><b><span class='name'></span></b> (<a href='#' onclick='mod_priv(this, \"remove\"); return false;' title='Remove Privilege'>remove privilege</a>) |</span>");
|
||||
p.find('span.name').text(user.privileges[j]);
|
||||
n.find('.privs').append(p);
|
||||
if (add_privs.indexOf(user.privileges[j]) >= 0)
|
||||
add_privs.splice(add_privs.indexOf(user.privileges[j]), 1);
|
||||
}
|
||||
for (var j = 0; j < user.privileges.length; j++) {
|
||||
var p = $("<span><b><span class='name'></span></b> (<a href='#' onclick='mod_priv(this, \"remove\"); return false;' title='Remove Privilege'>remove privilege</a>) |</span>");
|
||||
p.find('span.name').text(user.privileges[j]);
|
||||
n.find('.privs').append(p);
|
||||
if (add_privs.indexOf(user.privileges[j]) >= 0)
|
||||
add_privs.splice(add_privs.indexOf(user.privileges[j]), 1);
|
||||
}
|
||||
|
||||
for (var j = 0; j < add_privs.length; j++) {
|
||||
var p = $("<span><a href='#' onclick='mod_priv(this, \"add\"); return false;' title='Add Privilege'>make <span class='name'></span></a> | </span>");
|
||||
p.find('span.name').text(add_privs[j]);
|
||||
n.find('.add-privs').append(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
for (var j = 0; j < add_privs.length; j++) {
|
||||
var p = $("<span><a href='#' onclick='mod_priv(this, \"add\"); return false;' title='Add Privilege'>make <span class='name'></span></a> | </span>");
|
||||
p.find('span.name').text(add_privs[j]);
|
||||
n.find('.add-privs').append(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function do_add_user() {
|
||||
var email = $("#adduserEmail").val();
|
||||
var pw = $("#adduserPassword").val();
|
||||
var privs = $("#adduserPrivs").val();
|
||||
var quota = $("#adduserQuota").val();
|
||||
api(
|
||||
"/mail/users/add",
|
||||
"POST",
|
||||
{
|
||||
email: email,
|
||||
password: pw,
|
||||
privileges: privs,
|
||||
quota: quota
|
||||
},
|
||||
function(r) {
|
||||
// Responses are multiple lines of pre-formatted text.
|
||||
show_modal_error("Add User", $("<pre/>").text(r));
|
||||
show_users()
|
||||
},
|
||||
function(r) {
|
||||
show_modal_error("Add User", r);
|
||||
});
|
||||
return false;
|
||||
}
|
||||
function do_add_user() {
|
||||
var email = $("#adduserEmail").val();
|
||||
var pw = $("#adduserPassword").val();
|
||||
var privs = $("#adduserPrivs").val();
|
||||
var quota = $("#adduserQuota").val();
|
||||
api(
|
||||
"/mail/users/add",
|
||||
"POST",
|
||||
{
|
||||
email: email,
|
||||
password: pw,
|
||||
privileges: privs,
|
||||
quota: quota
|
||||
},
|
||||
function (r) {
|
||||
// Responses are multiple lines of pre-formatted text.
|
||||
show_modal_error("Add User", $("<pre/>").text(r));
|
||||
show_users()
|
||||
},
|
||||
function (r) {
|
||||
show_modal_error("Add User", r);
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
function users_set_password(elem) {
|
||||
var email = $(elem).parents('tr').attr('data-email');
|
||||
function users_set_password(elem) {
|
||||
var email = $(elem).parents('tr').attr('data-email');
|
||||
|
||||
var yourpw = "";
|
||||
if (api_credentials != null && email == api_credentials.username)
|
||||
yourpw = "<p class='text-danger'>If you change your own password, you will be logged out of this control panel and will need to log in again.</p>";
|
||||
var yourpw = "";
|
||||
if (api_credentials != null && email == api_credentials.username)
|
||||
yourpw = "<p class='text-danger'>If you change your own password, you will be logged out of this control panel and will need to log in again.</p>";
|
||||
|
||||
show_modal_confirm(
|
||||
"Set Password",
|
||||
$("<p>Set a new password for <b>" + email + "</b>?</p> <p><label for='users_set_password_pw' style='display: block; font-weight: normal'>New Password:</label><input type='password' id='users_set_password_pw'></p><p><small>Passwords must be at least eight characters.</small>" + yourpw + "</p>"),
|
||||
"Set Password",
|
||||
function() {
|
||||
api(
|
||||
"/mail/users/password",
|
||||
"POST",
|
||||
{
|
||||
email: email,
|
||||
password: $('#users_set_password_pw').val()
|
||||
},
|
||||
function(r) {
|
||||
// Responses are multiple lines of pre-formatted text.
|
||||
show_modal_error("Set Password", $("<pre/>").text(r));
|
||||
},
|
||||
function(r) {
|
||||
show_modal_error("Set Password", r);
|
||||
});
|
||||
});
|
||||
}
|
||||
show_modal_confirm(
|
||||
"Set Password",
|
||||
$("<p>Set a new password for <b>" + email + "</b>?</p> <p><label for='users_set_password_pw' style='display: block; font-weight: normal'>New Password:</label><input type='password' id='users_set_password_pw'></p><p><small>Passwords must be at least eight characters.</small>" + yourpw + "</p>"),
|
||||
"Set Password",
|
||||
function () {
|
||||
api(
|
||||
"/mail/users/password",
|
||||
"POST",
|
||||
{
|
||||
email: email,
|
||||
password: $('#users_set_password_pw').val()
|
||||
},
|
||||
function (r) {
|
||||
// Responses are multiple lines of pre-formatted text.
|
||||
show_modal_error("Set Password", $("<pre/>").text(r));
|
||||
},
|
||||
function (r) {
|
||||
show_modal_error("Set Password", r);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function users_set_quota(elem) {
|
||||
var email = $(elem).parents('tr').attr('data-email');
|
||||
var quota = $(elem).parents('tr').attr('data-quota');
|
||||
function users_set_quota(elem) {
|
||||
var email = $(elem).parents('tr').attr('data-email');
|
||||
var quota = $(elem).parents('tr').attr('data-quota');
|
||||
|
||||
show_modal_confirm(
|
||||
"Set Quota",
|
||||
$("<p>Set quota for <b>" + email + "</b>?</p>" +
|
||||
"<p>" +
|
||||
"<label for='users_set_quota' style='display: block; font-weight: normal'>Quota:</label>" +
|
||||
"<input type='text' id='users_set_quota' value='" + quota + "'></p>" +
|
||||
"<p><small>Quotas may not contain any spaces or commas. Suffixes of G (gigabytes) and M (megabytes) are allowed.</small></p>" +
|
||||
"<p><small>For unlimited storage enter 0 (zero)</small></p>"),
|
||||
"Set Quota",
|
||||
function() {
|
||||
api(
|
||||
"/mail/users/quota",
|
||||
"POST",
|
||||
{
|
||||
email: email,
|
||||
quota: $('#users_set_quota').val()
|
||||
},
|
||||
function(r) {
|
||||
show_users();
|
||||
},
|
||||
function(r) {
|
||||
show_modal_error("Set Quota", r);
|
||||
});
|
||||
});
|
||||
}
|
||||
show_modal_confirm(
|
||||
"Set Quota",
|
||||
$("<p>Set quota for <b>" + email + "</b>?</p>" +
|
||||
"<p>" +
|
||||
"<label for='users_set_quota' style='display: block; font-weight: normal'>Quota:</label>" +
|
||||
"<input type='text' id='users_set_quota' value='" + quota + "'></p>" +
|
||||
"<p><small>Quotas may not contain any spaces or commas. Suffixes of G (gigabytes) and M (megabytes) are allowed.</small></p>" +
|
||||
"<p><small>For unlimited storage enter 0 (zero)</small></p>"),
|
||||
"Set Quota",
|
||||
function () {
|
||||
api(
|
||||
"/mail/users/quota",
|
||||
"POST",
|
||||
{
|
||||
email: email,
|
||||
quota: $('#users_set_quota').val()
|
||||
},
|
||||
function (r) {
|
||||
show_users();
|
||||
},
|
||||
function (r) {
|
||||
show_modal_error("Set Quota", r);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function users_remove(elem) {
|
||||
var email = $(elem).parents('tr').attr('data-email');
|
||||
function users_remove(elem) {
|
||||
var email = $(elem).parents('tr').attr('data-email');
|
||||
|
||||
// can't remove yourself
|
||||
if (api_credentials != null && email == api_credentials.username) {
|
||||
show_modal_error("Archive User", "You cannot archive your own account.");
|
||||
return;
|
||||
}
|
||||
// can't remove yourself
|
||||
if (api_credentials != null && email == api_credentials.username) {
|
||||
show_modal_error("Archive User", "You cannot archive your own account.");
|
||||
return;
|
||||
}
|
||||
|
||||
show_modal_confirm(
|
||||
"Archive User",
|
||||
$("<p>Are you sure you want to archive <b>" + email + "</b>?</p> <p>The user's mailboxes will not be deleted (you can do that later), but the user will no longer be able to log into any services on this machine.</p>"),
|
||||
"Archive",
|
||||
function() {
|
||||
api(
|
||||
"/mail/users/remove",
|
||||
"POST",
|
||||
{
|
||||
email: email
|
||||
},
|
||||
function(r) {
|
||||
// Responses are multiple lines of pre-formatted text.
|
||||
show_modal_error("Remove User", $("<pre/>").text(r));
|
||||
show_users();
|
||||
},
|
||||
function(r) {
|
||||
show_modal_error("Remove User", r);
|
||||
});
|
||||
});
|
||||
}
|
||||
show_modal_confirm(
|
||||
"Archive User",
|
||||
$("<p>Are you sure you want to archive <b>" + email + "</b>?</p> <p>The user's mailboxes will not be deleted (you can do that later), but the user will no longer be able to log into any services on this machine.</p>"),
|
||||
"Archive",
|
||||
function () {
|
||||
api(
|
||||
"/mail/users/remove",
|
||||
"POST",
|
||||
{
|
||||
email: email
|
||||
},
|
||||
function (r) {
|
||||
// Responses are multiple lines of pre-formatted text.
|
||||
show_modal_error("Remove User", $("<pre/>").text(r));
|
||||
show_users();
|
||||
},
|
||||
function (r) {
|
||||
show_modal_error("Remove User", r);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function mod_priv(elem, add_remove) {
|
||||
var email = $(elem).parents('tr').attr('data-email');
|
||||
var priv = $(elem).parents('td').find('.name').text();
|
||||
function mod_priv(elem, add_remove) {
|
||||
var email = $(elem).parents('tr').attr('data-email');
|
||||
var priv = $(elem).parents('td').find('.name').text();
|
||||
|
||||
// can't remove your own admin access
|
||||
if (priv == "admin" && add_remove == "remove" && api_credentials != null && email == api_credentials.username) {
|
||||
show_modal_error("Modify Privileges", "You cannot remove the admin privilege from yourself.");
|
||||
return;
|
||||
}
|
||||
// can't remove your own admin access
|
||||
if (priv == "admin" && add_remove == "remove" && api_credentials != null && email == api_credentials.username) {
|
||||
show_modal_error("Modify Privileges", "You cannot remove the admin privilege from yourself.");
|
||||
return;
|
||||
}
|
||||
|
||||
var add_remove1 = add_remove.charAt(0).toUpperCase() + add_remove.substring(1);
|
||||
show_modal_confirm(
|
||||
"Modify Privileges",
|
||||
$("<p>Are you sure you want to " + add_remove + " the " + priv + " privilege for <b>" + email + "</b>?</p>"),
|
||||
add_remove1,
|
||||
function() {
|
||||
api(
|
||||
"/mail/users/privileges/" + add_remove,
|
||||
"POST",
|
||||
{
|
||||
email: email,
|
||||
privilege: priv
|
||||
},
|
||||
function(r) {
|
||||
show_users();
|
||||
});
|
||||
});
|
||||
}
|
||||
var add_remove1 = add_remove.charAt(0).toUpperCase() + add_remove.substring(1);
|
||||
show_modal_confirm(
|
||||
"Modify Privileges",
|
||||
$("<p>Are you sure you want to " + add_remove + " the " + priv + " privilege for <b>" + email + "</b>?</p>"),
|
||||
add_remove1,
|
||||
function () {
|
||||
api(
|
||||
"/mail/users/privileges/" + add_remove,
|
||||
"POST",
|
||||
{
|
||||
email: email,
|
||||
privilege: priv
|
||||
},
|
||||
function (r) {
|
||||
show_users();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function generate_random_password() {
|
||||
var pw = "";
|
||||
var charset = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789"; // confusable characters skipped
|
||||
for (var i = 0; i < 12; i++)
|
||||
pw += charset.charAt(Math.floor(Math.random() * charset.length));
|
||||
show_modal_error("Random Password", "<p>Here, try this:</p> <p><code style='font-size: 110%'>" + pw + "</code></p>");
|
||||
return false; // cancel click
|
||||
}
|
||||
function generate_random_password() {
|
||||
var pw = "";
|
||||
var charset = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789"; // confusable characters skipped
|
||||
for (var i = 0; i < 12; i++)
|
||||
pw += charset.charAt(Math.floor(Math.random() * charset.length));
|
||||
show_modal_error("Random Password", "<p>Here, try this:</p> <p><code style='font-size: 110%'>" + pw + "</code></p>");
|
||||
return false; // cancel click
|
||||
}
|
||||
</script>
|
||||
|
|
|
@ -3,87 +3,101 @@
|
|||
|
||||
<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’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’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>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Site</th>
|
||||
<th>Directory for Files</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
</tbody>
|
||||
</table>
|
||||
<table id="web_domains_existing" class="table col-12" style="margin-bottom: 1em;">
|
||||
<caption></caption>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Site</th>
|
||||
<th>Directory for Files</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>
|
||||
|
||||
<script>
|
||||
function show_web() {
|
||||
api(
|
||||
"/web/domains",
|
||||
"GET",
|
||||
{
|
||||
},
|
||||
function(domains) {
|
||||
var tb = $('#web_domains_existing tbody');
|
||||
tb.text('');
|
||||
for (var i = 0; i < domains.length; i++) {
|
||||
if (!domains[i].static_enabled) continue;
|
||||
var row = $("<tr><th class='domain'><a href=''></a></th><td class='directory'><tt/></td> <td class='change-root hidden'><button class='btn btn-default btn-xs' onclick='show_change_web_root(this)'>Change</button></td></tr>");
|
||||
tb.append(row);
|
||||
row.attr('data-domain', domains[i].domain);
|
||||
row.attr('data-custom-web-root', domains[i].custom_root);
|
||||
row.find('.domain a').text('https://' + domains[i].domain);
|
||||
row.find('.domain a').attr('href', 'https://' + domains[i].domain);
|
||||
row.find('.directory tt').text(domains[i].root);
|
||||
if (domains[i].root != domains[i].custom_root)
|
||||
row.find('.change-root').removeClass('hidden');
|
||||
function show_web() {
|
||||
api(
|
||||
"/web/domains",
|
||||
"GET",
|
||||
{
|
||||
},
|
||||
function (domains) {
|
||||
var tb = $('#web_domains_existing tbody');
|
||||
tb.text('');
|
||||
for (var i = 0; i < domains.length; i++) {
|
||||
if (!domains[i].static_enabled) continue;
|
||||
var row = $("<tr><th class='domain'><a href=''></a></th><td class='directory'><tt/></td> <td class='change-root hidden'><button class='btn btn-default btn-xs' onclick='show_change_web_root(this)'>Change</button></td></tr>");
|
||||
tb.append(row);
|
||||
row.attr('data-domain', domains[i].domain);
|
||||
row.attr('data-custom-web-root', domains[i].custom_root);
|
||||
row.find('.domain a').text('https://' + domains[i].domain);
|
||||
row.find('.domain a').attr('href', 'https://' + domains[i].domain);
|
||||
row.find('.directory tt').text(domains[i].root);
|
||||
if (domains[i].root != domains[i].custom_root)
|
||||
row.find('.change-root').removeClass('hidden');
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
function do_web_update() {
|
||||
api(
|
||||
"/web/update",
|
||||
"POST",
|
||||
{
|
||||
},
|
||||
function (data) {
|
||||
if (data == "")
|
||||
data = "Nothing changed.";
|
||||
else
|
||||
data = $("<pre/>").text(data);
|
||||
show_modal_error("Web Update", data, function () { show_web() });
|
||||
});
|
||||
}
|
||||
|
||||
function do_web_update() {
|
||||
api(
|
||||
"/web/update",
|
||||
"POST",
|
||||
{
|
||||
},
|
||||
function(data) {
|
||||
if (data == "")
|
||||
data = "Nothing changed.";
|
||||
else
|
||||
data = $("<pre/>").text(data);
|
||||
show_modal_error("Web Update", data, function() { show_web() });
|
||||
});
|
||||
}
|
||||
|
||||
function show_change_web_root(elem) {
|
||||
var domain = $(elem).parents('tr').attr('data-domain');
|
||||
var root = $(elem).parents('tr').attr('data-custom-web-root');
|
||||
show_modal_confirm(
|
||||
'Change Root Directory for ' + domain,
|
||||
$('<p>You can change the static directory for <tt>' + domain + '</tt> to:</p> <p><tt>' + root + '</tt></p> <p>First create this directory on the server. Then click Update to scan for the directory and update web settings.</p>'),
|
||||
'Update',
|
||||
function() { do_web_update(); });
|
||||
}
|
||||
function show_change_web_root(elem) {
|
||||
var domain = $(elem).parents('tr').attr('data-domain');
|
||||
var root = $(elem).parents('tr').attr('data-custom-web-root');
|
||||
show_modal_confirm(
|
||||
'Change Root Directory for ' + domain,
|
||||
$('<p>You can change the static directory for <tt>' + domain + '</tt> to:</p> <p><tt>' + root + '</tt></p> <p>First create this directory on the server. Then click Update to scan for the directory and update web settings.</p>'),
|
||||
'Update',
|
||||
function () { do_web_update(); });
|
||||
}
|
||||
</script>
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
<style>
|
||||
#wkd_table #uids {
|
||||
white-space: pre-line;
|
||||
}
|
||||
white-space: pre-line;
|
||||
}
|
||||
|
||||
#wkd_table .domain-header {
|
||||
margin-top: 0.5em;
|
||||
|
@ -59,7 +59,8 @@
|
|||
|
||||
<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>
|
||||
|
@ -70,7 +71,8 @@
|
|||
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
|
||||
|
@ -89,7 +91,8 @@
|
|||
<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();">
|
||||
<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>
|
||||
|
@ -98,8 +101,8 @@
|
|||
<caption></caption>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Email Address</th>
|
||||
<th></th>
|
||||
<th>Email Address</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="wkd_tbody">
|
||||
|
@ -151,7 +154,7 @@
|
|||
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.click(()=>{
|
||||
option.click(() => {
|
||||
$("#wkd_submit").attr("disabled", false)
|
||||
dirty_config[email] = key
|
||||
menurep.find("#current-key").html(option.html())
|
||||
|
@ -233,7 +236,7 @@
|
|||
template.remove()
|
||||
|
||||
let nokeyopt = menurep.find("#key-none")
|
||||
nokeyopt.click(()=>{
|
||||
nokeyopt.click(() => {
|
||||
$("#wkd_submit").attr("disabled", false)
|
||||
dirty_config[email] = null
|
||||
menurep.find("#current-key").html(nokeyopt.html())
|
||||
|
@ -285,14 +288,14 @@
|
|||
"POST",
|
||||
dirty_config,
|
||||
(r) => {
|
||||
show_modal_error("WKD Management", $("<p/>").text(r), () => {if (r == "OK") show_wkd()})
|
||||
show_modal_error("WKD Management", $("<p/>").text(r), () => { if (r == "OK") show_wkd() })
|
||||
},
|
||||
(r) => {
|
||||
show_modal_error("WKD Management", $("<p/>").text(r))
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
function toggle_emails_with_no_pgp_key() {
|
||||
let show_toggleable_lines = document.getElementById("wkd-show-all-entries").checked
|
||||
|
||||
|
|
|
@ -6,207 +6,241 @@ 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")
|
||||
# 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))
|
||||
return env
|
||||
# Load settings from a KEY=VALUE file.
|
||||
import collections
|
||||
env = collections.OrderedDict()
|
||||
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))
|
||||
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))
|
||||
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
|
||||
return config
|
||||
except:
|
||||
return { }
|
||||
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
|
||||
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='')
|
||||
# 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.
|
||||
# Put domain names in a nice sorted order.
|
||||
|
||||
# The nice order will group domain names by DNS zone, i.e. the top-most
|
||||
# domain name that we serve that ecompasses a set of subdomains. Map
|
||||
# each of the domain names to the zone that contains them. Walk the domains
|
||||
# from shortest to longest since zones are always shorter than their
|
||||
# subdomains.
|
||||
zones = { }
|
||||
for domain in sorted(domain_names, key=lambda d : len(d)):
|
||||
for z in zones.values():
|
||||
if domain.endswith("." + z):
|
||||
# We found a parent domain already in the list.
|
||||
zones[domain] = z
|
||||
break
|
||||
else:
|
||||
# 'break' did not occur: there is no parent domain, so it is its
|
||||
# own zone.
|
||||
zones[domain] = domain
|
||||
# The nice order will group domain names by DNS zone, i.e. the top-most
|
||||
# domain name that we serve that ecompasses a set of subdomains. Map
|
||||
# each of the domain names to the zone that contains them. Walk the domains
|
||||
# from shortest to longest since zones are always shorter than their
|
||||
# subdomains.
|
||||
zones = {}
|
||||
for domain in sorted(domain_names, key=lambda d: len(d)):
|
||||
for z in zones.values():
|
||||
if domain.endswith("." + z):
|
||||
# We found a parent domain already in the list.
|
||||
zones[domain] = z
|
||||
break
|
||||
else:
|
||||
# 'break' did not occur: there is no parent domain, so it is its
|
||||
# own zone.
|
||||
zones[domain] = domain
|
||||
|
||||
# Sort the zones.
|
||||
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)),
|
||||
# Sort the zones.
|
||||
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)),
|
||||
|
||||
# Then just dumb lexicographically.
|
||||
d,
|
||||
))
|
||||
# Then just dumb lexicographically.
|
||||
d,
|
||||
))
|
||||
|
||||
# Now sort the domain names that fall within each zone.
|
||||
domain_names = sorted(domain_names,
|
||||
key = lambda d : (
|
||||
# First by zone.
|
||||
zone_domains.index(zones[d]),
|
||||
# Now sort the domain names that fall within each zone.
|
||||
domain_names = sorted(
|
||||
domain_names,
|
||||
key=lambda d: (
|
||||
# First by zone.
|
||||
zone_domains.index(zones[d]),
|
||||
|
||||
# PRIMARY_HOSTNAME is always first within the zone that contains it.
|
||||
d != env['PRIMARY_HOSTNAME'],
|
||||
# PRIMARY_HOSTNAME is always first within the zone that contains it.
|
||||
d != env['PRIMARY_HOSTNAME'],
|
||||
|
||||
# Followed by any of its subdomains.
|
||||
not d.endswith("." + env['PRIMARY_HOSTNAME']),
|
||||
# Followed by any of its subdomains.
|
||||
not d.endswith("." + env['PRIMARY_HOSTNAME']),
|
||||
|
||||
# Then in right-to-left lexicographic order of the .-separated parts of the name.
|
||||
list(reversed(d.split("."))),
|
||||
))
|
||||
# Then in right-to-left lexicographic order of the .-separated parts of the name.
|
||||
list(reversed(d.split("."))),
|
||||
))
|
||||
|
||||
return domain_names
|
||||
|
||||
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)
|
||||
ret = []
|
||||
for domain in sort_domains(domains, env):
|
||||
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
|
||||
email_addresses = set(email_addresses)
|
||||
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))
|
||||
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):
|
||||
# A safe way to execute processes.
|
||||
# Some processes like apt-get require being given a sane PATH.
|
||||
import subprocess
|
||||
|
||||
env.update({ "PATH": "/sbin:/bin:/usr/sbin:/usr/bin" })
|
||||
kwargs = {
|
||||
'env': env,
|
||||
'stderr': None if not capture_stderr else subprocess.STDOUT,
|
||||
}
|
||||
if method == "check_output" and input is not None:
|
||||
kwargs['input'] = input
|
||||
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
|
||||
|
||||
env.update({"PATH": "/sbin:/bin:/usr/sbin:/usr/bin"})
|
||||
kwargs = {
|
||||
'env': env,
|
||||
'stderr': None if not capture_stderr else subprocess.STDOUT,
|
||||
}
|
||||
if method == "check_output" and input is not None:
|
||||
kwargs['input'] = input
|
||||
|
||||
if not trap:
|
||||
ret = getattr(subprocess, method)(cmd_args, **kwargs)
|
||||
else:
|
||||
try:
|
||||
ret = getattr(subprocess, method)(cmd_args, **kwargs)
|
||||
code = 0
|
||||
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 trap:
|
||||
return ret
|
||||
else:
|
||||
return code, ret
|
||||
|
||||
if not trap:
|
||||
ret = getattr(subprocess, method)(cmd_args, **kwargs)
|
||||
else:
|
||||
try:
|
||||
ret = getattr(subprocess, method)(cmd_args, **kwargs)
|
||||
code = 0
|
||||
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 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
|
||||
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
|
||||
# soft and hard links.
|
||||
total_size = 0
|
||||
seen = set()
|
||||
for dirpath, dirnames, filenames in os.walk(path):
|
||||
for f in filenames:
|
||||
fp = os.path.join(dirpath, f)
|
||||
try:
|
||||
stat = os.lstat(fp)
|
||||
except OSError:
|
||||
continue
|
||||
if stat.st_ino in seen:
|
||||
continue
|
||||
seen.add(stat.st_ino)
|
||||
total_size += stat.st_size
|
||||
return total_size
|
||||
# Computes the size of all files in the path, like the `du` command.
|
||||
# Based on http://stackoverflow.com/a/17936789. Takes into account
|
||||
# soft and hard links.
|
||||
total_size = 0
|
||||
seen = set()
|
||||
for dirpath, dirnames, filenames in os.walk(path):
|
||||
for f in filenames:
|
||||
fp = os.path.join(dirpath, f)
|
||||
try:
|
||||
stat = os.lstat(fp)
|
||||
except OSError:
|
||||
continue
|
||||
if stat.st_ino in seen:
|
||||
continue
|
||||
seen.add(stat.st_ino)
|
||||
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, time
|
||||
start = time.perf_counter()
|
||||
while True:
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
s.settimeout(timeout/3)
|
||||
try:
|
||||
s.connect(("127.0.0.1" if not public else env['PUBLIC_IP'], port))
|
||||
return True
|
||||
except OSError:
|
||||
if time.perf_counter() > start+timeout:
|
||||
return False
|
||||
time.sleep(min(timeout/4, 1))
|
||||
# Block until a service on a given port (bound privately or publicly)
|
||||
# is taking connections, with a maximum timeout.
|
||||
import socket
|
||||
import time
|
||||
start = time.perf_counter()
|
||||
while True:
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
s.settimeout(timeout / 3)
|
||||
try:
|
||||
s.connect(("127.0.0.1" if not public else env['PUBLIC_IP'], port))
|
||||
return True
|
||||
except OSError:
|
||||
if time.perf_counter() > start + 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"
|
||||
# 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]
|
||||
# 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()
|
||||
version = shell("check_output", ["/usr/bin/lsb_release", "-rs"]).strip()
|
||||
|
||||
if dist == "Debian":
|
||||
if version == "10":
|
||||
return "Debian10"
|
||||
elif version == "11":
|
||||
return "Debian11"
|
||||
elif dist == "Ubuntu":
|
||||
if version == "20.04":
|
||||
return "Ubuntu2004"
|
||||
|
||||
return None
|
||||
def get_os_code():
|
||||
# Massive mess incoming
|
||||
dist = shell("check_output", ["/usr/bin/lsb_release", "-is"]).strip()
|
||||
version = shell("check_output", ["/usr/bin/lsb_release", "-rs"]).strip()
|
||||
|
||||
if dist == "Debian":
|
||||
if version == "10":
|
||||
return "Debian10"
|
||||
elif version == "11":
|
||||
return "Debian11"
|
||||
elif dist == "Ubuntu":
|
||||
if version == "20.04":
|
||||
return "Ubuntu2004"
|
||||
|
||||
return None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from web_update import get_web_domains
|
||||
env = load_environment()
|
||||
domains = get_web_domains(env)
|
||||
for domain in domains:
|
||||
print(domain)
|
||||
from web_update import get_web_domains
|
||||
env = load_environment()
|
||||
domains = get_web_domains(env)
|
||||
for domain in domains:
|
||||
print(domain)
|
||||
|
|
|
@ -2,14 +2,20 @@
|
|||
# domains for which a mail account has been set up.
|
||||
########################################################################
|
||||
|
||||
import os.path, re, rtyaml
|
||||
import os.path
|
||||
import re
|
||||
import 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()
|
||||
|
||||
|
@ -28,14 +34,20 @@ def get_web_domains(env, include_www_redirects=True, include_auto=True, exclude_
|
|||
# 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
|
||||
|
@ -52,34 +64,41 @@ def get_web_domains(env, include_www_redirects=True, include_auto=True, exclude_
|
|||
|
||||
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.
|
||||
root_overrides = { }
|
||||
root_overrides = {}
|
||||
nginx_conf_custom_fn = os.path.join(env["STORAGE_ROOT"], "www/custom.yaml")
|
||||
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)
|
||||
|
@ -108,19 +127,24 @@ def get_web_domain_flags(env):
|
|||
# Last check for websites hosted elsewhere
|
||||
for d in flags.keys():
|
||||
if d in external:
|
||||
flags[d] = DOMAIN_EXTERNAL # -1 = All bits set to 1, assuming twos-complement
|
||||
# -1 = All bits set to 1, assuming twos-complement
|
||||
flags[d] = DOMAIN_EXTERNAL
|
||||
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([
|
||||
|
@ -133,20 +157,29 @@ 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())
|
||||
|
||||
# Sort the domains in some way to keep ordering consistency. Keep domains and subdomains together.
|
||||
pairs.sort(reverse = False, key = lambda x: x[0][::-1])
|
||||
pairs.sort(reverse=False, key=lambda x: x[0][::-1])
|
||||
for domain, flags in pairs:
|
||||
if flags & DOMAIN_PRIMARY == DOMAIN_PRIMARY or flags == DOMAIN_EXTERNAL:
|
||||
# PRIMARY_HOSTNAME is handled above.
|
||||
|
@ -154,14 +187,20 @@ 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"
|
||||
|
@ -182,6 +221,7 @@ def do_web_update(env):
|
|||
|
||||
return "web updated\n"
|
||||
|
||||
|
||||
def make_domain_config(domain, templates, ssl_certificates, env):
|
||||
# GET SOME VARIABLES
|
||||
|
||||
|
@ -206,7 +246,9 @@ 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"
|
||||
|
@ -251,7 +293,8 @@ 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)
|
||||
|
@ -263,7 +306,9 @@ 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([
|
||||
|
@ -280,57 +325,75 @@ 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)
|
||||
except OSError: # PRIMARY_HOSTNAME cert is missing
|
||||
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)]
|
||||
|
|
|
@ -2,7 +2,14 @@
|
|||
# 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, utils, rtyaml, mailconfig, copy, shutil, os, re
|
||||
import pgp
|
||||
import utils
|
||||
import rtyaml
|
||||
import mailconfig
|
||||
import copy
|
||||
import shutil
|
||||
import os
|
||||
import re
|
||||
from cryptography.hazmat.primitives import hashes
|
||||
from cryptography.hazmat.backends import default_backend
|
||||
|
||||
|
@ -10,32 +17,36 @@ 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()
|
||||
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:
|
||||
raise ValueError("Digest cannot have incomplete chunks of 40 bits!")
|
||||
base = "ybndrfg8ejkmcpqxot1uwisza345h769"
|
||||
encoded = ""
|
||||
for i in range(0, len(digest), 5):
|
||||
chunk = int.from_bytes(digest[i:i+5], byteorder="big")
|
||||
for j in range(35, -5, -5):
|
||||
encoded += base[(chunk >> j) & 31]
|
||||
return encoded
|
||||
# Crudely check if all quintets are complete
|
||||
if len(digest) % 5 != 0:
|
||||
raise ValueError("Digest cannot have incomplete chunks of 40 bits!")
|
||||
base = "ybndrfg8ejkmcpqxot1uwisza345h769"
|
||||
encoded = ""
|
||||
for i in range(0, len(digest), 5):
|
||||
chunk = int.from_bytes(digest[i:i + 5], byteorder="big")
|
||||
for j in range(35, -5, -5):
|
||||
encoded += base[(chunk >> j) & 31]
|
||||
return encoded
|
||||
|
||||
|
||||
# Strips and exports a key so that only the UID's with the provided email remain.
|
||||
|
@ -51,17 +62,13 @@ def zbase32(digest):
|
|||
# by the pgp.fork_context() decorator.
|
||||
@pgp.fork_context
|
||||
def strip_and_export(fpr, target_email, buffer=None, context=None):
|
||||
context.armor = False # We need to disable armor output for this key
|
||||
context.armor = False # We need to disable armor output for this key
|
||||
k = pgp.get_key(fpr, context)
|
||||
if k is 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]),.*"
|
||||
|
@ -85,13 +92,12 @@ 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
|
||||
elif request == "GET_BOOL":
|
||||
# No way to confirm interactively, so we just say yes
|
||||
return "y" # Yeah, I'd also rather just return True but that doesn't work
|
||||
return "y" # Yeah, I'd also rather just return True but that doesn't work
|
||||
elif request == "GET_LINE" and prompt == "keyedit.prompt":
|
||||
if not statusref["seq_read"]:
|
||||
buffer.seek(0, os.SEEK_SET)
|
||||
|
@ -108,6 +114,7 @@ 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):
|
||||
|
@ -121,13 +128,18 @@ 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):
|
||||
|
@ -141,7 +153,10 @@ def get_user_fpr_maps():
|
|||
pass
|
||||
return uk_maps
|
||||
|
||||
|
||||
# Gets the current WKD configuration
|
||||
|
||||
|
||||
def get_wkd_config():
|
||||
# Test
|
||||
try:
|
||||
|
@ -159,9 +174,12 @@ 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():
|
||||
|
@ -177,8 +195,11 @@ 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 = []
|
||||
|
@ -198,7 +219,8 @@ def parse_wkd_list():
|
|||
key = email_compatible_with_key(u, k)
|
||||
# Key is compatible
|
||||
|
||||
writeable[u] = key.fpr # Swap with the full-length fingerprint (if somehow this was changed by hand)
|
||||
# Swap with the full-length fingerprint (if somehow this was changed by hand)
|
||||
writeable[u] = key.fpr
|
||||
uidlist.append((u, key.fpr))
|
||||
except:
|
||||
writeable.pop(u)
|
||||
|
@ -208,8 +230,10 @@ def parse_wkd_list():
|
|||
wkdfile.write(rtyaml.dump(writeable))
|
||||
return (removed, uidlist)
|
||||
|
||||
|
||||
WKD_LOCATION = "/var/lib/mailinabox/wkd/"
|
||||
|
||||
|
||||
def build_wkd():
|
||||
# Clean everything
|
||||
try:
|
||||
|
|
Loading…
Reference in a new issue