2016-04-13 21:52:13 +00:00
|
|
|
import os, os.path, re, json, time
|
2016-01-14 03:20:33 +00:00
|
|
|
import subprocess
|
2016-04-13 21:52:13 +00:00
|
|
|
|
2014-08-17 22:43:57 +00:00
|
|
|
from functools import wraps
|
|
|
|
|
2016-01-14 03:20:33 +00:00
|
|
|
from flask import Flask, request, render_template, abort, Response, send_from_directory, make_response
|
2014-06-03 13:24:48 +00:00
|
|
|
|
2016-02-23 05:32:01 +00:00
|
|
|
import auth, utils, multiprocessing.pool
|
2014-10-07 19:47:30 +00:00
|
|
|
from mailconfig import get_mail_users, get_mail_users_ex, get_admins, add_mail_user, set_mail_password, remove_mail_user
|
2014-08-08 12:31:22 +00:00
|
|
|
from mailconfig import get_mail_user_privileges, add_remove_mail_user_privilege
|
2014-10-07 19:47:30 +00:00
|
|
|
from mailconfig import get_mail_aliases, get_mail_aliases_ex, get_mail_domains, add_mail_alias, remove_mail_alias
|
2014-06-03 13:24:48 +00:00
|
|
|
|
2014-06-03 20:21:17 +00:00
|
|
|
env = utils.load_environment()
|
|
|
|
|
2014-06-22 12:55:19 +00:00
|
|
|
auth_service = auth.KeyAuthService()
|
2014-06-21 23:42:48 +00:00
|
|
|
|
2014-08-17 22:43:57 +00:00
|
|
|
# We may deploy via a symbolic link, which confuses flask's template finding.
|
|
|
|
me = __file__
|
|
|
|
try:
|
|
|
|
me = os.readlink(__file__)
|
|
|
|
except OSError:
|
|
|
|
pass
|
|
|
|
|
2015-12-26 16:48:23 +00:00
|
|
|
# for generating CSRs we need a list of country codes
|
|
|
|
csr_country_codes = []
|
|
|
|
with open(os.path.join(os.path.dirname(me), "csr_country_codes.tsv")) as f:
|
|
|
|
for line in f:
|
|
|
|
if line.strip() == "" or line.startswith("#"): continue
|
|
|
|
code, name = line.strip().split("\t")[0:2]
|
|
|
|
csr_country_codes.append((code, name))
|
|
|
|
|
2014-08-17 22:43:57 +00:00
|
|
|
app = Flask(__name__, template_folder=os.path.abspath(os.path.join(os.path.dirname(me), "templates")))
|
|
|
|
|
2014-11-30 15:43:07 +00:00
|
|
|
# Decorator to protect views that require a user with 'admin' privileges.
|
2014-08-17 22:43:57 +00:00
|
|
|
def authorized_personnel_only(viewfunc):
|
|
|
|
@wraps(viewfunc)
|
|
|
|
def newview(*args, **kwargs):
|
2014-11-30 15:43:07 +00:00
|
|
|
# Authenticate the passed credentials, which is either the API key or a username:password pair.
|
|
|
|
error = None
|
|
|
|
try:
|
2014-12-01 19:20:46 +00:00
|
|
|
email, privs = auth_service.authenticate(request, env)
|
2014-11-30 15:43:07 +00:00
|
|
|
except ValueError as e:
|
|
|
|
# Authentication failed.
|
|
|
|
privs = []
|
2016-03-26 13:06:43 +00:00
|
|
|
error = "Incorrect username or password"
|
2014-11-30 15:43:07 +00:00
|
|
|
|
2016-04-13 21:52:13 +00:00
|
|
|
# Write a line in the log recording the failed login
|
|
|
|
log_failed_login(request)
|
|
|
|
|
2014-11-30 15:43:07 +00:00
|
|
|
# Authorized to access an API view?
|
|
|
|
if "admin" in privs:
|
2015-06-27 17:23:15 +00:00
|
|
|
# Call view func.
|
2014-08-17 22:43:57 +00:00
|
|
|
return viewfunc(*args, **kwargs)
|
2014-11-30 15:43:07 +00:00
|
|
|
elif not error:
|
|
|
|
error = "You are not an administrator."
|
2014-08-17 22:43:57 +00:00
|
|
|
|
|
|
|
# Not authorized. Return a 401 (send auth) and a prompt to authorize by default.
|
|
|
|
status = 401
|
2014-11-30 15:43:07 +00:00
|
|
|
headers = {
|
|
|
|
'WWW-Authenticate': 'Basic realm="{0}"'.format(auth_service.auth_realm),
|
|
|
|
'X-Reason': error,
|
|
|
|
}
|
2014-08-17 22:43:57 +00:00
|
|
|
|
|
|
|
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
|
|
|
|
# Don't issue a 401 to an AJAX request because the user will
|
|
|
|
# be prompted for credentials, which is not helpful.
|
|
|
|
status = 403
|
|
|
|
headers = None
|
|
|
|
|
|
|
|
if request.headers.get('Accept') in (None, "", "*/*"):
|
|
|
|
# Return plain text output.
|
2014-11-30 15:43:07 +00:00
|
|
|
return Response(error+"\n", status=status, mimetype='text/plain', headers=headers)
|
2014-08-17 22:43:57 +00:00
|
|
|
else:
|
|
|
|
# Return JSON output.
|
|
|
|
return Response(json.dumps({
|
|
|
|
"status": "error",
|
2014-11-30 15:43:07 +00:00
|
|
|
"reason": error,
|
|
|
|
})+"\n", status=status, mimetype='application/json', headers=headers)
|
2014-08-17 22:43:57 +00:00
|
|
|
|
|
|
|
return newview
|
2014-06-21 23:42:48 +00:00
|
|
|
|
|
|
|
@app.errorhandler(401)
|
|
|
|
def unauthorized(error):
|
|
|
|
return auth_service.make_unauthorized_response()
|
|
|
|
|
2014-08-17 22:43:57 +00:00
|
|
|
def json_response(data):
|
2015-05-03 12:53:09 +00:00
|
|
|
return Response(json.dumps(data, indent=2, sort_keys=True)+'\n', status=200, mimetype='application/json')
|
2014-08-17 22:43:57 +00:00
|
|
|
|
|
|
|
###################################
|
|
|
|
|
|
|
|
# Control Panel (unauthenticated views)
|
|
|
|
|
2014-06-03 13:24:48 +00:00
|
|
|
@app.route('/')
|
|
|
|
def index():
|
2014-08-17 22:43:57 +00:00
|
|
|
# Render the control panel. This route does not require user authentication
|
|
|
|
# so it must be safe!
|
2015-08-09 18:25:26 +00:00
|
|
|
|
2015-04-28 11:11:41 +00:00
|
|
|
no_users_exist = (len(get_mail_users(env)) == 0)
|
2014-10-07 19:28:07 +00:00
|
|
|
no_admins_exist = (len(get_admins(env)) == 0)
|
2015-08-09 18:25:26 +00:00
|
|
|
|
2015-11-26 14:47:49 +00:00
|
|
|
utils.fix_boto() # must call prior to importing boto
|
2015-08-09 18:25:26 +00:00
|
|
|
import boto.s3
|
|
|
|
backup_s3_hosts = [(r.name, r.endpoint) for r in boto.s3.regions()]
|
|
|
|
|
2014-08-17 22:43:57 +00:00
|
|
|
return render_template('index.html',
|
|
|
|
hostname=env['PRIMARY_HOSTNAME'],
|
2014-10-07 16:05:38 +00:00
|
|
|
storage_root=env['STORAGE_ROOT'],
|
2015-12-26 16:48:23 +00:00
|
|
|
|
2015-04-28 11:11:41 +00:00
|
|
|
no_users_exist=no_users_exist,
|
2014-08-26 11:31:45 +00:00
|
|
|
no_admins_exist=no_admins_exist,
|
2015-12-26 16:48:23 +00:00
|
|
|
|
2015-08-09 18:25:26 +00:00
|
|
|
backup_s3_hosts=backup_s3_hosts,
|
2015-12-26 16:48:23 +00:00
|
|
|
csr_country_codes=csr_country_codes,
|
2014-08-17 22:43:57 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
@app.route('/me')
|
|
|
|
def me():
|
|
|
|
# Is the caller authorized?
|
2014-11-30 15:43:07 +00:00
|
|
|
try:
|
2014-12-01 19:20:46 +00:00
|
|
|
email, privs = auth_service.authenticate(request, env)
|
2014-11-30 15:43:07 +00:00
|
|
|
except ValueError as e:
|
2016-04-13 21:52:13 +00:00
|
|
|
# Log the failed login
|
|
|
|
log_failed_login(request)
|
|
|
|
|
2014-08-17 22:43:57 +00:00
|
|
|
return json_response({
|
2014-11-30 15:43:07 +00:00
|
|
|
"status": "invalid",
|
2016-03-26 13:06:43 +00:00
|
|
|
"reason": "Incorrect username or password",
|
2014-08-17 22:43:57 +00:00
|
|
|
})
|
2014-11-30 15:43:07 +00:00
|
|
|
|
|
|
|
resp = {
|
|
|
|
"status": "ok",
|
2014-12-01 19:20:46 +00:00
|
|
|
"email": email,
|
2014-11-30 15:43:07 +00:00
|
|
|
"privileges": privs,
|
|
|
|
}
|
|
|
|
|
2014-12-01 19:20:46 +00:00
|
|
|
# Is authorized as admin? Return an API key for future use.
|
2014-11-30 15:43:07 +00:00
|
|
|
if "admin" in privs:
|
2015-06-06 12:33:31 +00:00
|
|
|
resp["api_key"] = auth_service.create_user_key(email, env)
|
2014-11-30 15:43:07 +00:00
|
|
|
|
|
|
|
# Return.
|
|
|
|
return json_response(resp)
|
2014-06-03 13:24:48 +00:00
|
|
|
|
|
|
|
# MAIL
|
|
|
|
|
|
|
|
@app.route('/mail/users')
|
2014-08-17 22:43:57 +00:00
|
|
|
@authorized_personnel_only
|
2014-06-03 13:24:48 +00:00
|
|
|
def mail_users():
|
2014-08-08 12:31:22 +00:00
|
|
|
if request.args.get("format", "") == "json":
|
2018-11-30 14:33:24 +00:00
|
|
|
return json_response(get_mail_users_ex(env, with_archived=True))
|
2014-08-08 12:31:22 +00:00
|
|
|
else:
|
|
|
|
return "".join(x+"\n" for x in get_mail_users(env))
|
2014-06-03 13:24:48 +00:00
|
|
|
|
|
|
|
@app.route('/mail/users/add', methods=['POST'])
|
2014-08-17 22:43:57 +00:00
|
|
|
@authorized_personnel_only
|
2014-06-03 13:24:48 +00:00
|
|
|
def mail_users_add():
|
2014-09-21 17:24:01 +00:00
|
|
|
try:
|
|
|
|
return add_mail_user(request.form.get('email', ''), request.form.get('password', ''), request.form.get('privileges', ''), env)
|
|
|
|
except ValueError as e:
|
|
|
|
return (str(e), 400)
|
2014-06-03 13:24:48 +00:00
|
|
|
|
|
|
|
@app.route('/mail/users/password', methods=['POST'])
|
2014-08-17 22:43:57 +00:00
|
|
|
@authorized_personnel_only
|
2014-06-03 13:24:48 +00:00
|
|
|
def mail_users_password():
|
2014-09-21 17:24:01 +00:00
|
|
|
try:
|
|
|
|
return set_mail_password(request.form.get('email', ''), request.form.get('password', ''), env)
|
|
|
|
except ValueError as e:
|
|
|
|
return (str(e), 400)
|
2014-06-03 13:24:48 +00:00
|
|
|
|
|
|
|
@app.route('/mail/users/remove', methods=['POST'])
|
2014-08-17 22:43:57 +00:00
|
|
|
@authorized_personnel_only
|
2014-06-03 13:24:48 +00:00
|
|
|
def mail_users_remove():
|
|
|
|
return remove_mail_user(request.form.get('email', ''), env)
|
|
|
|
|
2014-08-08 12:31:22 +00:00
|
|
|
|
|
|
|
@app.route('/mail/users/privileges')
|
2014-08-17 22:43:57 +00:00
|
|
|
@authorized_personnel_only
|
2014-08-08 12:31:22 +00:00
|
|
|
def mail_user_privs():
|
|
|
|
privs = get_mail_user_privileges(request.args.get('email', ''), env)
|
|
|
|
if isinstance(privs, tuple): return privs # error
|
|
|
|
return "\n".join(privs)
|
|
|
|
|
|
|
|
@app.route('/mail/users/privileges/add', methods=['POST'])
|
2014-08-17 22:43:57 +00:00
|
|
|
@authorized_personnel_only
|
2014-08-08 12:31:22 +00:00
|
|
|
def mail_user_privs_add():
|
|
|
|
return add_remove_mail_user_privilege(request.form.get('email', ''), request.form.get('privilege', ''), "add", env)
|
|
|
|
|
|
|
|
@app.route('/mail/users/privileges/remove', methods=['POST'])
|
2014-08-17 22:43:57 +00:00
|
|
|
@authorized_personnel_only
|
2014-08-08 12:31:22 +00:00
|
|
|
def mail_user_privs_remove():
|
|
|
|
return add_remove_mail_user_privilege(request.form.get('email', ''), request.form.get('privilege', ''), "remove", env)
|
|
|
|
|
|
|
|
|
2014-06-03 13:24:48 +00:00
|
|
|
@app.route('/mail/aliases')
|
2014-08-17 22:43:57 +00:00
|
|
|
@authorized_personnel_only
|
2014-06-03 13:24:48 +00:00
|
|
|
def mail_aliases():
|
2014-08-17 22:43:57 +00:00
|
|
|
if request.args.get("format", "") == "json":
|
2014-10-07 19:47:30 +00:00
|
|
|
return json_response(get_mail_aliases_ex(env))
|
2014-08-17 22:43:57 +00:00
|
|
|
else:
|
2015-08-14 23:05:08 +00:00
|
|
|
return "".join(address+"\t"+receivers+"\t"+(senders or "")+"\n" for address, receivers, senders in get_mail_aliases(env))
|
2014-06-03 13:24:48 +00:00
|
|
|
|
|
|
|
@app.route('/mail/aliases/add', methods=['POST'])
|
2014-08-17 22:43:57 +00:00
|
|
|
@authorized_personnel_only
|
2014-06-03 13:24:48 +00:00
|
|
|
def mail_aliases_add():
|
2014-08-17 22:43:57 +00:00
|
|
|
return add_mail_alias(
|
2015-07-04 15:31:11 +00:00
|
|
|
request.form.get('address', ''),
|
2015-08-14 23:05:08 +00:00
|
|
|
request.form.get('forwards_to', ''),
|
|
|
|
request.form.get('permitted_senders', ''),
|
2014-08-17 22:43:57 +00:00
|
|
|
env,
|
|
|
|
update_if_exists=(request.form.get('update_if_exists', '') == '1')
|
|
|
|
)
|
2014-06-03 13:24:48 +00:00
|
|
|
|
|
|
|
@app.route('/mail/aliases/remove', methods=['POST'])
|
2014-08-17 22:43:57 +00:00
|
|
|
@authorized_personnel_only
|
2014-06-03 13:24:48 +00:00
|
|
|
def mail_aliases_remove():
|
2015-07-04 20:40:19 +00:00
|
|
|
return remove_mail_alias(request.form.get('address', ''), env)
|
2014-06-03 13:24:48 +00:00
|
|
|
|
|
|
|
@app.route('/mail/domains')
|
2014-08-17 22:43:57 +00:00
|
|
|
@authorized_personnel_only
|
2014-06-03 13:24:48 +00:00
|
|
|
def mail_domains():
|
|
|
|
return "".join(x+"\n" for x in get_mail_domains(env))
|
|
|
|
|
|
|
|
# DNS
|
|
|
|
|
2014-12-21 16:31:10 +00:00
|
|
|
@app.route('/dns/zones')
|
|
|
|
@authorized_personnel_only
|
|
|
|
def dns_zones():
|
|
|
|
from dns_update import get_dns_zones
|
|
|
|
return json_response([z[0] for z in get_dns_zones(env)])
|
|
|
|
|
2014-06-03 13:24:48 +00:00
|
|
|
@app.route('/dns/update', methods=['POST'])
|
2014-08-17 22:43:57 +00:00
|
|
|
@authorized_personnel_only
|
2014-06-03 13:24:48 +00:00
|
|
|
def dns_update():
|
|
|
|
from dns_update import do_dns_update
|
2014-06-17 22:21:12 +00:00
|
|
|
try:
|
2014-08-01 12:05:34 +00:00
|
|
|
return do_dns_update(env, force=request.form.get('force', '') == '1')
|
2014-06-17 22:21:12 +00:00
|
|
|
except Exception as e:
|
|
|
|
return (str(e), 500)
|
|
|
|
|
2014-10-05 14:53:42 +00:00
|
|
|
@app.route('/dns/secondary-nameserver')
|
|
|
|
@authorized_personnel_only
|
|
|
|
def dns_get_secondary_nameserver():
|
2015-05-03 01:10:28 +00:00
|
|
|
from dns_update import get_custom_dns_config, get_secondary_dns
|
2015-07-10 15:42:33 +00:00
|
|
|
return json_response({ "hostnames": get_secondary_dns(get_custom_dns_config(env), mode=None) })
|
2014-10-05 14:53:42 +00:00
|
|
|
|
|
|
|
@app.route('/dns/secondary-nameserver', methods=['POST'])
|
|
|
|
@authorized_personnel_only
|
|
|
|
def dns_set_secondary_nameserver():
|
|
|
|
from dns_update import set_secondary_dns
|
|
|
|
try:
|
2015-07-10 15:42:33 +00:00
|
|
|
return set_secondary_dns([ns.strip() for ns in re.split(r"[, ]+", request.form.get('hostnames') or "") if ns.strip() != ""], env)
|
2014-10-05 14:53:42 +00:00
|
|
|
except ValueError as e:
|
|
|
|
return (str(e), 400)
|
|
|
|
|
2015-05-03 13:40:52 +00:00
|
|
|
@app.route('/dns/custom')
|
2014-12-21 16:31:10 +00:00
|
|
|
@authorized_personnel_only
|
2015-05-03 13:40:52 +00:00
|
|
|
def dns_get_records(qname=None, rtype=None):
|
2015-05-03 01:10:28 +00:00
|
|
|
from dns_update import get_custom_dns_config
|
2015-05-03 13:40:52 +00:00
|
|
|
return json_response([
|
|
|
|
{
|
2014-12-21 16:31:10 +00:00
|
|
|
"qname": r[0],
|
|
|
|
"rtype": r[1],
|
|
|
|
"value": r[2],
|
2015-05-03 13:40:52 +00:00
|
|
|
}
|
|
|
|
for r in get_custom_dns_config(env)
|
|
|
|
if r[0] != "_secondary_nameserver"
|
|
|
|
and (not qname or r[0] == qname)
|
|
|
|
and (not rtype or r[1] == rtype) ])
|
2014-10-05 14:53:42 +00:00
|
|
|
|
2015-05-03 13:40:52 +00:00
|
|
|
@app.route('/dns/custom/<qname>', methods=['GET', 'POST', 'PUT', 'DELETE'])
|
|
|
|
@app.route('/dns/custom/<qname>/<rtype>', methods=['GET', 'POST', 'PUT', 'DELETE'])
|
2014-08-23 23:03:45 +00:00
|
|
|
@authorized_personnel_only
|
2015-05-03 13:40:52 +00:00
|
|
|
def dns_set_record(qname, rtype="A"):
|
2014-08-23 23:03:45 +00:00
|
|
|
from dns_update import do_dns_update, set_custom_dns_record
|
|
|
|
try:
|
2015-05-03 13:40:52 +00:00
|
|
|
# Normalize.
|
|
|
|
rtype = rtype.upper()
|
|
|
|
|
|
|
|
# Read the record value from the request BODY, which must be
|
|
|
|
# ASCII-only. Not used with GET.
|
2018-10-17 13:27:17 +00:00
|
|
|
value = request.args.get("override_value", request.stream.read().decode("ascii", "ignore").strip())
|
2015-05-03 13:40:52 +00:00
|
|
|
|
2018-10-17 13:27:17 +00:00
|
|
|
method = request.args.get("override_method", request.method)
|
|
|
|
|
|
|
|
if method == "GET":
|
2015-05-03 13:40:52 +00:00
|
|
|
# Get the existing records matching the qname and rtype.
|
|
|
|
return dns_get_records(qname, rtype)
|
|
|
|
|
2018-10-17 13:27:17 +00:00
|
|
|
elif method in ("POST", "PUT"):
|
2015-05-03 13:40:52 +00:00
|
|
|
# There is a default value for A/AAAA records.
|
|
|
|
if rtype in ("A", "AAAA") and value == "":
|
|
|
|
value = request.environ.get("HTTP_X_FORWARDED_FOR") # normally REMOTE_ADDR but we're behind nginx as a reverse proxy
|
|
|
|
|
|
|
|
# Cannot add empty records.
|
|
|
|
if value == '':
|
|
|
|
return ("No value for the record provided.", 400)
|
|
|
|
|
2018-10-17 13:27:17 +00:00
|
|
|
if method == "POST":
|
2015-05-03 13:40:52 +00:00
|
|
|
# Add a new record (in addition to any existing records
|
|
|
|
# for this qname-rtype pair).
|
|
|
|
action = "add"
|
2018-10-17 13:27:17 +00:00
|
|
|
elif method == "PUT":
|
2015-05-03 13:40:52 +00:00
|
|
|
# In REST, PUT is supposed to be idempotent, so we'll
|
|
|
|
# make this action set (replace all records for this
|
|
|
|
# qname-rtype pair) rather than add (add a new record).
|
|
|
|
action = "set"
|
2015-06-27 17:23:15 +00:00
|
|
|
|
2018-10-17 13:27:17 +00:00
|
|
|
elif method == "DELETE":
|
2015-05-03 13:40:52 +00:00
|
|
|
if value == '':
|
|
|
|
# Delete all records for this qname-type pair.
|
|
|
|
value = None
|
|
|
|
else:
|
|
|
|
# Delete just the qname-rtype-value record exactly.
|
|
|
|
pass
|
|
|
|
action = "remove"
|
|
|
|
|
|
|
|
if set_custom_dns_record(qname, rtype, value, action, env):
|
|
|
|
return do_dns_update(env) or "Something isn't right."
|
2014-08-23 23:03:45 +00:00
|
|
|
return "OK"
|
2015-05-03 13:40:52 +00:00
|
|
|
|
2014-08-23 23:03:45 +00:00
|
|
|
except ValueError as e:
|
|
|
|
return (str(e), 400)
|
|
|
|
|
2014-08-17 22:43:57 +00:00
|
|
|
@app.route('/dns/dump')
|
|
|
|
@authorized_personnel_only
|
|
|
|
def dns_get_dump():
|
|
|
|
from dns_update import build_recommended_dns
|
|
|
|
return json_response(build_recommended_dns(env))
|
2014-06-03 13:24:48 +00:00
|
|
|
|
2014-10-10 15:49:14 +00:00
|
|
|
# SSL
|
|
|
|
|
2016-01-02 22:53:47 +00:00
|
|
|
@app.route('/ssl/status')
|
|
|
|
@authorized_personnel_only
|
|
|
|
def ssl_get_status():
|
|
|
|
from ssl_certificates import get_certificates_to_provision
|
2016-01-04 23:22:02 +00:00
|
|
|
from web_update import get_web_domains_info, get_web_domains
|
|
|
|
|
|
|
|
# What domains can we provision certificates for? What unexpected problems do we have?
|
2018-05-13 00:02:25 +00:00
|
|
|
provision, cant_provision = get_certificates_to_provision(env, show_valid_certs=False)
|
2016-01-04 23:22:02 +00:00
|
|
|
|
|
|
|
# What's the current status of TLS certificates on all of the domain?
|
2016-01-02 22:53:47 +00:00
|
|
|
domains_status = get_web_domains_info(env)
|
2018-05-13 00:02:25 +00:00
|
|
|
domains_status = [
|
|
|
|
{
|
|
|
|
"domain": d["domain"],
|
|
|
|
"status": d["ssl_certificate"][0],
|
|
|
|
"text": d["ssl_certificate"][1] + ((" " + cant_provision[d["domain"]] if d["domain"] in cant_provision else ""))
|
|
|
|
} for d in domains_status ]
|
2016-01-04 23:22:02 +00:00
|
|
|
|
|
|
|
# Warn the user about domain names not hosted here because of other settings.
|
|
|
|
for domain in set(get_web_domains(env, exclude_dns_elsewhere=False)) - set(get_web_domains(env)):
|
|
|
|
domains_status.append({
|
|
|
|
"domain": domain,
|
|
|
|
"status": "not-applicable",
|
|
|
|
"text": "The domain's website is hosted elsewhere.",
|
|
|
|
})
|
|
|
|
|
2016-01-02 22:53:47 +00:00
|
|
|
return json_response({
|
2016-01-02 23:22:22 +00:00
|
|
|
"can_provision": utils.sort_domains(provision, env),
|
2016-01-04 23:22:02 +00:00
|
|
|
"status": domains_status,
|
2016-01-02 22:53:47 +00:00
|
|
|
})
|
|
|
|
|
2014-10-10 15:49:14 +00:00
|
|
|
@app.route('/ssl/csr/<domain>', methods=['POST'])
|
|
|
|
@authorized_personnel_only
|
|
|
|
def ssl_get_csr(domain):
|
2015-11-29 13:59:22 +00:00
|
|
|
from ssl_certificates import create_csr
|
2015-09-18 13:03:07 +00:00
|
|
|
ssl_private_key = os.path.join(os.path.join(env["STORAGE_ROOT"], 'ssl', 'ssl_private_key.pem'))
|
2015-12-26 16:48:23 +00:00
|
|
|
return create_csr(domain, ssl_private_key, request.form.get('countrycode', ''), env)
|
2014-10-10 15:49:14 +00:00
|
|
|
|
|
|
|
@app.route('/ssl/install', methods=['POST'])
|
|
|
|
@authorized_personnel_only
|
|
|
|
def ssl_install_cert():
|
2015-11-29 14:43:12 +00:00
|
|
|
from web_update import get_web_domains
|
2015-11-29 13:59:22 +00:00
|
|
|
from ssl_certificates import install_cert
|
2014-10-10 15:49:14 +00:00
|
|
|
domain = request.form.get('domain')
|
|
|
|
ssl_cert = request.form.get('cert')
|
|
|
|
ssl_chain = request.form.get('chain')
|
2015-11-29 14:43:12 +00:00
|
|
|
if domain not in get_web_domains(env):
|
2015-11-29 13:59:22 +00:00
|
|
|
return "Invalid domain name."
|
2014-10-10 15:49:14 +00:00
|
|
|
return install_cert(domain, ssl_cert, ssl_chain, env)
|
|
|
|
|
2016-01-04 23:22:02 +00:00
|
|
|
@app.route('/ssl/provision', methods=['POST'])
|
|
|
|
@authorized_personnel_only
|
|
|
|
def ssl_provision_certs():
|
|
|
|
from ssl_certificates import provision_certificates
|
2018-05-13 00:02:25 +00:00
|
|
|
requests = provision_certificates(env, limit_domains=None)
|
|
|
|
return json_response({ "requests": requests })
|
2016-01-04 23:22:02 +00:00
|
|
|
|
|
|
|
|
2014-06-20 01:16:38 +00:00
|
|
|
# WEB
|
|
|
|
|
2014-10-07 16:05:38 +00:00
|
|
|
@app.route('/web/domains')
|
|
|
|
@authorized_personnel_only
|
|
|
|
def web_get_domains():
|
|
|
|
from web_update import get_web_domains_info
|
|
|
|
return json_response(get_web_domains_info(env))
|
|
|
|
|
2014-06-20 01:16:38 +00:00
|
|
|
@app.route('/web/update', methods=['POST'])
|
2014-08-17 22:43:57 +00:00
|
|
|
@authorized_personnel_only
|
2014-06-20 01:16:38 +00:00
|
|
|
def web_update():
|
|
|
|
from web_update import do_web_update
|
|
|
|
return do_web_update(env)
|
|
|
|
|
2014-06-05 20:57:25 +00:00
|
|
|
# System
|
|
|
|
|
2015-06-25 13:42:22 +00:00
|
|
|
@app.route('/system/version', methods=["GET"])
|
|
|
|
@authorized_personnel_only
|
|
|
|
def system_version():
|
|
|
|
from status_checks import what_version_is_this
|
|
|
|
try:
|
|
|
|
return what_version_is_this(env)
|
|
|
|
except Exception as e:
|
|
|
|
return (str(e), 500)
|
|
|
|
|
|
|
|
@app.route('/system/latest-upstream-version', methods=["POST"])
|
|
|
|
@authorized_personnel_only
|
|
|
|
def system_latest_upstream_version():
|
|
|
|
from status_checks import get_latest_miab_version
|
|
|
|
try:
|
|
|
|
return get_latest_miab_version()
|
|
|
|
except Exception as e:
|
|
|
|
return (str(e), 500)
|
|
|
|
|
2014-08-17 22:43:57 +00:00
|
|
|
@app.route('/system/status', methods=["POST"])
|
|
|
|
@authorized_personnel_only
|
|
|
|
def system_status():
|
2014-08-21 10:43:55 +00:00
|
|
|
from status_checks import run_checks
|
2014-08-17 22:43:57 +00:00
|
|
|
class WebOutput:
|
|
|
|
def __init__(self):
|
|
|
|
self.items = []
|
|
|
|
def add_heading(self, heading):
|
|
|
|
self.items.append({ "type": "heading", "text": heading, "extra": [] })
|
|
|
|
def print_ok(self, message):
|
|
|
|
self.items.append({ "type": "ok", "text": message, "extra": [] })
|
|
|
|
def print_error(self, message):
|
|
|
|
self.items.append({ "type": "error", "text": message, "extra": [] })
|
2014-10-07 20:41:07 +00:00
|
|
|
def print_warning(self, message):
|
|
|
|
self.items.append({ "type": "warning", "text": message, "extra": [] })
|
2014-08-17 22:43:57 +00:00
|
|
|
def print_line(self, message, monospace=False):
|
|
|
|
self.items[-1]["extra"].append({ "text": message, "monospace": monospace })
|
|
|
|
output = WebOutput()
|
2016-02-23 05:32:01 +00:00
|
|
|
# Create a temporary pool of processes for the status checks
|
|
|
|
pool = multiprocessing.pool.Pool(processes=5)
|
2015-03-08 21:56:28 +00:00
|
|
|
run_checks(False, env, output, pool)
|
2016-02-23 05:32:01 +00:00
|
|
|
pool.terminate()
|
2014-08-17 22:43:57 +00:00
|
|
|
return json_response(output.items)
|
|
|
|
|
2014-06-05 20:57:25 +00:00
|
|
|
@app.route('/system/updates')
|
2014-08-17 22:43:57 +00:00
|
|
|
@authorized_personnel_only
|
2014-06-05 20:57:25 +00:00
|
|
|
def show_updates():
|
2014-08-21 11:09:51 +00:00
|
|
|
from status_checks import list_apt_updates
|
|
|
|
return "".join(
|
|
|
|
"%s (%s)\n"
|
|
|
|
% (p["package"], p["version"])
|
|
|
|
for p in list_apt_updates())
|
2014-06-05 20:57:25 +00:00
|
|
|
|
|
|
|
@app.route('/system/update-packages', methods=["POST"])
|
2014-08-17 22:43:57 +00:00
|
|
|
@authorized_personnel_only
|
2014-06-05 20:57:25 +00:00
|
|
|
def do_updates():
|
2014-06-09 12:09:45 +00:00
|
|
|
utils.shell("check_call", ["/usr/bin/apt-get", "-qq", "update"])
|
|
|
|
return utils.shell("check_output", ["/usr/bin/apt-get", "-y", "upgrade"], env={
|
|
|
|
"DEBIAN_FRONTEND": "noninteractive"
|
|
|
|
})
|
2014-06-05 20:57:25 +00:00
|
|
|
|
2016-03-23 20:37:15 +00:00
|
|
|
|
2016-02-25 20:56:27 +00:00
|
|
|
@app.route('/system/reboot', methods=["GET"])
|
|
|
|
@authorized_personnel_only
|
|
|
|
def needs_reboot():
|
2016-03-23 20:37:15 +00:00
|
|
|
from status_checks import is_reboot_needed_due_to_package_installation
|
|
|
|
if is_reboot_needed_due_to_package_installation():
|
2016-02-25 20:56:27 +00:00
|
|
|
return json_response(True)
|
|
|
|
else:
|
|
|
|
return json_response(False)
|
|
|
|
|
|
|
|
@app.route('/system/reboot', methods=["POST"])
|
|
|
|
@authorized_personnel_only
|
|
|
|
def do_reboot():
|
2016-03-23 20:37:15 +00:00
|
|
|
# To keep the attack surface low, we don't allow a remote reboot if one isn't necessary.
|
|
|
|
from status_checks import is_reboot_needed_due_to_package_installation
|
|
|
|
if is_reboot_needed_due_to_package_installation():
|
2016-02-25 20:56:27 +00:00
|
|
|
return utils.shell("check_output", ["/sbin/shutdown", "-r", "now"], capture_stderr=True)
|
|
|
|
else:
|
2016-03-23 20:37:15 +00:00
|
|
|
return "No reboot is required, so it is not allowed."
|
2016-02-25 20:56:27 +00:00
|
|
|
|
|
|
|
|
2014-09-01 13:06:38 +00:00
|
|
|
@app.route('/system/backup/status')
|
|
|
|
@authorized_personnel_only
|
|
|
|
def backup_status():
|
|
|
|
from backup import backup_status
|
2016-01-02 21:25:36 +00:00
|
|
|
try:
|
|
|
|
return json_response(backup_status(env))
|
|
|
|
except Exception as e:
|
|
|
|
return json_response({ "error": str(e) })
|
2014-09-01 13:06:38 +00:00
|
|
|
|
2015-07-27 20:00:36 +00:00
|
|
|
@app.route('/system/backup/config', methods=["GET"])
|
2015-07-26 16:25:52 +00:00
|
|
|
@authorized_personnel_only
|
|
|
|
def backup_get_custom():
|
|
|
|
from backup import get_backup_config
|
2015-08-28 11:37:04 +00:00
|
|
|
return json_response(get_backup_config(env, for_ui=True))
|
2015-07-26 16:25:52 +00:00
|
|
|
|
2015-07-27 20:00:36 +00:00
|
|
|
@app.route('/system/backup/config', methods=["POST"])
|
2015-07-26 16:25:52 +00:00
|
|
|
@authorized_personnel_only
|
|
|
|
def backup_set_custom():
|
|
|
|
from backup import backup_set_custom
|
2015-08-09 16:56:33 +00:00
|
|
|
return json_response(backup_set_custom(env,
|
2015-07-26 16:25:52 +00:00
|
|
|
request.form.get('target', ''),
|
|
|
|
request.form.get('target_user', ''),
|
|
|
|
request.form.get('target_pass', ''),
|
2015-07-28 18:58:39 +00:00
|
|
|
request.form.get('min_age', '')
|
2015-07-26 16:25:52 +00:00
|
|
|
))
|
|
|
|
|
2015-08-28 12:29:55 +00:00
|
|
|
@app.route('/system/privacy', methods=["GET"])
|
2015-07-25 11:47:10 +00:00
|
|
|
@authorized_personnel_only
|
2015-08-28 12:29:55 +00:00
|
|
|
def privacy_status_get():
|
|
|
|
config = utils.load_settings(env)
|
|
|
|
return json_response(config.get("privacy", True))
|
2015-07-25 11:47:10 +00:00
|
|
|
|
2015-08-28 12:29:55 +00:00
|
|
|
@app.route('/system/privacy', methods=["POST"])
|
2015-07-25 11:47:10 +00:00
|
|
|
@authorized_personnel_only
|
2015-08-28 12:29:55 +00:00
|
|
|
def privacy_status_set():
|
|
|
|
config = utils.load_settings(env)
|
|
|
|
config["privacy"] = (request.form.get('value') == "private")
|
|
|
|
utils.write_settings(config, env)
|
|
|
|
return "OK"
|
2015-07-25 11:47:10 +00:00
|
|
|
|
2015-05-25 17:01:53 +00:00
|
|
|
# MUNIN
|
|
|
|
|
|
|
|
@app.route('/munin/')
|
|
|
|
@app.route('/munin/<path:filename>')
|
|
|
|
@authorized_personnel_only
|
|
|
|
def munin(filename=""):
|
|
|
|
# Checks administrative access (@authorized_personnel_only) and then just proxies
|
|
|
|
# the request to static files.
|
|
|
|
if filename == "": filename = "index.html"
|
|
|
|
return send_from_directory("/var/cache/munin/www", filename)
|
|
|
|
|
2016-01-14 03:20:33 +00:00
|
|
|
@app.route('/munin/cgi-graph/<path:filename>')
|
|
|
|
@authorized_personnel_only
|
2016-03-23 20:07:34 +00:00
|
|
|
def munin_cgi(filename):
|
2016-01-14 03:20:33 +00:00
|
|
|
""" Relay munin cgi dynazoom requests
|
|
|
|
/usr/lib/munin/cgi/munin-cgi-graph is a perl cgi script in the munin package
|
|
|
|
that is responsible for generating binary png images _and_ associated HTTP
|
|
|
|
headers based on parameters in the requesting URL. All output is written
|
|
|
|
to stdout which munin_cgi splits into response headers and binary response
|
|
|
|
data.
|
2016-08-19 16:42:43 +00:00
|
|
|
munin-cgi-graph reads environment variables to determine
|
2016-01-14 03:20:33 +00:00
|
|
|
what it should do. It expects a path to be in the env-var PATH_INFO, and a
|
2016-08-19 16:42:43 +00:00
|
|
|
querystring to be in the env-var QUERY_STRING.
|
2016-01-14 04:55:45 +00:00
|
|
|
munin-cgi-graph has several failure modes. Some write HTTP Status headers and
|
|
|
|
others return nonzero exit codes.
|
2016-01-14 03:20:33 +00:00
|
|
|
Situating munin_cgi between the user-agent and munin-cgi-graph enables keeping
|
|
|
|
the cgi script behind mailinabox's auth mechanisms and avoids additional
|
|
|
|
support infrastructure like spawn-fcgi.
|
|
|
|
"""
|
|
|
|
|
2016-08-19 16:42:43 +00:00
|
|
|
COMMAND = 'su - munin --preserve-environment --shell=/bin/bash -c /usr/lib/munin/cgi/munin-cgi-graph'
|
2016-01-14 03:20:33 +00:00
|
|
|
# su changes user, we use the munin user here
|
|
|
|
# --preserve-environment retains the environment, which is where Popen's `env` data is
|
|
|
|
# --shell=/bin/bash ensures the shell used is bash
|
|
|
|
# -c "/usr/lib/munin/cgi/munin-cgi-graph" passes the command to run as munin
|
2016-01-14 15:24:04 +00:00
|
|
|
# "%s" is a placeholder for where the request's querystring will be added
|
2016-01-14 03:20:33 +00:00
|
|
|
|
|
|
|
if filename == "":
|
|
|
|
return ("a path must be specified", 404)
|
|
|
|
|
|
|
|
query_str = request.query_string.decode("utf-8", 'ignore')
|
|
|
|
|
2016-08-19 16:42:43 +00:00
|
|
|
env = {'PATH_INFO': '/%s/' % filename, 'REQUEST_METHOD': 'GET', 'QUERY_STRING': query_str}
|
2016-01-14 15:24:04 +00:00
|
|
|
code, binout = utils.shell('check_output',
|
2016-08-19 16:42:43 +00:00
|
|
|
COMMAND.split(" ", 5),
|
|
|
|
# Using a maxsplit of 5 keeps the last arguments together
|
2016-01-14 15:24:04 +00:00
|
|
|
env=env,
|
|
|
|
return_bytes=True,
|
|
|
|
trap=True)
|
|
|
|
|
|
|
|
if code != 0:
|
2016-01-14 03:20:33 +00:00
|
|
|
# nonzero returncode indicates error
|
2018-11-30 15:39:53 +00:00
|
|
|
app.logger.error("munin_cgi: munin-cgi-graph returned nonzero exit code, %s", code)
|
2016-01-14 03:20:33 +00:00
|
|
|
return ("error processing graph image", 500)
|
|
|
|
|
|
|
|
# /usr/lib/munin/cgi/munin-cgi-graph returns both headers and binary png when successful.
|
2016-03-23 20:07:34 +00:00
|
|
|
# A double-Windows-style-newline always indicates the end of HTTP headers.
|
|
|
|
headers, image_bytes = binout.split(b'\r\n\r\n', 1)
|
|
|
|
response = make_response(image_bytes)
|
|
|
|
for line in headers.splitlines():
|
|
|
|
name, value = line.decode("utf8").split(':', 1)
|
|
|
|
response.headers[name] = value
|
2016-01-14 03:20:33 +00:00
|
|
|
if 'Status' in response.headers and '404' in response.headers['Status']:
|
|
|
|
app.logger.warning("munin_cgi: munin-cgi-graph returned 404 status code. PATH_INFO=%s", env['PATH_INFO'])
|
|
|
|
return response
|
|
|
|
|
2016-04-13 21:52:13 +00:00
|
|
|
def log_failed_login(request):
|
|
|
|
# We need to figure out the ip to list in the message, all our calls are routed
|
|
|
|
# through nginx who will put the original ip in X-Forwarded-For.
|
|
|
|
# During setup we call the management interface directly to determine the user
|
|
|
|
# status. So we can't always use X-Forwarded-For because during setup that header
|
|
|
|
# will not be present.
|
|
|
|
if request.headers.getlist("X-Forwarded-For"):
|
|
|
|
ip = request.headers.getlist("X-Forwarded-For")[0]
|
|
|
|
else:
|
|
|
|
ip = request.remote_addr
|
|
|
|
|
|
|
|
# We need to add a timestamp to the log message, otherwise /dev/log will eat the "duplicate"
|
|
|
|
# message.
|
|
|
|
app.logger.warning( "Mail-in-a-Box Management Daemon: Failed login attempt from ip %s - timestamp %s" % (ip, time.time()))
|
|
|
|
|
|
|
|
|
2014-06-03 13:24:48 +00:00
|
|
|
# APP
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
if "DEBUG" in os.environ: app.debug = True
|
2014-08-17 22:43:57 +00:00
|
|
|
if "APIKEY" in os.environ: auth_service.key = os.environ["APIKEY"]
|
2014-06-21 23:42:48 +00:00
|
|
|
|
2014-06-21 23:25:35 +00:00
|
|
|
if not app.debug:
|
|
|
|
app.logger.addHandler(utils.create_syslog_handler())
|
|
|
|
|
2014-06-21 23:42:48 +00:00
|
|
|
# For testing on the command line, you can use `curl` like so:
|
|
|
|
# curl --user $(</var/lib/mailinabox/api.key): http://localhost:10222/mail/users
|
|
|
|
auth_service.write_key()
|
|
|
|
|
|
|
|
# For testing in the browser, you can copy the API key that's output to the
|
|
|
|
# debug console and enter that as the username
|
|
|
|
app.logger.info('API key: ' + auth_service.key)
|
|
|
|
|
2014-10-05 12:55:28 +00:00
|
|
|
# Start the application server. Listens on 127.0.0.1 (IPv4 only).
|
2014-06-03 13:24:48 +00:00
|
|
|
app.run(port=10222)
|