feature: the package installs the Router Manager, which is no longer a package of its own.
Release / release (push) Failing after 4s
Release / release (push) Failing after 4s
This commit is contained in:
1 parent
6d90441bee
commit
8efe21bfa6
129 files changed
+17381
-104
No files matched your search
@@ -1,22 +0,0 @@
|
||||
ARG UBUNTU_VERSION=24.04
|
||||
FROM ubuntu:${UBUNTU_VERSION}
|
||||
ARG HOST_UID
|
||||
ARG HOST_GID
|
||||
|
||||
RUN apt-get update \
|
||||
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
|
||||
build-essential \
|
||||
dpkg-dev \
|
||||
debhelper \
|
||||
lintian \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /build
|
||||
COPY . src/
|
||||
RUN cd src && dpkg-buildpackage -us -uc -b
|
||||
|
||||
RUN lintian --no-tag-display-limit /build/*.changes || true
|
||||
|
||||
RUN mkdir /out \
|
||||
&& find /build -maxdepth 1 \( -name '*.deb' -o -name '*.buildinfo' -o -name '*.changes' \) \
|
||||
-exec install -o "$HOST_UID" -g "$HOST_GID" -m 0644 {} /out/ \;
|
||||
@@ -1,17 +0,0 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
# Apple container CLI on macOS, Docker CE on Linux.
|
||||
case "$(uname -s)" in
|
||||
Darwin) CONTAINER_RUNTIME=container ;;
|
||||
Linux) CONTAINER_RUNTIME=docker ;;
|
||||
*) printf 'ERROR: unsupported platform %s\n' "$(uname -s)" >&2; exit 1 ;;
|
||||
esac
|
||||
|
||||
mkdir -p out
|
||||
|
||||
$CONTAINER_RUNTIME build --build-arg HOST_UID=$(id -u) --build-arg HOST_GID=$(id -g) -t vpn-router-builder "$@" .
|
||||
# Artifacts are streamed out as a tar archive, so no bind mount is needed.
|
||||
$CONTAINER_RUNTIME run --rm vpn-router-builder tar -cf - -C /out . | tar -xf - -C out
|
||||
|
||||
echo "Build artifacts written to out/"
|
||||
@@ -1,3 +1,35 @@
|
||||
vpn-router (0.40.0-1) unstable; urgency=medium
|
||||
|
||||
feature: the package installs the Router Manager, which is no longer a
|
||||
package of its own.
|
||||
|
||||
* The Router Manager, vpn-router-manager.service, is installed and started
|
||||
with the router; its programs are in /usr/lib/vpn-router, its application
|
||||
and help in /usr/share/vpn-router/manager.
|
||||
* Its settings are /etc/vpn-router/manager.json, its database password
|
||||
/etc/vpn-router/manager-database.secret and the state of its upgrades
|
||||
/var/lib/vpn-router/upgrade.json and system-upgrade.json.
|
||||
* The debconf questions vpn-router/admin_username and admin_password give
|
||||
its first administrator, written to /etc/vpn-router/manager-admin.json.
|
||||
* The Overview tab and the upgrade helper know the package vpn-router
|
||||
alone.
|
||||
* The bootstrap page on port 17081 shows the manager's service and log;
|
||||
port 17080 and vpn-router-manager-bootstrap are gone.
|
||||
* The status has no manager_version; the manager's unit is always among
|
||||
the services.
|
||||
* The package cannot be installed beside the package vpn-router-manager,
|
||||
which has to be removed first.
|
||||
* A purge also removes the manager's settings, its database and role, and
|
||||
the record of its upgrades.
|
||||
* build.sh, publish.sh and the Dockerfile are in the repository root, the
|
||||
build also builds the application in web/, and CONTAINER_RUNTIME chooses
|
||||
the container runtime.
|
||||
* The README and the ADR call the product that deploys the router Cloud
|
||||
Manager, also where they named manage-ui, and the docstring of the GCP
|
||||
platform names Google Cloud.
|
||||
|
||||
-- Slawomir Koszewski <slawek@koszewscy.waw.pl> Fri, 13 Nov 2026 20:15:15 +0100
|
||||
|
||||
vpn-router (0.39.1-1) unstable; urgency=medium
|
||||
|
||||
fix: the web service starts again after its first start with 0.39.0, and the
|
||||
|
||||
@@ -12,6 +12,16 @@ fi
|
||||
# preseeded completes without prompting. The defaults are platform "none" and
|
||||
# mode "manual", which together mean: install the files, configure nothing.
|
||||
|
||||
# The Router Manager's first administrator, asked whatever the platform is; the password only with a name.
|
||||
db_input medium vpn-router/admin_username || true
|
||||
db_go || true
|
||||
|
||||
db_get vpn-router/admin_username
|
||||
if [ -n "$RET" ]; then
|
||||
db_input medium vpn-router/admin_password || true
|
||||
db_go || true
|
||||
fi
|
||||
|
||||
db_input high vpn-router/platform || true
|
||||
db_go || true
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@ Depends: ${misc:Depends},
|
||||
python3-psycopg,
|
||||
python3-psutil,
|
||||
python3-prometheus-client,
|
||||
python3-requests,
|
||||
postgresql,
|
||||
slapd,
|
||||
nslcd,
|
||||
@@ -46,7 +47,7 @@ Suggests: caddy,
|
||||
pdns-server,
|
||||
pdns-backend-pgsql,
|
||||
proxmox-backup-client-static
|
||||
Description: Linux VPN router with IPSec, IKEv2, OpenVPN and WireGuard support
|
||||
Description: Linux VPN router with IPSec, IKEv2, OpenVPN, WireGuard and a web manager
|
||||
Configures a Linux host or virtual machine as a VPN router: site-to-site
|
||||
IKEv2 IPSec (strongSwan swanctl) with pre-shared keys or certificates,
|
||||
optional IKEv2 access using EAP-TLS, optional OpenVPN with a
|
||||
@@ -64,6 +65,11 @@ Description: Linux VPN router with IPSec, IKEv2, OpenVPN and WireGuard support
|
||||
or to a Proxmox Backup Server. Nothing in the package is specific to a cloud
|
||||
provider.
|
||||
.
|
||||
The Router Manager, a web application served by the router, shows the
|
||||
router's state and manages its users, connections, certificates, web sites,
|
||||
name server, backups and packages. Users sign in through the router's web
|
||||
service; their sessions are kept in PostgreSQL.
|
||||
.
|
||||
Settings live in /etc/vpn-router/vpn-router.json, which is created on first
|
||||
install and owned by the administrator afterwards. Editing it and restarting
|
||||
vpn-router-setup applies the change; the same service reconciles the system
|
||||
|
||||
@@ -2,4 +2,5 @@ etc/vpn-router
|
||||
usr/lib/vpn-router
|
||||
usr/lib/vpn-router/vpnrouter_platforms
|
||||
usr/share/vpn-router/templates
|
||||
usr/share/vpn-router/manager/web
|
||||
var/lib/vpn-router/sites
|
||||
@@ -37,9 +37,15 @@ src/usr/lib/vpn-router/metrics usr/lib/vpn-router/
|
||||
src/usr/lib/vpn-router/bootstrap usr/lib/vpn-router/
|
||||
src/usr/lib/vpn-router/wait-for-libpq usr/lib/vpn-router/
|
||||
src/usr/lib/vpn-router/generate-config usr/lib/vpn-router/
|
||||
src/usr/lib/vpn-router/manager usr/lib/vpn-router/
|
||||
src/usr/lib/vpn-router/vpnrouter_manager.py usr/lib/vpn-router/
|
||||
src/usr/lib/vpn-router/upgrade usr/lib/vpn-router/
|
||||
src/usr/lib/vpn-router/vpnrouter_platforms/*.py usr/lib/vpn-router/vpnrouter_platforms/
|
||||
src/usr/share/vpn-router/templates/* usr/share/vpn-router/templates/
|
||||
src/usr/share/vpn-router/sql/* usr/share/vpn-router/sql/
|
||||
src/usr/share/bash-completion/completions/*.bash usr/share/bash-completion/completions/
|
||||
src/usr/lib/systemd/system/caddy.service.d/vpn-router.conf usr/lib/systemd/system/caddy.service.d/
|
||||
src/usr/share/doc/vpn-router/vpn-router.json.example usr/share/doc/vpn-router/
|
||||
src/usr/share/doc/vpn-router/manager.json.example usr/share/doc/vpn-router/
|
||||
web/dist/* usr/share/vpn-router/manager/web/
|
||||
docs/* usr/share/vpn-router/manager/docs/
|
||||
@@ -63,6 +63,22 @@ case "$1" in
|
||||
# not blank the key on the next dpkg-reconfigure.
|
||||
db_set vpn-router/psk ""
|
||||
|
||||
# The Router Manager's administrator account for vpn-router-setup to create, when a name and a
|
||||
# password were given; the answers are cleared so that a later run does not ask for it again.
|
||||
db_get vpn-router/admin_username
|
||||
ADMIN_USERNAME="$RET"
|
||||
db_get vpn-router/admin_password
|
||||
ADMIN_PASSWORD="$RET"
|
||||
if [ -n "$ADMIN_USERNAME" ] && [ -n "$ADMIN_PASSWORD" ]; then
|
||||
(umask 077; ADMIN_USERNAME="$ADMIN_USERNAME" ADMIN_PASSWORD="$ADMIN_PASSWORD" python3 -c \
|
||||
'import json, os, sys; json.dump({"username": os.environ["ADMIN_USERNAME"], "password": os.environ["ADMIN_PASSWORD"]}, sys.stdout)' \
|
||||
> /etc/vpn-router/manager-admin.json)
|
||||
elif [ -n "$ADMIN_USERNAME" ]; then
|
||||
echo 'vpn-router: no administrator password was given; no Router Manager administrator is created' >&2
|
||||
fi
|
||||
db_set vpn-router/admin_username ""
|
||||
db_set vpn-router/admin_password ""
|
||||
|
||||
# Apply the sysctl drop-in shipped by this package so it takes effect
|
||||
# without waiting for a reboot.
|
||||
sysctl --system >/dev/null
|
||||
@@ -71,12 +87,13 @@ case "$1" in
|
||||
# setting the forward policy all belong to vpn-router-setup, which does
|
||||
# them only once the configuration says this host is a router.
|
||||
|
||||
# The setup and web services wait for libpq in the linker cache, which
|
||||
# dpkg refreshes after this script, so they are started without waiting
|
||||
# for them.
|
||||
# The setup, web and manager services wait for libpq in the linker cache,
|
||||
# which dpkg refreshes after this script, so they are started without
|
||||
# waiting for them.
|
||||
if [ -d /run/systemd/system ]; then
|
||||
systemctl --no-block restart vpn-router-setup.service >/dev/null 2>&1 || true
|
||||
systemctl --no-block restart vpn-router-web.service >/dev/null 2>&1 || true
|
||||
systemctl --no-block restart vpn-router-manager.service >/dev/null 2>&1 || true
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
@@ -56,6 +56,12 @@ case "$1" in
|
||||
/etc/vpn-router/web.key \
|
||||
/etc/vpn-router/oidc.key \
|
||||
/etc/vpn-router/metrics.secret \
|
||||
/etc/vpn-router/manager.json \
|
||||
/etc/vpn-router/manager-admin.json \
|
||||
/var/lib/vpn-router/upgrade.json \
|
||||
/var/lib/vpn-router/upgrade.log \
|
||||
/var/lib/vpn-router/system-upgrade.json \
|
||||
/var/lib/vpn-router/system-upgrade.log \
|
||||
/etc/systemd/system/vpn-router-backup.timer.d/schedule.conf \
|
||||
/etc/sudoers.d/vpn-router \
|
||||
/etc/ssh/sshd_config.d/vpn-router.conf \
|
||||
@@ -76,8 +82,9 @@ case "$1" in
|
||||
fi
|
||||
rm -f /etc/vpn-router/database.secret
|
||||
|
||||
# The databases and roles of the web sites and of the name server, when the package created them.
|
||||
for database in vpn-router-sites vpn-router-dns; do
|
||||
# The databases and roles of the web sites, of the name server and of the Router Manager's sessions,
|
||||
# when the package created them.
|
||||
for database in vpn-router-sites vpn-router-dns vpn-router-manager; do
|
||||
secret="/etc/vpn-router/${database#vpn-router-}-database.secret"
|
||||
if [ -f "$secret" ] && command -v psql >/dev/null 2>&1; then
|
||||
runuser -u postgres -- psql -X -q -c "DROP DATABASE IF EXISTS \"$database\"" || true
|
||||
|
||||
@@ -2,8 +2,12 @@
|
||||
%:
|
||||
dh $@
|
||||
|
||||
override_dh_auto_build:
|
||||
test -f web/dist/index.html
|
||||
|
||||
override_dh_installsystemd:
|
||||
dh_installsystemd --name=vpn-router-setup --no-start
|
||||
dh_installsystemd --name=vpn-router-manager --no-start
|
||||
dh_installsystemd --name=vpn-router-docker
|
||||
dh_installsystemd --name=vpn-router-web --no-start
|
||||
dh_installsystemd --name=vpn-router-metrics --no-enable --no-start
|
||||
|
||||
@@ -13,6 +13,24 @@ Description: Platform:
|
||||
.
|
||||
generic configures the router with no platform-specific additions.
|
||||
|
||||
Template: vpn-router/admin_username
|
||||
Type: string
|
||||
Default:
|
||||
Description: Name of the Router Manager's administrator account:
|
||||
The Router Manager can have a first administrator: a Manager-only account
|
||||
of the router's user directory, a member of the group admins, which may
|
||||
sign in to the Router Manager but has no VPN access. vpn-router-setup
|
||||
creates it.
|
||||
.
|
||||
Leave this empty to create no account and no group.
|
||||
|
||||
Template: vpn-router/admin_password
|
||||
Type: password
|
||||
Description: Password of the administrator account:
|
||||
The password of the administrator account, 8 to 128 characters. It is
|
||||
passed to vpn-router-setup in a file readable by root only, which is removed
|
||||
once the account exists, and not kept by debconf.
|
||||
|
||||
Template: vpn-router/mode
|
||||
Type: select
|
||||
Choices: manual, interfaces, auto
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
[Unit]
|
||||
Description=VPN Router Manager web application
|
||||
Documentation=file:/usr/share/doc/vpn-router/README.md
|
||||
After=network-online.target postgresql.service
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStartPre=/usr/lib/vpn-router/wait-for-libpq
|
||||
ExecStart=/usr/bin/python3 /usr/lib/vpn-router/manager
|
||||
TimeoutStartSec=5min
|
||||
Restart=on-failure
|
||||
RestartSec=15
|
||||
NoNewPrivileges=yes
|
||||
ProtectSystem=strict
|
||||
ReadWritePaths=-/etc/vpn-router
|
||||
ProtectHome=yes
|
||||
PrivateTmp=yes
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -1,45 +0,0 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
# Apple container CLI on macOS, Docker CE on Linux.
|
||||
case "$(uname -s)" in
|
||||
Darwin) CONTAINER_RUNTIME=container ;;
|
||||
Linux) CONTAINER_RUNTIME=docker ;;
|
||||
*) printf 'ERROR: unsupported platform %s\n' "$(uname -s)" >&2; exit 1 ;;
|
||||
esac
|
||||
|
||||
OWNER="${OWNER:-koszewscy}"
|
||||
SERVER_URL="${SERVER_URL:-https://gitea.koszewscy.waw.pl}"
|
||||
PACKAGES_TOKEN="${PACKAGES_TOKEN:-$(cat ~/.gitea-packages-token)}"
|
||||
# The Ubuntu releases whose distribution of the repository gets the package, in its component main.
|
||||
DISTRIBUTIONS="${DISTRIBUTIONS:-noble resolute}"
|
||||
|
||||
# Reads the changelog copied into the builder image, so no bind mount is needed.
|
||||
changelog_field() {
|
||||
$CONTAINER_RUNTIME run --rm vpn-router-builder \
|
||||
dpkg-parsechangelog --show-field "$1" -l /build/src/debian/changelog
|
||||
}
|
||||
|
||||
VERSION="$(changelog_field Version)"
|
||||
PACKAGE="$(changelog_field Source)"
|
||||
DEB="out/${PACKAGE}_${VERSION}_all.deb"
|
||||
|
||||
if [ ! -f "$DEB" ]; then
|
||||
printf 'ERROR: %s does not exist. Run ./build.sh first.\n' "$DEB" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
BODY="$(mktemp)"
|
||||
trap 'rm -f "$BODY"' EXIT
|
||||
|
||||
# Gitea answers 409 for a version that is in the distribution already.
|
||||
for DISTRIBUTION in $DISTRIBUTIONS; do
|
||||
STATUS="$(curl -s -o "$BODY" -w '%{http_code}' --user "$OWNER:$PACKAGES_TOKEN" \
|
||||
--upload-file "$DEB" \
|
||||
"$SERVER_URL/api/packages/$OWNER/debian/pool/$DISTRIBUTION/main/upload")"
|
||||
case "$STATUS" in
|
||||
2??) printf '%s %s is published in %s/main.\n' "$PACKAGE" "$VERSION" "$DISTRIBUTION" ;;
|
||||
409) printf '%s %s is already in %s/main, skipping.\n' "$PACKAGE" "$VERSION" "$DISTRIBUTION" ;;
|
||||
*) printf 'ERROR: the upload to %s/main returned HTTP %s: %s\n' "$DISTRIBUTION" "$STATUS" "$(cat "$BODY")" >&2; exit 1 ;;
|
||||
esac
|
||||
done
|
||||
@@ -16,14 +16,16 @@ PORT = 17081
|
||||
#: The title of each section and its command.
|
||||
COMMANDS = (
|
||||
('Setup state', ['cat', '/run/vpn-router/setup.json']),
|
||||
('Services', ['systemctl', 'is-active', 'vpn-router-setup', 'vpn-router-web', 'slapd', 'postgresql',
|
||||
'strongswan', 'openvpn-server@vpn-router', 'wg-quick@wg0']),
|
||||
('Services', ['systemctl', 'is-active', 'vpn-router-setup', 'vpn-router-web', 'vpn-router-manager', 'slapd',
|
||||
'postgresql', 'strongswan', 'openvpn-server@vpn-router', 'wg-quick@wg0']),
|
||||
('Failed units', ['systemctl', '--failed', '--no-legend', '--plain']),
|
||||
('Addresses', ['ip', '-brief', 'address']),
|
||||
('Routes', ['ip', 'route']),
|
||||
('cloud-init', ['cloud-init', 'status', '--long']),
|
||||
('vpn-router-setup log', ['journalctl', '--unit', 'vpn-router-setup', '--lines', '60', '--no-pager', '--output', 'short-iso']),
|
||||
('vpn-router-web log', ['journalctl', '--unit', 'vpn-router-web', '--lines', '30', '--no-pager', '--output', 'short-iso']),
|
||||
('vpn-router-manager log', ['journalctl', '--unit', 'vpn-router-manager', '--lines', '30', '--no-pager', '--output',
|
||||
'short-iso']),
|
||||
)
|
||||
|
||||
|
||||
|
||||
+903
@@ -0,0 +1,903 @@
|
||||
#!/usr/bin/python3
|
||||
"""Serve the Router Manager: the web application and its API, which passes calls to the router.
|
||||
|
||||
Run by vpn-router-manager.service. It uses python3-requests to call the router and
|
||||
python3-psycopg to keep the sessions; its settings and its listening loop are in
|
||||
vpnrouter_manager.
|
||||
|
||||
Pages:
|
||||
/api/info the version of this package and the router it manages, as JSON
|
||||
/api/session POST signs in through the router's /auth with {"name", "password", "code"?},
|
||||
GET answers the signed-in user, DELETE signs out
|
||||
/api/session/passkey
|
||||
POST begins a sign-in with a passkey at the router's /auth/passkey;
|
||||
/api/session/passkey/complete POST signs in through /auth/passkey/complete
|
||||
/api/updates GET the installed and the candidate version of vpn-router
|
||||
from apt (see updates()), POST updates apt's package lists (see start_check());
|
||||
needs a session, POST a member of admins
|
||||
/api/upgrade GET the state and the output of the upgrade of that package (see upgrade_state()),
|
||||
POST starts it (see start_upgrade()); needs a session, POST a member of admins
|
||||
/api/system-updates
|
||||
GET the packages of the system apt-get upgrade would upgrade, with their installed
|
||||
and candidate versions (see system_updates()); needs a session
|
||||
/api/system-upgrade
|
||||
GET the state and the output of the upgrade of the system's packages, POST starts
|
||||
it (see start_upgrade()); needs a session, POST a member of admins
|
||||
/api/reboot POST reboots the system (see start_reboot()); needs a member of admins
|
||||
/api/shell a WebSocket handshake goes to the router's /shell, and the WebSocket is relayed
|
||||
(see Handler.relay()); POST passes as every other path does
|
||||
/api/<path> the router's web service at /<path>, with the access token of the session;
|
||||
the method, the body and the answer pass unchanged; the files of a web site,
|
||||
/api/sites/<name>/files/..., pass streamed for GET, HEAD and PUT (see Handler.transfer())
|
||||
/docs/<file> a file of the help in DOCS_DIR, Markdown, SVG or PNG (see doc_file()); needs a session
|
||||
/<file> the web application from WEB_DIR; a path that names no file gives index.html
|
||||
|
||||
A session is a row of the table sessions in PostgreSQL, found by the SHA-256 of a random id in
|
||||
the HttpOnly cookie COOKIE; it holds the user's access and refresh tokens and ends with the
|
||||
refresh token. An access token that expires within REFRESH_MARGIN seconds is renewed through
|
||||
the router's /auth/refresh before a call; a refused renewal ends the session. /api/<path>
|
||||
without a session answers 401. Sign-in calls carry the browser's address in X-Forwarded-For,
|
||||
which the router reads for its rate limit when the manager is one of its trusted proxies.
|
||||
Without router_url the API answers 503.
|
||||
|
||||
The manager first initializes, without listening: on the router, unless the settings name a
|
||||
database, it creates its role, password and database when they are missing; then it connects to
|
||||
the sessions database and creates its table, retrying every INIT_RETRY_SECONDS until it succeeds
|
||||
and logging each failure. Then it listens. Its unit starts it only once wait-for-libpq has found
|
||||
libpq in the linker cache, where psycopg looks it up.
|
||||
|
||||
The service needs nothing else to start and does not end on its own. Every DISCOVERY_SECONDS it
|
||||
works out where to listen, bind or the interfaces listen names, and runs a server at each address
|
||||
(vpnrouter_manager.serve). Every request
|
||||
reads the settings when it is made.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import http.cookies
|
||||
import json
|
||||
import mimetypes
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import signal
|
||||
import socket
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.parse
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
|
||||
|
||||
import psycopg
|
||||
import requests
|
||||
import urllib3
|
||||
|
||||
import vpnrouter_manager
|
||||
from vpnrouter_manager import DATABASE, DATABASE_SECRET, ROUTER_CONFIG_FILE
|
||||
|
||||
#: The address a proxy on this host calls from.
|
||||
LOOPBACK = '127.0.0.1'
|
||||
|
||||
CONFIG_FILE = vpnrouter_manager.CONFIG_FILE
|
||||
WEB_DIR = '/usr/share/vpn-router/manager/web'
|
||||
DOCS_DIR = '/usr/share/vpn-router/manager/docs'
|
||||
|
||||
#: The files of DOCS_DIR /docs serves, by extension, and their content types.
|
||||
DOC_TYPES = {'.md': 'text/markdown; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png'}
|
||||
|
||||
#: The headers of every /docs answer: no type guessing, and an SVG opened on its own runs no script.
|
||||
DOC_HEADERS = (('X-Content-Type-Options', 'nosniff'), ('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'"))
|
||||
|
||||
#: The cookie that holds the session id.
|
||||
COOKIE = 'vpn_router_manager_session'
|
||||
|
||||
#: Seconds before its expiry an access token is renewed.
|
||||
REFRESH_MARGIN = 30
|
||||
|
||||
#: Seconds between two attempts of the initialization.
|
||||
INIT_RETRY_SECONDS = 15
|
||||
|
||||
#: The packages /api/updates reports.
|
||||
PACKAGES = ('vpn-router',)
|
||||
|
||||
#: Touched by apt at every successful update of its package lists.
|
||||
APT_UPDATED = '/var/lib/apt/periodic/update-success-stamp'
|
||||
|
||||
#: The transient units of the upgrade, of the reboot and of the update of the package lists, outside the manager's unit.
|
||||
UPGRADE_UNIT = 'vpn-router-manager-upgrade'
|
||||
SYSTEM_UPGRADE_UNIT = 'vpn-router-manager-system-upgrade'
|
||||
REBOOT_UNIT = 'vpn-router-manager-reboot'
|
||||
CHECK_UNIT = 'vpn-router-manager-check'
|
||||
|
||||
#: Seconds the update of the package lists waits for apt's lock, which Ubuntu's apt-daily or unattended-upgrades may hold.
|
||||
CHECK_LOCK_SECONDS = 300
|
||||
|
||||
#: The upgrade helper, and the state and the output it records of the router's package and of the system's.
|
||||
UPGRADE = '/usr/lib/vpn-router/upgrade'
|
||||
UPGRADE_STATE = '/var/lib/vpn-router/upgrade.json'
|
||||
UPGRADE_LOG = '/var/lib/vpn-router/upgrade.log'
|
||||
SYSTEM_UPGRADE_STATE = '/var/lib/vpn-router/system-upgrade.json'
|
||||
SYSTEM_UPGRADE_LOG = '/var/lib/vpn-router/system-upgrade.log'
|
||||
|
||||
#: A package apt-get -s upgrade would upgrade: Inst <name> [<installed>] (<candidate> <release> [<architecture>]).
|
||||
SIMULATED = re.compile(r'^Inst (\S+) (?:\[([^\]]*)\] )?\((\S+)')
|
||||
|
||||
#: The last lines of the upgrade's output /api/upgrade answers.
|
||||
LOG_LINES = 200
|
||||
|
||||
#: Written by packages that need a reboot, with the packages in REBOOT_REQUIRED.pkgs.
|
||||
REBOOT_REQUIRED = '/var/run/reboot-required'
|
||||
|
||||
#: Seconds between the answer of /api/reboot and the reboot.
|
||||
REBOOT_DELAY = 5
|
||||
|
||||
SCHEMA = ('CREATE TABLE IF NOT EXISTS sessions (id_hash text PRIMARY KEY, name text NOT NULL, access_token text NOT NULL, '
|
||||
'access_expires timestamptz NOT NULL, refresh_token text NOT NULL, expires timestamptz NOT NULL)')
|
||||
|
||||
#: Seconds between two discoveries of where the service should listen.
|
||||
DISCOVERY_SECONDS = 30
|
||||
|
||||
#: Seconds a call to the router may take; adding a user creates an RSA key.
|
||||
ROUTER_TIMEOUT = 130
|
||||
|
||||
#: The largest request body passed to the router, in bytes; a CSR or a certificate chain in PEM is a few kilobytes.
|
||||
BODY_LIMIT = 65536
|
||||
|
||||
#: The largest body of a save of the Shell page's editor, /api/shell/editor/...: a file of up to 1 MiB, as the router
|
||||
#: takes, escaped in JSON.
|
||||
EDITOR_BODY_LIMIT = 2 * 1024 * 1024 + BODY_LIMIT
|
||||
|
||||
#: The paths of a web site's files, whose GET, HEAD and PUT pass streamed (see Handler.transfer()).
|
||||
SITE_FILES = re.compile(r'^/api/sites/[^/]+/files(/.*)?$')
|
||||
|
||||
|
||||
def settings():
|
||||
return vpnrouter_manager.settings(CONFIG_FILE)
|
||||
|
||||
|
||||
def package_version():
|
||||
try:
|
||||
result = subprocess.run(['dpkg-query', '-W', '-f=${Version}', 'vpn-router'],
|
||||
capture_output=True, text=True, timeout=5)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return None
|
||||
return result.stdout.strip() if result.returncode == 0 else None
|
||||
|
||||
|
||||
def updates():
|
||||
"""The installed and the candidate version of each of PACKAGES, from apt-cache policy, and whether an update is available.
|
||||
|
||||
The candidate is the version apt would install from the sources it is configured with, as of
|
||||
its last update of the package lists, whose time checked gives (APT_UPDATED, None when it is
|
||||
not known); a version apt does not know is None. checking is whether start_check's update of
|
||||
the package lists runs. Where apt cannot be asked, available is False and the packages are empty.
|
||||
"""
|
||||
checking = unit_active(CHECK_UNIT)
|
||||
try:
|
||||
result = subprocess.run(['apt-cache', 'policy', *PACKAGES], capture_output=True, text=True, timeout=30)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return {'available': False, 'checked': None, 'checking': checking, 'packages': []}
|
||||
try:
|
||||
checked = time.strftime('%Y-%m-%dT%H:%M:%S%z', time.localtime(os.path.getmtime(APT_UPDATED)))
|
||||
except OSError:
|
||||
checked = None
|
||||
found = {}
|
||||
package = None
|
||||
for line in result.stdout.splitlines():
|
||||
if line and not line[0].isspace() and line.endswith(':'):
|
||||
package = found.setdefault(line[:-1], {'name': line[:-1], 'installed': None, 'candidate': None})
|
||||
elif package is not None and line.strip().startswith(('Installed:', 'Candidate:')):
|
||||
key, _, value = line.strip().partition(': ')
|
||||
package[key.lower()] = None if value == '(none)' else value
|
||||
packages = [dict(found.get(name, {'name': name, 'installed': None, 'candidate': None})) for name in PACKAGES]
|
||||
for package in packages:
|
||||
package['update'] = package['installed'] is not None and package['candidate'] not in (None, package['installed'])
|
||||
return {'available': True, 'checked': checked, 'checking': checking, 'packages': packages}
|
||||
|
||||
|
||||
def system_updates():
|
||||
"""The packages of the system apt-get upgrade would upgrade, from its simulation (apt-get -s), as updates() answers
|
||||
its packages, each with update true, sorted by name; the other keys are those of updates().
|
||||
|
||||
The simulation takes no lock and changes nothing; it answers what the package lists of apt's last update give.
|
||||
"""
|
||||
checking = unit_active(CHECK_UNIT)
|
||||
try:
|
||||
result = subprocess.run(['apt-get', '-s', '-q', 'upgrade'], capture_output=True, text=True, timeout=60,
|
||||
env=dict(os.environ, LC_ALL='C'))
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return {'available': False, 'checked': None, 'checking': checking, 'packages': []}
|
||||
if result.returncode != 0:
|
||||
return {'available': False, 'checked': None, 'checking': checking, 'packages': []}
|
||||
try:
|
||||
checked = time.strftime('%Y-%m-%dT%H:%M:%S%z', time.localtime(os.path.getmtime(APT_UPDATED)))
|
||||
except OSError:
|
||||
checked = None
|
||||
found = {}
|
||||
for line in result.stdout.splitlines():
|
||||
match = SIMULATED.match(line)
|
||||
if match:
|
||||
found[match[1]] = {'name': match[1], 'installed': match[2], 'candidate': match[3], 'update': True}
|
||||
return {'available': True, 'checked': checked, 'checking': checking, 'packages': [found[name] for name in sorted(found)]}
|
||||
|
||||
|
||||
def unit_active(unit):
|
||||
"""Whether a unit of systemd is active or activating; False where systemctl cannot be asked."""
|
||||
try:
|
||||
result = subprocess.run(['systemctl', 'is-active', f'{unit}.service', f'{unit}.timer'],
|
||||
capture_output=True, text=True, timeout=5)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return False
|
||||
return any(line.strip() in ('active', 'activating') for line in result.stdout.splitlines())
|
||||
|
||||
|
||||
def upgrade_state(system=False):
|
||||
"""The state of the upgrade of the router's package, as GET /api/upgrade answers it, or with system of the system's
|
||||
packages, as GET /api/system-upgrade answers it.
|
||||
|
||||
state is idle before the first upgrade, running, succeeded or failed as the helper recorded it, and interrupted when
|
||||
it recorded running but its unit is not active, as after a reboot during the upgrade; the other keys of the helper's
|
||||
state follow, and log holds the last LOG_LINES lines of its output. reboot_required and reboot_packages tell whether
|
||||
a package asks for a reboot, and rebooting whether one is about to happen.
|
||||
"""
|
||||
state_file, log_file = (SYSTEM_UPGRADE_STATE, SYSTEM_UPGRADE_LOG) if system else (UPGRADE_STATE, UPGRADE_LOG)
|
||||
try:
|
||||
with open(state_file, encoding='utf-8') as handle:
|
||||
recorded = json.load(handle)
|
||||
except (OSError, ValueError):
|
||||
recorded = {}
|
||||
if not isinstance(recorded, dict):
|
||||
recorded = {}
|
||||
running = unit_active(SYSTEM_UPGRADE_UNIT if system else UPGRADE_UNIT)
|
||||
state = recorded.get('state', 'idle')
|
||||
if running:
|
||||
state = 'running'
|
||||
elif state == 'running':
|
||||
state = 'interrupted'
|
||||
try:
|
||||
with open(log_file, encoding='utf-8', errors='replace') as handle:
|
||||
log = handle.read().splitlines()[-LOG_LINES:]
|
||||
except OSError:
|
||||
log = []
|
||||
try:
|
||||
with open(f'{REBOOT_REQUIRED}.pkgs', encoding='utf-8') as handle:
|
||||
reboot_packages = sorted({line.strip() for line in handle if line.strip()})
|
||||
except OSError:
|
||||
reboot_packages = []
|
||||
return {
|
||||
'state': state,
|
||||
'user': recorded.get('user'),
|
||||
'started': recorded.get('started'),
|
||||
'finished': recorded.get('finished'),
|
||||
'exit_status': recorded.get('exit_status'),
|
||||
'before': recorded.get('before'),
|
||||
'after': recorded.get('after'),
|
||||
'log': log,
|
||||
'reboot_required': os.path.exists(REBOOT_REQUIRED),
|
||||
'reboot_packages': reboot_packages,
|
||||
'rebooting': unit_active(REBOOT_UNIT),
|
||||
}
|
||||
|
||||
|
||||
def transient(*args):
|
||||
"""Start a transient unit with systemd-run and the arguments; the HTTP status and the message of a refusal, or None."""
|
||||
try:
|
||||
result = subprocess.run(['systemd-run', '--quiet', '--collect', *args], capture_output=True, text=True, timeout=15)
|
||||
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||
return 503, f'systemd-run cannot be run here: {exc}'
|
||||
if result.returncode != 0:
|
||||
message = result.stderr.strip() or f'systemd-run ended with status {result.returncode}'
|
||||
return (409 if 'already' in message.lower() else 500), message
|
||||
return None
|
||||
|
||||
|
||||
def busy():
|
||||
"""Whether an upgrade, of the router's package or of the system's, or a reboot runs."""
|
||||
return unit_active(UPGRADE_UNIT) or unit_active(SYSTEM_UPGRADE_UNIT) or unit_active(REBOOT_UNIT)
|
||||
|
||||
|
||||
def start_upgrade(name, system=False):
|
||||
"""Start the upgrade of the router's package in the transient unit UPGRADE_UNIT, or with system of the system's
|
||||
packages in SYSTEM_UPGRADE_UNIT, outside this service, so the restarts it makes do not end it.
|
||||
|
||||
The HTTP status and the JSON document: 202 when it started, 409 while an upgrade or a reboot runs, 503 where apt
|
||||
cannot be used.
|
||||
"""
|
||||
if busy():
|
||||
return 409, {'error': 'an upgrade or a reboot is already running'}
|
||||
if not os.path.exists('/usr/bin/apt-get'):
|
||||
return 503, {'error': 'apt is not available here'}
|
||||
if system:
|
||||
refused = transient(f'--unit={SYSTEM_UPGRADE_UNIT}', '--description=VPN Router system upgrade',
|
||||
'--property=Type=exec', '--no-block', '/usr/bin/python3', UPGRADE, '--system', name)
|
||||
else:
|
||||
refused = transient(f'--unit={UPGRADE_UNIT}', '--description=VPN Router package upgrade', '--property=Type=exec',
|
||||
'--no-block', '/usr/bin/python3', UPGRADE, name)
|
||||
if refused:
|
||||
return refused[0], {'error': refused[1]}
|
||||
return 202, {'started': True}
|
||||
|
||||
|
||||
def start_check():
|
||||
"""Update apt's package lists in the transient unit CHECK_UNIT, as root outside this service's sandbox, and touch
|
||||
APT_UPDATED when it succeeds, so updates() answers the new candidates and the time of the check.
|
||||
|
||||
The HTTP status and the JSON document: 202 when it started, 409 while an update of the lists, an upgrade or a
|
||||
reboot runs, 503 where apt cannot be used.
|
||||
"""
|
||||
if unit_active(CHECK_UNIT) or busy():
|
||||
return 409, {'error': 'a check for updates, an upgrade or a reboot is already running'}
|
||||
if not os.path.exists('/usr/bin/apt-get'):
|
||||
return 503, {'error': 'apt is not available here'}
|
||||
refused = transient(f'--unit={CHECK_UNIT}', '--description=VPN Router package lists update', '--property=Type=oneshot',
|
||||
f'--property=ExecStartPost=/usr/bin/touch {APT_UPDATED}', '--no-block',
|
||||
'/usr/bin/apt-get', '-q', '-o', f'DPkg::Lock::Timeout={CHECK_LOCK_SECONDS}', 'update')
|
||||
if refused:
|
||||
return refused[0], {'error': refused[1]}
|
||||
return 202, {'checking': True}
|
||||
|
||||
|
||||
def start_reboot():
|
||||
"""Reboot the system REBOOT_DELAY seconds from now, so the answer reaches the browser first.
|
||||
|
||||
The HTTP status and the JSON document: 202 when the reboot is scheduled, 409 while an upgrade or a reboot runs.
|
||||
"""
|
||||
if busy():
|
||||
return 409, {'error': 'an upgrade or a reboot is already running'}
|
||||
refused = transient(f'--unit={REBOOT_UNIT}', '--description=VPN Router reboot', f'--on-active={REBOOT_DELAY}',
|
||||
'/usr/bin/systemctl', 'reboot')
|
||||
if refused:
|
||||
return refused[0], {'error': refused[1]}
|
||||
return 202, {'rebooting': True}
|
||||
|
||||
|
||||
def admin(current, access, client):
|
||||
"""Whether the signed-in user is a member of the router's admins, as the router's /account answers."""
|
||||
response = router_call(current, 'GET', '/account', None, {'Authorization': f'Bearer {access}', 'X-Forwarded-For': client})
|
||||
try:
|
||||
return response.ok and response.json().get('admin') is True
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def error(code, message):
|
||||
return code, 'application/json', json.dumps({'error': message}).encode() + b'\n'
|
||||
|
||||
|
||||
class Unavailable(Exception):
|
||||
"""A setting the API needs is missing, or the router or the database cannot be reached; the HTTP status and message."""
|
||||
|
||||
def __init__(self, code, message):
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
|
||||
|
||||
def router_call(current, method, path, body=None, headers=None):
|
||||
"""The router's answer to a call; Unavailable when it cannot be reached."""
|
||||
if not current['router_url']:
|
||||
raise Unavailable(503, f'no router is configured; set router_url in {CONFIG_FILE}')
|
||||
headers = dict(headers or {}, Accept='application/json')
|
||||
if body is not None:
|
||||
headers['Content-Type'] = 'application/json'
|
||||
try:
|
||||
return requests.request(method, current['router_url'] + path, data=body, headers=headers,
|
||||
timeout=ROUTER_TIMEOUT, allow_redirects=False)
|
||||
except requests.RequestException as failure:
|
||||
raise Unavailable(502, f'the router at {current["router_url"]} cannot be reached: {failure}')
|
||||
|
||||
|
||||
def answer_of(response):
|
||||
"""The HTTP status, the content type and the body to pass on for an answer of the router."""
|
||||
kind = response.headers.get('Content-Type', '')
|
||||
if response.ok or kind.startswith('application/json'):
|
||||
return response.status_code, kind or 'application/json', response.content
|
||||
return error(response.status_code, f'the router answered {response.status_code}: {response.text.strip()}')
|
||||
|
||||
|
||||
def database(current):
|
||||
"""A connection to the sessions database, with its table; Unavailable when it is not configured or fails."""
|
||||
if not current['database']:
|
||||
raise Unavailable(503, f'no session database is configured; set database in {CONFIG_FILE}')
|
||||
try:
|
||||
connection = psycopg.connect(current['database'], autocommit=True)
|
||||
connection.execute(SCHEMA)
|
||||
except psycopg.Error as failure:
|
||||
raise Unavailable(503, f'the session database cannot be used: {failure}')
|
||||
return connection
|
||||
|
||||
|
||||
def psql(sql):
|
||||
"""The output of an SQL statement, read from standard input, run by psql as postgres with DATABASE as the variable v1."""
|
||||
result = subprocess.run(['runuser', '-u', 'postgres', '--', 'psql', '-X', '-q', '-t', '-A', '-v', 'ON_ERROR_STOP=1',
|
||||
'-v', f'v1={DATABASE}'], input=sql, capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
raise OSError(f'psql failed: {result.stderr.strip()}')
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def provision():
|
||||
"""Create the role, its password file and the database on the router, each when missing.
|
||||
|
||||
The password, of URL-safe characters, reaches psql on standard input, not on its command line.
|
||||
"""
|
||||
if not psql("SELECT 1 FROM pg_roles WHERE rolname = :'v1'"):
|
||||
if os.path.exists(DATABASE_SECRET):
|
||||
os.unlink(DATABASE_SECRET)
|
||||
psql('CREATE ROLE :"v1" LOGIN')
|
||||
if not os.path.exists(DATABASE_SECRET):
|
||||
password = secrets.token_urlsafe(32)
|
||||
psql(f"ALTER ROLE :\"v1\" PASSWORD '{password}'")
|
||||
os.makedirs(os.path.dirname(DATABASE_SECRET), exist_ok=True)
|
||||
descriptor = os.open(DATABASE_SECRET, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||
with os.fdopen(descriptor, 'w', encoding='utf-8') as handle:
|
||||
handle.write(password + '\n')
|
||||
if not psql("SELECT 1 FROM pg_database WHERE datname = :'v1'"):
|
||||
psql('CREATE DATABASE :"v1" OWNER :"v1"')
|
||||
|
||||
|
||||
def initialize():
|
||||
"""Create the sessions database on the router when it is missing and connect to it, retrying every INIT_RETRY_SECONDS."""
|
||||
reported = None
|
||||
while True:
|
||||
phase = 'reading the settings'
|
||||
try:
|
||||
configured = vpnrouter_manager.text_setting(vpnrouter_manager.read_json(CONFIG_FILE), 'database')
|
||||
if not configured and os.path.exists(ROUTER_CONFIG_FILE):
|
||||
phase = 'creating the sessions database'
|
||||
provision()
|
||||
phase = 'connecting to the sessions database'
|
||||
database(settings()).close()
|
||||
except (OSError, Unavailable) as exc:
|
||||
failure = f'{phase} failed: {exc}'
|
||||
if failure != reported:
|
||||
log(f'{failure}; retrying every {INIT_RETRY_SECONDS} seconds')
|
||||
reported = failure
|
||||
time.sleep(INIT_RETRY_SECONDS)
|
||||
continue
|
||||
log('ready')
|
||||
return
|
||||
|
||||
|
||||
def digest(session_id):
|
||||
return hashlib.sha256(session_id.encode()).hexdigest()
|
||||
|
||||
|
||||
def tokens_of(response):
|
||||
"""The tokens of a 200 answer of /auth or /auth/refresh, or None when it holds none."""
|
||||
try:
|
||||
document = response.json()
|
||||
values = (document['access_token'], int(document['expires_in']), document['refresh_token'],
|
||||
int(document['refresh_expires_in']))
|
||||
except (ValueError, KeyError, TypeError):
|
||||
return None
|
||||
return values if response.status_code == 200 and all(values) else None
|
||||
|
||||
|
||||
def sign_in(current, path, body, client):
|
||||
"""Sign in through the router's path, /auth or /auth/passkey/complete: the HTTP status, the content type, the body
|
||||
and the session id, or None."""
|
||||
response = router_call(current, 'POST', path, body, {'X-Forwarded-For': client})
|
||||
tokens = tokens_of(response)
|
||||
if tokens is None:
|
||||
return (*answer_of(response), None)
|
||||
try:
|
||||
name = response.json()['name']
|
||||
except (ValueError, KeyError, TypeError):
|
||||
return (*error(502, 'the router named no user'), None)
|
||||
session_id = secrets.token_urlsafe(32)
|
||||
access, access_seconds, refresh, refresh_seconds = tokens
|
||||
with database(current) as connection:
|
||||
connection.execute('DELETE FROM sessions WHERE expires < now()')
|
||||
connection.execute('INSERT INTO sessions VALUES (%s, %s, %s, now() + make_interval(secs => %s), %s, '
|
||||
'now() + make_interval(secs => %s))',
|
||||
(digest(session_id), name, access, access_seconds, refresh, refresh_seconds))
|
||||
return 200, 'application/json', json.dumps({'name': name}).encode() + b'\n', session_id
|
||||
|
||||
|
||||
def session(current, session_id, client):
|
||||
"""The user name and a current access token of the session, renewed when it expires soon, or None."""
|
||||
if not session_id:
|
||||
return None
|
||||
with database(current) as connection:
|
||||
with connection.transaction():
|
||||
row = connection.execute('SELECT name, access_token, access_expires < now() + make_interval(secs => %s), '
|
||||
'refresh_token FROM sessions WHERE id_hash = %s AND expires > now() FOR UPDATE',
|
||||
(REFRESH_MARGIN, digest(session_id))).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
name, access, stale, refresh = row
|
||||
if not stale:
|
||||
return name, access
|
||||
response = router_call(current, 'POST', '/auth/refresh', json.dumps({'refresh_token': refresh}).encode(),
|
||||
{'X-Forwarded-For': client})
|
||||
tokens = tokens_of(response)
|
||||
if tokens is None:
|
||||
connection.execute('DELETE FROM sessions WHERE id_hash = %s', (digest(session_id),))
|
||||
return None
|
||||
access, access_seconds, refresh, refresh_seconds = tokens
|
||||
connection.execute('UPDATE sessions SET access_token = %s, access_expires = now() + make_interval(secs => %s), '
|
||||
'refresh_token = %s, expires = now() + make_interval(secs => %s) WHERE id_hash = %s',
|
||||
(access, access_seconds, refresh, refresh_seconds, digest(session_id)))
|
||||
return name, access
|
||||
|
||||
|
||||
def sign_out(current, session_id):
|
||||
"""End the session and revoke its refresh token at the router."""
|
||||
if not session_id:
|
||||
return
|
||||
with database(current) as connection:
|
||||
row = connection.execute('DELETE FROM sessions WHERE id_hash = %s RETURNING refresh_token',
|
||||
(digest(session_id),)).fetchone()
|
||||
if row:
|
||||
router_call(current, 'POST', '/auth/logout', json.dumps({'refresh_token': row[0]}).encode())
|
||||
|
||||
|
||||
def static(path):
|
||||
"""A file of the web application; a path that names no file gives index.html, so the application routes it."""
|
||||
root = os.path.realpath(WEB_DIR)
|
||||
name = os.path.realpath(os.path.join(root, path.lstrip('/')))
|
||||
if not name.startswith(root + os.sep) or not os.path.isfile(name):
|
||||
name = os.path.join(root, 'index.html')
|
||||
try:
|
||||
with open(name, 'rb') as handle:
|
||||
data = handle.read()
|
||||
except OSError:
|
||||
return 404, 'text/plain; charset=utf-8', b'Not found\n'
|
||||
return 200, mimetypes.guess_type(name)[0] or 'application/octet-stream', data
|
||||
|
||||
|
||||
def doc_file(path, root=DOCS_DIR):
|
||||
"""The file of the help that a /docs/<file> path names and its content type, or None: a file inside root whose
|
||||
extension DOC_TYPES lists."""
|
||||
root = os.path.realpath(root)
|
||||
name = os.path.realpath(os.path.join(root, urllib.parse.unquote(path).lstrip('/')))
|
||||
kind = DOC_TYPES.get(os.path.splitext(name)[1].lower())
|
||||
if kind is None or not name.startswith(root + os.sep) or not os.path.isfile(name):
|
||||
return None
|
||||
return name, kind
|
||||
|
||||
|
||||
class Stream:
|
||||
"""A request body of length bytes read from a stream as requests sends it, which takes its length from len()."""
|
||||
|
||||
def __init__(self, stream, length):
|
||||
self.stream = stream
|
||||
self.length = length
|
||||
self.left = length
|
||||
|
||||
def __len__(self):
|
||||
return self.length
|
||||
|
||||
def read(self, size=-1):
|
||||
size = self.left if size is None or size < 0 else min(size, self.left)
|
||||
data = self.stream.read(size) if size else b''
|
||||
self.left -= len(data)
|
||||
return data
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
protocol_version = 'HTTP/1.1'
|
||||
|
||||
def session_id(self):
|
||||
"""The session id of the request's cookie, or ''."""
|
||||
cookies = http.cookies.SimpleCookie()
|
||||
try:
|
||||
cookies.load(self.headers.get('Cookie', ''))
|
||||
except http.cookies.CookieError:
|
||||
return ''
|
||||
return cookies[COOKIE].value if COOKIE in cookies else ''
|
||||
|
||||
def proxied(self):
|
||||
"""True for a call from a proxy on this host, such as the router's HTTPS proxy, which names the client."""
|
||||
return self.client_address[0] == LOOPBACK and 'X-Forwarded-For' in self.headers
|
||||
|
||||
def client(self):
|
||||
"""The browser's address: the last X-Forwarded-For entry of a proxied call, else the peer."""
|
||||
if self.proxied():
|
||||
return self.headers['X-Forwarded-For'].split(',')[-1].strip()
|
||||
return self.client_address[0]
|
||||
|
||||
def api(self, path, route, payload):
|
||||
"""Answer an /api/ request: the HTTP status, the content type, the body and the Set-Cookie value or None."""
|
||||
current = settings()
|
||||
client = self.client()
|
||||
session_id = self.session_id()
|
||||
if route == '/api/session/passkey' and self.command == 'POST':
|
||||
return (*answer_of(router_call(current, 'POST', '/auth/passkey', b'{}', {'X-Forwarded-For': client})), None)
|
||||
if route in ('/api/session', '/api/session/passkey/complete') and self.command == 'POST':
|
||||
code, kind, body, created = sign_in(current, '/auth' if route == '/api/session' else '/auth/passkey/complete',
|
||||
payload, client)
|
||||
if created is None:
|
||||
return code, kind, body, None
|
||||
return code, kind, body, f'{COOKIE}={created}; HttpOnly; SameSite=Strict; Path=/'
|
||||
if route == '/api/session' and self.command == 'DELETE':
|
||||
sign_out(current, session_id)
|
||||
return 200, 'application/json', b'{"signed_out": true}\n', f'{COOKIE}=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0'
|
||||
found = session(current, session_id, client)
|
||||
if found is None:
|
||||
return (*error(401, 'not signed in'), None)
|
||||
name, access = found
|
||||
if route == '/api/session':
|
||||
return 200, 'application/json', json.dumps({'name': name}).encode() + b'\n', None
|
||||
if route == '/api/updates' and self.command in ('GET', 'HEAD'):
|
||||
return 200, 'application/json', json.dumps(updates()).encode() + b'\n', None
|
||||
if route == '/api/updates' and self.command == 'POST':
|
||||
if not admin(current, access, client):
|
||||
return (*error(403, f'user {name} is not a member of admins'), None)
|
||||
code, document = start_check()
|
||||
return code, 'application/json', json.dumps(document).encode() + b'\n', None
|
||||
if route == '/api/system-updates' and self.command in ('GET', 'HEAD'):
|
||||
return 200, 'application/json', json.dumps(system_updates()).encode() + b'\n', None
|
||||
if route in ('/api/upgrade', '/api/system-upgrade') and self.command in ('GET', 'HEAD'):
|
||||
return 200, 'application/json', json.dumps(upgrade_state(route == '/api/system-upgrade')).encode() + b'\n', None
|
||||
if route in ('/api/upgrade', '/api/system-upgrade', '/api/reboot') and self.command == 'POST':
|
||||
if not admin(current, access, client):
|
||||
return (*error(403, f'user {name} is not a member of admins'), None)
|
||||
code, document = start_reboot() if route == '/api/reboot' else start_upgrade(name, route == '/api/system-upgrade')
|
||||
return code, 'application/json', json.dumps(document).encode() + b'\n', None
|
||||
return (*answer_of(router_call(current, self.command, path[4:], payload,
|
||||
{'Authorization': f'Bearer {access}', 'X-Forwarded-For': client})), None)
|
||||
|
||||
def relay(self, path):
|
||||
"""Pass the WebSocket handshake of /api/shell to the router's /shell with the session's access token, then
|
||||
relay the bytes both ways until either side closes; the HTTP status, the content type and the body of a
|
||||
refusal, or None after a relayed WebSocket.
|
||||
|
||||
The handshake must come from a page of this host (Origin), and asks the router for no extension, so the
|
||||
frames pass unchanged.
|
||||
"""
|
||||
current = settings()
|
||||
client = self.client()
|
||||
if urllib.parse.urlsplit(self.headers.get('Origin', '')).netloc != self.headers.get('Host', ''):
|
||||
return error(403, 'the shell must be opened from a page of the Router Manager')
|
||||
found = session(current, self.session_id(), client)
|
||||
if found is None:
|
||||
return error(401, 'not signed in')
|
||||
if not current['router_url']:
|
||||
raise Unavailable(503, f'no router is configured; set router_url in {CONFIG_FILE}')
|
||||
url = urllib.parse.urlsplit(current['router_url'] + path[4:])
|
||||
secure = url.scheme == 'https'
|
||||
request = '\r\n'.join([
|
||||
f'GET {url.path}?{url.query} HTTP/1.1', f'Host: {url.netloc}', 'Upgrade: websocket', 'Connection: Upgrade',
|
||||
f'Sec-WebSocket-Key: {self.headers.get("Sec-WebSocket-Key", "")}',
|
||||
f'Sec-WebSocket-Version: {self.headers.get("Sec-WebSocket-Version", "")}',
|
||||
f'Authorization: Bearer {found[1]}', f'X-Forwarded-For: {client}', '', ''])
|
||||
try:
|
||||
upstream = socket.create_connection((url.hostname, url.port or (443 if secure else 80)), timeout=ROUTER_TIMEOUT)
|
||||
if secure:
|
||||
upstream = ssl.create_default_context().wrap_socket(upstream, server_hostname=url.hostname)
|
||||
upstream.sendall(request.encode())
|
||||
reader = upstream.makefile('rb')
|
||||
code = int(reader.readline().split(b' ', 2)[1])
|
||||
headers = {}
|
||||
while (line := reader.readline().strip()):
|
||||
name, _, value = line.decode('latin-1').partition(':')
|
||||
headers[name.strip().lower()] = value.strip()
|
||||
if code != 101:
|
||||
body = reader.read(int(headers.get('content-length', '0')))
|
||||
upstream.close()
|
||||
return code, headers.get('content-type', 'application/json'), body
|
||||
upstream.settimeout(None)
|
||||
except (OSError, ValueError, IndexError) as failure:
|
||||
raise Unavailable(502, f'the router at {current["router_url"]} cannot open a shell: {failure}')
|
||||
self.close_connection = True
|
||||
try:
|
||||
self.send_response(101, 'Switching Protocols')
|
||||
self.send_header('Upgrade', 'websocket')
|
||||
self.send_header('Connection', 'Upgrade')
|
||||
self.send_header('Sec-WebSocket-Accept', headers.get('sec-websocket-accept', ''))
|
||||
self.end_headers()
|
||||
except ConnectionError:
|
||||
# The client went away before the shell was relayed; the router ends the shell when upstream closes.
|
||||
upstream.close()
|
||||
return None
|
||||
|
||||
def pump(source, target):
|
||||
try:
|
||||
while data := source.read1(65536):
|
||||
target.sendall(data)
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
for end in (upstream, self.connection):
|
||||
try:
|
||||
end.shutdown(socket.SHUT_RDWR)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
thread = threading.Thread(target=pump, args=(reader, self.connection), name='shell output', daemon=True)
|
||||
thread.start()
|
||||
pump(self.rfile, upstream)
|
||||
thread.join()
|
||||
upstream.close()
|
||||
return None
|
||||
|
||||
def transfer(self, path, send_body):
|
||||
"""Pass a GET, HEAD or PUT of a web site's files to the router with the session's access token, streaming the
|
||||
request body and the answer; the HTTP status, the content type and the body of a refusal, or None once the
|
||||
router's answer was passed on.
|
||||
|
||||
The body of a PUT goes to the router as it arrives, with its Content-Type and Content-Length, so it is not held
|
||||
to BODY_LIMIT; the answer passes with its Content-Type, Content-Length and Content-Disposition.
|
||||
"""
|
||||
current = settings()
|
||||
client = self.client()
|
||||
found = session(current, self.session_id(), client)
|
||||
if found is None:
|
||||
return error(401, 'not signed in')
|
||||
if not current['router_url']:
|
||||
raise Unavailable(503, f'no router is configured; set router_url in {CONFIG_FILE}')
|
||||
headers = {'Authorization': f'Bearer {found[1]}', 'X-Forwarded-For': client}
|
||||
body = None
|
||||
if self.command == 'PUT':
|
||||
length = self.headers.get('Content-Length', '')
|
||||
if not length.isdigit():
|
||||
return error(411, 'the body needs a Content-Length')
|
||||
headers['Content-Type'] = self.headers.get('Content-Type') or 'application/octet-stream'
|
||||
body = Stream(self.rfile, int(length))
|
||||
try:
|
||||
response = requests.request(self.command, current['router_url'] + path[4:], data=body, headers=headers,
|
||||
timeout=ROUTER_TIMEOUT, allow_redirects=False, stream=True)
|
||||
except requests.RequestException as failure:
|
||||
raise Unavailable(502, f'the router at {current["router_url"]} cannot be reached: {failure}')
|
||||
with response:
|
||||
try:
|
||||
self.send_response(response.status_code)
|
||||
for name in ('Content-Type', 'Content-Length', 'Content-Disposition'):
|
||||
if name in response.headers:
|
||||
self.send_header(name, response.headers[name])
|
||||
self.send_header('Cache-Control', 'no-store')
|
||||
self.end_headers()
|
||||
if send_body:
|
||||
for chunk in response.raw.stream(65536, decode_content=False):
|
||||
self.wfile.write(chunk)
|
||||
except ConnectionError:
|
||||
# The client went away before the answer was passed on.
|
||||
self.close_connection = True
|
||||
except urllib3.exceptions.HTTPError as failure:
|
||||
# The router's answer broke off after its headers were passed on.
|
||||
self.close_connection = True
|
||||
log(f'the router\'s answer to {self.command} {path.split("?", 1)[0]} broke off: {failure}')
|
||||
return None
|
||||
|
||||
def doc(self, path):
|
||||
"""Answer GET /docs/<path> with a file of the help (doc_file): the HTTP status, the content type and the body; 401
|
||||
without a session, 404 for a path that names no such file."""
|
||||
try:
|
||||
if session(settings(), self.session_id(), self.client()) is None:
|
||||
return error(401, 'not signed in')
|
||||
except Unavailable as failure:
|
||||
return error(failure.code, str(failure))
|
||||
except psycopg.Error as failure:
|
||||
return error(503, f'the session database failed: {failure}')
|
||||
found = doc_file(path)
|
||||
if found is None:
|
||||
return 404, 'text/plain; charset=utf-8', b'Not found\n'
|
||||
try:
|
||||
with open(found[0], 'rb') as handle:
|
||||
return 200, found[1], handle.read()
|
||||
except OSError:
|
||||
return 404, 'text/plain; charset=utf-8', b'Not found\n'
|
||||
|
||||
def answer(self, send_body):
|
||||
path = self.path.split('#', 1)[0]
|
||||
route = path.split('?', 1)[0]
|
||||
cookie = None
|
||||
# A body that is not read must not be taken for the next request.
|
||||
if self.command not in ('GET', 'HEAD'):
|
||||
self.close_connection = True
|
||||
if route == '/api/info':
|
||||
https = self.proxied() and self.headers.get('X-Forwarded-Proto') == 'https'
|
||||
status = vpnrouter_manager.status_url(CONFIG_FILE, self.headers.get('Host', ''), self.server.server_address[0], https)
|
||||
body = json.dumps({'version': package_version(), 'status_url': status or None}).encode()
|
||||
code, kind = 200, 'application/json'
|
||||
elif route == '/api/shell' and self.command == 'GET' and self.headers.get('Upgrade', '').lower() == 'websocket':
|
||||
try:
|
||||
refused = self.relay(path)
|
||||
except Unavailable as failure:
|
||||
refused = error(failure.code, str(failure))
|
||||
except psycopg.Error as failure:
|
||||
refused = error(503, f'the session database failed: {failure}')
|
||||
if refused is None:
|
||||
return
|
||||
code, kind, body = refused
|
||||
elif SITE_FILES.match(route) and self.command in ('GET', 'HEAD', 'PUT'):
|
||||
try:
|
||||
refused = self.transfer(path, send_body)
|
||||
except Unavailable as failure:
|
||||
refused = error(failure.code, str(failure))
|
||||
except psycopg.Error as failure:
|
||||
refused = error(503, f'the session database failed: {failure}')
|
||||
if refused is None:
|
||||
return
|
||||
code, kind, body = refused
|
||||
elif route.startswith('/api/'):
|
||||
limit = EDITOR_BODY_LIMIT if route.startswith('/api/shell/editor/') else BODY_LIMIT
|
||||
payload = self.request_body(limit)
|
||||
if payload is False:
|
||||
code, kind, body = error(413, f'the body is larger than {limit} bytes')
|
||||
else:
|
||||
try:
|
||||
code, kind, body, cookie = self.api(path, route, payload)
|
||||
except Unavailable as failure:
|
||||
code, kind, body = error(failure.code, str(failure))
|
||||
except psycopg.Error as failure:
|
||||
code, kind, body = error(503, f'the session database failed: {failure}')
|
||||
elif route.startswith('/docs/') and self.command in ('GET', 'HEAD'):
|
||||
code, kind, body = self.doc(route[len('/docs/'):])
|
||||
elif self.command in ('GET', 'HEAD'):
|
||||
code, kind, body = static(route)
|
||||
else:
|
||||
code, kind, body = 405, 'text/plain; charset=utf-8', b'Method not allowed\n'
|
||||
try:
|
||||
self.send_response(code)
|
||||
self.send_header('Content-Type', kind)
|
||||
self.send_header('Content-Length', str(len(body)))
|
||||
self.send_header('Cache-Control', 'no-store' if route.startswith('/api/') or not route.startswith('/assets/') else 'max-age=31536000, immutable')
|
||||
if cookie:
|
||||
self.send_header('Set-Cookie', cookie)
|
||||
for name, value in DOC_HEADERS if route.startswith('/docs/') else ():
|
||||
self.send_header(name, value)
|
||||
self.end_headers()
|
||||
if send_body:
|
||||
self.wfile.write(body)
|
||||
except ConnectionError:
|
||||
# The client went away before the answer was written.
|
||||
self.close_connection = True
|
||||
|
||||
def request_body(self, limit=BODY_LIMIT):
|
||||
"""The request body, None when there is none, or False when it is larger than limit bytes."""
|
||||
length = self.headers.get('Content-Length')
|
||||
if not length:
|
||||
return None
|
||||
try:
|
||||
size = int(length)
|
||||
except ValueError:
|
||||
return False
|
||||
if not 0 <= size <= limit:
|
||||
return False
|
||||
return self.rfile.read(size)
|
||||
|
||||
def do_GET(self):
|
||||
self.answer(True)
|
||||
|
||||
def do_HEAD(self):
|
||||
self.answer(False)
|
||||
|
||||
def do_POST(self):
|
||||
self.answer(True)
|
||||
|
||||
def do_PUT(self):
|
||||
self.answer(True)
|
||||
|
||||
def do_DELETE(self):
|
||||
self.answer(True)
|
||||
|
||||
def log_message(self, format, *args):
|
||||
sys.stderr.write('%s - - [%s] %s\n' % (self.client(), self.log_date_time_string(), format % args))
|
||||
|
||||
|
||||
def log(message):
|
||||
print(f'vpn-router-manager: {message}', file=sys.stderr, flush=True)
|
||||
|
||||
|
||||
def main():
|
||||
global CONFIG_FILE
|
||||
parser = argparse.ArgumentParser(description='Serve the VPN Router Manager.')
|
||||
parser.add_argument('--config', default=CONFIG_FILE, help=f'the settings file (default: {CONFIG_FILE})')
|
||||
CONFIG_FILE = parser.parse_args().config
|
||||
signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
|
||||
initialize()
|
||||
try:
|
||||
vpnrouter_manager.serve(lambda: vpnrouter_manager.listen(CONFIG_FILE), Handler, log, DISCOVERY_SECONDS)
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -6,10 +6,10 @@ the live system: routes, DNS-derived identity, WireGuard keys, firewall rules
|
||||
and service reloads. Idempotent - a second run changes nothing.
|
||||
|
||||
Until a run has succeeded (SETUP_DONE), every run starts the bootstrap
|
||||
services, BOOTSTRAP_UNITS, which show the progress and the failure recorded in
|
||||
service, BOOTSTRAP_UNITS, which shows the progress and the failure recorded in
|
||||
SETUP_STATE on vpnrouter.BOOTSTRAP_PORTS, and the firewall opens those ports on the
|
||||
internal interface. The first successful run writes SETUP_DONE, closes the
|
||||
ports and stops the bootstrap services; a failed run leaves them running.
|
||||
ports and stops the bootstrap service; a failed run leaves it running.
|
||||
|
||||
Interface names come from the configuration and are never guessed. The
|
||||
firewall and NAT rules are written against them, so choosing the wrong one
|
||||
@@ -46,18 +46,18 @@ UFW_DEFAULTS = pathlib.Path('/etc/default/ufw')
|
||||
WG_DIR = pathlib.Path('/etc/wireguard')
|
||||
WEB_STATE = vpnrouter.WEB_STATE
|
||||
|
||||
#: The state, the current step and the failure of the last run, which the bootstrap services show.
|
||||
#: The state, the current step and the failure of the last run, which the bootstrap service shows.
|
||||
SETUP_STATE = pathlib.Path('/run/vpn-router/setup.json')
|
||||
|
||||
#: Written once a run has succeeded; until then setup runs the bootstrap services and opens their ports.
|
||||
#: Written once a run has succeeded; until then setup runs the bootstrap service and opens its ports.
|
||||
SETUP_DONE = pathlib.Path('/var/lib/vpn-router/setup.done')
|
||||
|
||||
#: The units of the bootstrap services, whose ports are vpnrouter.BOOTSTRAP_PORTS.
|
||||
BOOTSTRAP_UNITS = ('vpn-router-bootstrap.service', 'vpn-router-manager-bootstrap.service')
|
||||
#: The unit of the bootstrap service, whose ports are vpnrouter.BOOTSTRAP_PORTS.
|
||||
BOOTSTRAP_UNITS = ('vpn-router-bootstrap.service',)
|
||||
|
||||
#: The default admin of the Router Manager, {"username", "password"}, which its package writes from
|
||||
#: The default admin of the Router Manager, {"username", "password"}, which the package's postinst writes from
|
||||
#: its debconf answers; setup creates the account and removes the file.
|
||||
MANAGER_ADMIN = pathlib.Path('/etc/vpn-router-manager/admin.json')
|
||||
MANAGER_ADMIN = pathlib.Path('/etc/vpn-router/manager-admin.json')
|
||||
|
||||
#: The password of the metrics service account, which setup makes and keeps (root only).
|
||||
METRICS_SECRET = pathlib.Path('/etc/vpn-router/metrics.secret')
|
||||
@@ -275,7 +275,7 @@ def filter_block(ctx):
|
||||
'# BOOTSTRAP RULES END',
|
||||
]
|
||||
|
||||
if vpnrouter.MANAGER.exists() and interfaces:
|
||||
if interfaces:
|
||||
port = vpnrouter.manager_port()
|
||||
lines += [
|
||||
'',
|
||||
@@ -298,7 +298,7 @@ def filter_block(ctx):
|
||||
publish = ctx['pki_publish']
|
||||
ports = [port for wanted, port in ((ctx['web_enabled'] or 'https' in publish or ctx['pki_acme'],
|
||||
ctx['https_web_port']),
|
||||
(vpnrouter.MANAGER.exists(), ctx['https_manager_port']),
|
||||
(True, ctx['https_manager_port']),
|
||||
(vpnrouter.metrics_ready(ctx), ctx['metrics_https_port']),
|
||||
(vpnrouter.webdav_ready(ctx), ctx['webdav_port']),
|
||||
('http-80' in publish, vpnrouter.ACME_HTTP_PORT),
|
||||
@@ -697,8 +697,8 @@ def manage_caddy(cfg, ctx):
|
||||
"""Run Caddy, the HTTPS proxy of the router's services and the server of the web sites, while either is wanted, and
|
||||
stop it when not.
|
||||
|
||||
While HTTPS is ready, CADDYFILE serves the web service on https.web_port, while the manager is installed the
|
||||
manager on https.manager_port, while metrics are enabled the metrics service on metrics.https_port, and while
|
||||
While HTTPS is ready, CADDYFILE serves the web service on https.web_port, the manager on
|
||||
https.manager_port, while metrics are enabled the metrics service on metrics.https_port, and while
|
||||
WebDAV is ready WebDAV on sites.webdav_port, all for wan.local_fqdn with a certificate from Let's Encrypt, and all
|
||||
calling the service on its loopback address. It also serves the CA files of vpnrouter_pki.PUBLISH_DIR at /pki/ on
|
||||
the endpoints of pki.publish that are Caddy's, and an ACME server at /acme/<name>/ on https.web_port for each
|
||||
@@ -778,7 +778,7 @@ def manage_caddy(cfg, ctx):
|
||||
os.chown(folder / file, 0, group)
|
||||
vpnrouter_sites.ensure_folders(site['name'] for site in sites)
|
||||
names = vpnrouter.issuing_cas(cfg)
|
||||
caddy_ctx = dict(ctx, https=https, manager_port=vpnrouter.manager_port() if vpnrouter.MANAGER.exists() else 0,
|
||||
caddy_ctx = dict(ctx, https=https, manager_port=vpnrouter.manager_port(),
|
||||
pki_publish_dir=str(vpnrouter_pki.PUBLISH_DIR),
|
||||
pki_cas=[{'id': name, 'name': names[name]['name'].strip(),
|
||||
'cert': str(CADDY_PKI_DIR / name / 'cert.pem'),
|
||||
@@ -998,14 +998,14 @@ def progress(state, step, error=None):
|
||||
|
||||
|
||||
def start_bootstrap():
|
||||
"""Start the bootstrap services while no run has succeeded; a unit that is not installed is skipped."""
|
||||
"""Start the bootstrap service while no run has succeeded."""
|
||||
if not SETUP_DONE.exists():
|
||||
for unit in BOOTSTRAP_UNITS:
|
||||
run(['systemctl', 'start', '--no-block', unit], check=False)
|
||||
|
||||
|
||||
def end_bootstrap(ctx):
|
||||
"""After the first successful run: write SETUP_DONE, close the bootstrap ports and stop the bootstrap services."""
|
||||
"""After the first successful run: write SETUP_DONE, close the bootstrap ports and stop the bootstrap service."""
|
||||
if SETUP_DONE.exists():
|
||||
return
|
||||
SETUP_DONE.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/python3
|
||||
"""Upgrade the router's package, vpn-router, or with --system every package of the system, recording the state and
|
||||
the output.
|
||||
|
||||
Started by the Router Manager as the transient unit vpn-router-manager-upgrade, or with --system
|
||||
vpn-router-manager-system-upgrade (systemd-run), so it runs outside the manager's unit: the
|
||||
restarts of the manager and of the router's web service that the package's scripts make do not
|
||||
stop it. Usage: upgrade [--system] <user>, the user who started it.
|
||||
|
||||
The state file, STATE_FILE or with --system SYSTEM_STATE_FILE, holds the state, running while it
|
||||
runs, then succeeded or failed, with the user, the start and the end, the exit status of apt-get
|
||||
and the installed versions of PACKAGES before and after; it is replaced by a rename, so a reader
|
||||
never sees half of it. The log file, LOG_FILE or SYSTEM_LOG_FILE, holds the output of dpkg and
|
||||
apt-get, from the start of the run. A dpkg run that was interrupted is finished first
|
||||
(dpkg --configure -a). Then apt-get install --only-upgrade PACKAGES, or with --system apt-get
|
||||
upgrade, which upgrades the installed packages without installing or removing any. apt-get waits
|
||||
up to LOCK_SECONDS for the dpkg lock, which Ubuntu's apt-daily or unattended-upgrades may hold,
|
||||
takes the installed version of a changed configuration file and asks nothing.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
STATE_DIR = '/var/lib/vpn-router'
|
||||
STATE_FILE = os.path.join(STATE_DIR, 'upgrade.json')
|
||||
LOG_FILE = os.path.join(STATE_DIR, 'upgrade.log')
|
||||
SYSTEM_STATE_FILE = os.path.join(STATE_DIR, 'system-upgrade.json')
|
||||
SYSTEM_LOG_FILE = os.path.join(STATE_DIR, 'system-upgrade.log')
|
||||
|
||||
PACKAGES = ('vpn-router',)
|
||||
|
||||
#: Seconds apt-get waits for the dpkg lock.
|
||||
LOCK_SECONDS = 300
|
||||
|
||||
#: The environment of dpkg and apt-get: no questions, the installed configuration files kept, and needrestart left out,
|
||||
#: as the package's scripts restart their own services.
|
||||
ENVIRONMENT = {
|
||||
'DEBIAN_FRONTEND': 'noninteractive',
|
||||
'UCF_FORCE_CONFFOLD': '1',
|
||||
'APT_LISTCHANGES_FRONTEND': 'none',
|
||||
'NEEDRESTART_SUSPEND': '1',
|
||||
}
|
||||
|
||||
|
||||
def now():
|
||||
return time.strftime('%Y-%m-%dT%H:%M:%S%z')
|
||||
|
||||
|
||||
def versions():
|
||||
"""The installed version of each of PACKAGES, None for one that is not installed."""
|
||||
found = {}
|
||||
for package in PACKAGES:
|
||||
result = subprocess.run(['dpkg-query', '-W', '-f=${Version}', package], capture_output=True, text=True)
|
||||
found[package] = (result.stdout.strip() or None) if result.returncode == 0 else None
|
||||
return found
|
||||
|
||||
|
||||
def save(state, path):
|
||||
"""Write the state to the file of path by a rename."""
|
||||
temporary = path + '.new'
|
||||
with open(temporary, 'w', encoding='utf-8') as handle:
|
||||
json.dump(state, handle)
|
||||
handle.write('\n')
|
||||
os.chmod(temporary, 0o644)
|
||||
os.replace(temporary, path)
|
||||
|
||||
|
||||
def main(argv):
|
||||
system = argv[:1] == ['--system']
|
||||
if system:
|
||||
argv = argv[1:]
|
||||
if len(argv) != 1:
|
||||
print('usage: upgrade [--system] <user>', file=sys.stderr)
|
||||
return 2
|
||||
state_file, log_file = (SYSTEM_STATE_FILE, SYSTEM_LOG_FILE) if system else (STATE_FILE, LOG_FILE)
|
||||
os.makedirs(STATE_DIR, exist_ok=True)
|
||||
state = {'state': 'running', 'user': argv[0], 'started': now(), 'finished': None, 'exit_status': None,
|
||||
'before': versions(), 'after': None}
|
||||
save(state, state_file)
|
||||
environment = dict(os.environ, **ENVIRONMENT)
|
||||
with open(log_file, 'w', encoding='utf-8') as log:
|
||||
os.chmod(log_file, 0o644)
|
||||
status = 1
|
||||
for command in (
|
||||
['dpkg', '--configure', '-a'],
|
||||
['apt-get', '-y', '-q', '-o', f'DPkg::Lock::Timeout={LOCK_SECONDS}', '-o', 'Dpkg::Options::=--force-confdef',
|
||||
'-o', 'Dpkg::Options::=--force-confold', *(['upgrade'] if system else ['install', '--only-upgrade', *PACKAGES])],
|
||||
):
|
||||
log.write(f'$ {" ".join(command)}\n')
|
||||
log.flush()
|
||||
try:
|
||||
status = subprocess.run(command, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, env=environment).returncode
|
||||
except OSError as exc:
|
||||
log.write(f'{exc}\n')
|
||||
status = 1
|
||||
if status != 0:
|
||||
break
|
||||
log.write(f'exit status {status}\n')
|
||||
state.update(state='succeeded' if status == 0 else 'failed', finished=now(), exit_status=status, after=versions())
|
||||
save(state, state_file)
|
||||
return status
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -158,12 +158,11 @@ ZONE_NAME = re.compile(r'^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-
|
||||
DNS_DOMAIN = re.compile(r'^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$')
|
||||
DNS_DOMAINS_MAX = 16
|
||||
|
||||
#: The ports of the bootstrap services: the Router Manager's and the router's.
|
||||
BOOTSTRAP_PORTS = (17080, 17081)
|
||||
#: The ports of the bootstrap service.
|
||||
BOOTSTRAP_PORTS = (17081,)
|
||||
|
||||
#: The Router Manager, vpn-router-manager, when it is installed, its settings and its port when they set none.
|
||||
MANAGER = pathlib.Path('/usr/lib/vpn-router-manager/manager')
|
||||
MANAGER_CONFIG = pathlib.Path('/etc/vpn-router-manager/manager.json')
|
||||
#: The settings of the Router Manager, and its port when they set none.
|
||||
MANAGER_CONFIG = pathlib.Path('/etc/vpn-router/manager.json')
|
||||
MANAGER_PORT = 7080
|
||||
|
||||
#: Where vpn-router-setup installs Caddy from, https.caddy_source: the Ubuntu archive or Caddy's own repository.
|
||||
|
||||
@@ -52,8 +52,7 @@ UNIT = 'vpn-router-backup.service'
|
||||
TIMER = 'vpn-router-backup.timer'
|
||||
|
||||
#: The state a backup copies: directories and files, each where it is on the system.
|
||||
TREES = ('/etc/vpn-router', '/etc/wireguard', '/etc/ufw', '/etc/default/ufw', '/etc/vpn-router-manager',
|
||||
str(vpnrouter_sites.SITES_DIR))
|
||||
TREES = ('/etc/vpn-router', '/etc/wireguard', '/etc/ufw', '/etc/default/ufw', str(vpnrouter_sites.SITES_DIR))
|
||||
|
||||
#: The databases a backup always dumps, each while it exists: the dump -> the database and its password file.
|
||||
DUMPS = {'postgresql/vpn-router-sites.dump': (vpnrouter_sites.DATABASE, vpnrouter_sites.DATABASE_SECRET),
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
"""The settings of the Router Manager and its listening loop.
|
||||
|
||||
The settings file (CONFIG_FILE unless another is given) sets, all optional: router_url, database,
|
||||
listen, bind, port, terraform_dir and iac_tool. bind is the one address to listen on. Without
|
||||
router_url, terraform_dir names the Terraform root module whose output router_web_url gives the
|
||||
URL of the router's web service, read with iac_tool, terraform (the default) or tofu; dev.sh uses
|
||||
it to run the manager on a workstation. A setting that is not given comes from the router's
|
||||
configuration, ROUTER_CONFIG_FILE: without bind the manager listens on the addresses of the
|
||||
interfaces listen names, internal, external or both (the default), and on the loopback address,
|
||||
where the router's HTTPS proxy calls it, router_url is the first address and web.port of the
|
||||
router's web service, and database is the DATABASE database on this host, with the password in
|
||||
DATABASE_SECRET.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.parse
|
||||
from http.server import ThreadingHTTPServer
|
||||
|
||||
import vpnrouter_net
|
||||
|
||||
CONFIG_FILE = '/etc/vpn-router/manager.json'
|
||||
ROUTER_CONFIG_FILE = '/etc/vpn-router/vpn-router.json'
|
||||
DATABASE_SECRET = '/etc/vpn-router/manager-database.secret'
|
||||
|
||||
#: The role and the database the manager creates on the router.
|
||||
DATABASE = 'vpn-router-manager'
|
||||
|
||||
#: The port when port is not set.
|
||||
DEFAULT_PORT = 7080
|
||||
|
||||
#: The port of the router's web service when web.port is not set.
|
||||
ROUTER_PORT = 7081
|
||||
|
||||
#: The HTTPS port of the router's web service, on its HTTPS proxy, when https.web_port is not set.
|
||||
ROUTER_HTTPS_PORT = 7444
|
||||
|
||||
#: Seconds the Terraform outputs are kept; terraform output is not cheap.
|
||||
OUTPUTS_SECONDS = 30
|
||||
|
||||
_outputs = {}
|
||||
_outputs_lock = threading.Lock()
|
||||
|
||||
|
||||
def read_json(path):
|
||||
"""The object in a JSON file, or {} when the file is missing or holds no object."""
|
||||
try:
|
||||
with open(path, encoding='utf-8') as handle:
|
||||
data = json.load(handle)
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def text_setting(configuration, name):
|
||||
"""A string setting, or '' when it is missing or not a string."""
|
||||
value = configuration.get(name)
|
||||
return value.strip() if isinstance(value, str) else ''
|
||||
|
||||
|
||||
def port_setting(value, default):
|
||||
"""A port number, or the default when the value is not one."""
|
||||
return value if isinstance(value, int) and not isinstance(value, bool) and 1 <= value <= 65535 else default
|
||||
|
||||
|
||||
def terraform_outputs(directory, tool):
|
||||
"""The outputs of the Terraform root directory read with the tool, terraform or tofu, kept for OUTPUTS_SECONDS, or
|
||||
{} when they cannot be read."""
|
||||
with _outputs_lock:
|
||||
cached = _outputs.get(directory)
|
||||
if cached and time.monotonic() - cached[0] < OUTPUTS_SECONDS:
|
||||
return cached[1]
|
||||
try:
|
||||
result = subprocess.run([tool, f'-chdir={directory}', 'output', '-json', '-no-color'],
|
||||
capture_output=True, text=True, timeout=60,
|
||||
env=dict(os.environ, TF_IN_AUTOMATION='1'))
|
||||
outputs = json.loads(result.stdout) if result.returncode == 0 else {}
|
||||
except (OSError, subprocess.TimeoutExpired, ValueError):
|
||||
outputs = {}
|
||||
if not isinstance(outputs, dict):
|
||||
outputs = {}
|
||||
_outputs[directory] = (time.monotonic(), outputs)
|
||||
return outputs
|
||||
|
||||
|
||||
def output_value(outputs, name):
|
||||
"""The value of a Terraform output, or None when it is missing."""
|
||||
output = outputs.get(name)
|
||||
return output.get('value') if isinstance(output, dict) else None
|
||||
|
||||
|
||||
def listen(config_file):
|
||||
"""Where the manager listens, read now: ([(address, port), ...], ''), or ([], the reason) while no address is known."""
|
||||
configuration = read_json(config_file)
|
||||
bind = text_setting(configuration, 'bind')
|
||||
port = port_setting(configuration.get('port'), DEFAULT_PORT)
|
||||
if bind:
|
||||
return [(bind, port)], ''
|
||||
addresses = vpnrouter_net.listen_addresses(read_json(ROUTER_CONFIG_FILE), text_setting(configuration, 'listen'))
|
||||
if not addresses:
|
||||
return [], "the router's addresses to listen on are not known yet"
|
||||
return [(address, port) for address in [*addresses, vpnrouter_net.LOOPBACK]], ''
|
||||
|
||||
|
||||
def settings(config_file):
|
||||
"""The settings read now: router_url and database, with the router's defaults for those not set."""
|
||||
configuration = read_json(config_file)
|
||||
result = {name: text_setting(configuration, name) for name in ('router_url', 'database')}
|
||||
directory = text_setting(configuration, 'terraform_dir')
|
||||
if directory and not result['router_url']:
|
||||
tool = 'tofu' if text_setting(configuration, 'iac_tool') == 'tofu' else 'terraform'
|
||||
url = output_value(terraform_outputs(os.path.expanduser(directory), tool), 'router_web_url')
|
||||
if isinstance(url, str):
|
||||
result['router_url'] = url
|
||||
if os.path.exists(ROUTER_CONFIG_FILE):
|
||||
router = read_json(ROUTER_CONFIG_FILE)
|
||||
if not result['database']:
|
||||
try:
|
||||
with open(DATABASE_SECRET, encoding='utf-8') as handle:
|
||||
password = handle.read().strip()
|
||||
except OSError:
|
||||
password = ''
|
||||
# The password, of URL-safe characters, is written unquoted.
|
||||
if password:
|
||||
result['database'] = f'host=localhost dbname={DATABASE} user={DATABASE} password={password}'
|
||||
if not result['router_url']:
|
||||
targets, _ = vpnrouter_net.web_listen(router, ROUTER_PORT)
|
||||
if targets:
|
||||
result['router_url'] = f'http://{targets[0][0]}:{targets[0][1]}'
|
||||
result['router_url'] = result['router_url'].rstrip('/')
|
||||
return result
|
||||
|
||||
|
||||
def status_url(config_file, host, address, https):
|
||||
"""The URL of the router's status page for a browser that reached the manager as host on its address.
|
||||
|
||||
On the router, while neither router_url nor terraform_dir is set, it has host, without its
|
||||
port, so the link works by whatever name or address the browser used: with https, a call
|
||||
through the router's HTTPS proxy, https and https.web_port; else, while the router's web
|
||||
service listens on address, http and web.port. Otherwise it is router_url, or '' without one.
|
||||
"""
|
||||
configuration = read_json(config_file)
|
||||
try:
|
||||
hostname = urllib.parse.urlsplit(f'//{host}').hostname
|
||||
except ValueError:
|
||||
hostname = None
|
||||
if (hostname and os.path.exists(ROUTER_CONFIG_FILE)
|
||||
and not text_setting(configuration, 'router_url') and not text_setting(configuration, 'terraform_dir')):
|
||||
name = f'[{hostname}]' if ':' in hostname else hostname
|
||||
router = read_json(ROUTER_CONFIG_FILE)
|
||||
if https:
|
||||
options = router.get('https') if isinstance(router.get('https'), dict) else {}
|
||||
return f'https://{name}:{port_setting(options.get("web_port"), ROUTER_HTTPS_PORT)}'
|
||||
targets, _ = vpnrouter_net.web_listen(router, ROUTER_PORT)
|
||||
ports = [port for listened, port in targets if listened == address]
|
||||
if ports:
|
||||
return f'http://{name}:{ports[0]}'
|
||||
return settings(config_file)['router_url']
|
||||
|
||||
|
||||
def serve(wanted, handler, log, interval):
|
||||
"""Work out where to listen every interval seconds with wanted, and run an HTTP server of handler at each place.
|
||||
|
||||
wanted answers ([(address, port), ...], '') or ([], the reason not to listen). A server whose
|
||||
place is no longer wanted is stopped, and a new one listens at each new place; a place that
|
||||
cannot be bound is tried again the next round. Every new message is logged with log. A request
|
||||
whose client went away is not logged; any other exception a request, a thread or the process
|
||||
does not handle is logged with log in one line, without a traceback. Does not return.
|
||||
"""
|
||||
def failed(request, client_address):
|
||||
failure = sys.exc_info()[1]
|
||||
if not isinstance(failure, ConnectionError):
|
||||
log(f'a request from {client_address[0]} failed: {type(failure).__name__}: {failure}')
|
||||
|
||||
def thread_failed(hook):
|
||||
if not issubclass(hook.exc_type, (SystemExit, ConnectionError)):
|
||||
log(f'{hook.thread.name if hook.thread else "a thread"} failed: {hook.exc_type.__name__}: {hook.exc_value}')
|
||||
|
||||
threading.excepthook = thread_failed
|
||||
sys.excepthook = lambda kind, value, _: log(f'failed: {kind.__name__}: {value}')
|
||||
servers, reported = {}, None
|
||||
while True:
|
||||
targets, reason = wanted()
|
||||
for target in [target for target in servers if target not in targets]:
|
||||
server, thread = servers.pop(target)
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread.join()
|
||||
messages = [reason] if reason else []
|
||||
for target in targets:
|
||||
if target in servers:
|
||||
continue
|
||||
try:
|
||||
server = ThreadingHTTPServer(target, handler)
|
||||
except OSError as exc:
|
||||
messages.append(f'cannot listen on {target[0]}:{target[1]}: {exc}')
|
||||
continue
|
||||
server.handle_error = failed
|
||||
thread = threading.Thread(target=server.serve_forever, name=f'server {target[0]}', daemon=True)
|
||||
thread.start()
|
||||
servers[target] = (server, thread)
|
||||
if servers:
|
||||
messages.append('serving on ' + ', '.join(f'http://{address}:{port}' for address, port in servers))
|
||||
message = '; '.join(messages)
|
||||
if message and message != reported:
|
||||
log(message)
|
||||
reported = message
|
||||
time.sleep(interval)
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Google Cloud Platform.
|
||||
"""Google Cloud.
|
||||
|
||||
No platform-specific configuration is currently required.
|
||||
|
||||
|
||||
@@ -179,7 +179,7 @@ def taken_ports(cfg):
|
||||
cfg['sites']['webdav_port']: 'sites.webdav_port', vpnrouter.WEBDAV_LOOPBACK_PORT: 'rclone\'s WebDAV',
|
||||
53: 'DNS'}
|
||||
for port in vpnrouter.BOOTSTRAP_PORTS:
|
||||
taken[port] = 'the bootstrap services'
|
||||
taken[port] = 'the bootstrap service'
|
||||
if cfg['openvpn']['protocol'] == 'tcp':
|
||||
taken[cfg['openvpn']['port']] = 'openvpn.port'
|
||||
for item in cfg['docker']['exposed_ports']:
|
||||
|
||||
@@ -78,8 +78,7 @@ default the address the call came in on, is the last entry of its X-Forwarded-Fo
|
||||
|
||||
/ and /status show only the status, as much as web.status_content says (see shown): basic, the
|
||||
default, the overall status, the time and the client's address (its address as for the rate limit
|
||||
below); standard also the package version, the installed version of vpn-router-manager
|
||||
(manager_version, null when it is not installed) and the number of active and other services; full
|
||||
below); standard also the package version and the number of active and other services; full
|
||||
whether each service runs, whether Docker is installed, how many of the site-to-site connections are established
|
||||
(site_to_site: connections and established, null when swanctl cannot be asked), and IKEv2, OpenVPN
|
||||
and WireGuard. No configuration data, key or connection name is shown, and no address but the client's.
|
||||
|
||||
@@ -59,10 +59,7 @@ def postgresql_clusters():
|
||||
def collect(state):
|
||||
"""The status document. state says which features the router has."""
|
||||
units = {'vpn-router-setup': unit_state('vpn-router-setup.service'), 'slapd': unit_state('slapd.service'),
|
||||
**postgresql_clusters()}
|
||||
manager_version = package_version('vpn-router-manager')
|
||||
if manager_version:
|
||||
units['vpn-router-manager'] = unit_state('vpn-router-manager.service')
|
||||
'vpn-router-manager': unit_state('vpn-router-manager.service'), **postgresql_clusters()}
|
||||
if state.get('site_to_site') or state.get('p2s'):
|
||||
units['strongswan'] = unit_state('strongswan.service')
|
||||
if state.get('wireguard'):
|
||||
@@ -73,7 +70,6 @@ def collect(state):
|
||||
status = {
|
||||
'status': 'ok' if all(value == 'active' for value in units.values()) else 'degraded',
|
||||
'version': package_version(),
|
||||
'manager_version': manager_version,
|
||||
'time': time.strftime('%Y-%m-%dT%H:%M:%S%z'),
|
||||
'units': units,
|
||||
'docker': docker_status(),
|
||||
@@ -96,7 +92,7 @@ def shown(status, content, client):
|
||||
"""The status document as web.status_content shows it to the client at its address.
|
||||
|
||||
Every content has status, time and client_ip, the client's address, and content, which one it is: basic nothing
|
||||
more; standard adds version, manager_version and services, the number of active units and of units in every
|
||||
more; standard adds version and services, the number of active units and of units in every
|
||||
other state; full adds the whole status document of collect. Content that is not one of
|
||||
vpnrouter.STATUS_CONTENTS, or not set, is basic.
|
||||
"""
|
||||
@@ -107,7 +103,7 @@ def shown(status, content, client):
|
||||
document = {'status': status['status'], 'content': content, 'time': status['time'], 'client_ip': client}
|
||||
if content == 'standard':
|
||||
active = sum(1 for value in status['units'].values() if value == 'active')
|
||||
document.update(version=status['version'], manager_version=status['manager_version'],
|
||||
document.update(version=status['version'],
|
||||
services={'active': active, 'failed': len(status['units']) - active})
|
||||
return document
|
||||
|
||||
@@ -242,8 +238,6 @@ def text_of(status):
|
||||
if 'version' in status:
|
||||
lines.append(f'Version: {status["version"] or "unknown"}')
|
||||
lines += ['', f'Client IP: {status["client_ip"]}']
|
||||
if 'manager_version' in status:
|
||||
lines.append(f'Router Manager: {status["manager_version"] or "not installed"}')
|
||||
if 'services' in status:
|
||||
lines.append(f'Services: {status["services"]["active"]} active, {status["services"]["failed"]} failed')
|
||||
lines += [f'{name}: {value}' for name, value in status.get('units', {}).items()]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/bin/sh
|
||||
# Wait until libpq is in the dynamic linker cache, where psycopg looks it up.
|
||||
# ExecStartPre= of vpn-router-setup.service, vpn-router-web.service and vpn-router-metrics.service;
|
||||
# TimeoutStartSec= of the unit bounds the wait.
|
||||
# ExecStartPre= of vpn-router-setup.service, vpn-router-web.service, vpn-router-metrics.service and
|
||||
# vpn-router-manager.service; TimeoutStartSec= of the unit bounds the wait.
|
||||
|
||||
reported=
|
||||
until ldconfig -p | grep -q '^[[:space:]]*libpq\.so\.5 '; do
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"router_url": "http://10.0.0.4:7081",
|
||||
"database": "host=localhost dbname=vpn-router-manager user=vpn-router-manager password=change-me",
|
||||
"listen": "both",
|
||||
"port": 7080
|
||||
}
|
||||
@@ -72,7 +72,7 @@ http://{{ local_fqdn }} {
|
||||
}
|
||||
}
|
||||
{% endif %}
|
||||
{%- if https and manager_port %}
|
||||
{%- if https %}
|
||||
{{ local_fqdn }}:{{ https_manager_port }} {
|
||||
reverse_proxy {{ loopback }}:{{ manager_port }}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user