#!/bin/bash # Installs Überbringer on a fresh Debian or Ubuntu host, behind Caddy, which # obtains and renews the TLS certificate itself. Ports 80 and 443 must be # free for Caddy. # # Usage: sudo ./install.sh # # Installs the latest release. To install a given release, v0.2.0 or later, # name its tag: # sudo UBERBRINGER_VERSION=v0.2.0 ./install.sh # Re-running the script upgrades the binary, the systemd unit and Caddy, # rewrites Überbringer's Caddy site and restarts the service. It keeps the # config, an edited Caddyfile and any `systemctl edit uberbringer` drop-ins. set -euo pipefail DOMAIN="${1:-}" ACME_EMAIL="${2:-}" PRINTER_ADDRESS="${3:-}" LOG=/var/log/uberbringer-install.log CONFIG_DIR=/etc/uberbringer CONFIG="$CONFIG_DIR/config.toml" TOKEN_FILE="$CONFIG_DIR/initial-token" BIN=/usr/local/bin/uberbringer SERVICE_USER=uberbringer # The vendor unit path for locally installed software. Units in # /etc/systemd/system take precedence over it, so operator changes belong in # drop-ins there. UNIT_FILE=/usr/local/lib/systemd/system/uberbringer.service CADDYFILE=/etc/caddy/Caddyfile CADDY_SITE=/etc/caddy/uberbringer.caddy CADDY_LOG=/var/log/caddy/uberbringer-access.log CADDY_IMPORT="import $CADDY_SITE" CADDY_KEYRING=/usr/share/keyrings/caddy-stable-archive-keyring.gpg CADDY_SOURCES=/etc/apt/sources.list.d/caddy-stable.list CADDY_REPO=https://dl.cloudsmith.io/public/caddy/stable # Gitea resolves the tag "latest" to the newest release that is neither a # draft nor a prerelease. RELEASE_URL="https://git.anomalous.dev/57_Wolve/uberbringer/releases/download/${UBERBRINGER_VERSION:-latest}" CONFIG_CREATED=0 WORK_DIR="" # Set by read_settings from the config, as the daemon reads it. BODY_LIMIT="" UPSTREAM="" if [[ "$EUID" -ne 0 ]]; then echo -e "\e[31m[FATAL]\e[39m This script must be run as root." >&2 exit 1 fi if [[ -z "$DOMAIN" || -z "$ACME_EMAIL" || -z "$PRINTER_ADDRESS" ]]; then echo "Usage: $0 " >&2 exit 1 fi # The domain and the email go unquoted into the Caddy site file, and the # printer address into a TOML string, so each is limited to the characters # its kind of value needs. The domain must be a DNS name with at least one # dot that a certificate can be issued for, so not an IP address. DOMAIN_RE='^[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)+$' if [[ ! "$DOMAIN" =~ $DOMAIN_RE || "$DOMAIN" =~ ^[0-9.]+$ ]]; then echo "Invalid domain: $DOMAIN (expected a DNS name such as printer.example.com)" >&2 exit 1 fi if [[ ! "$ACME_EMAIL" =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+$ ]]; then echo "Invalid email address: $ACME_EMAIL" >&2 exit 1 fi # A single colon is a host:port pair; an IPv6 address has at least two. if [[ ! "$PRINTER_ADDRESS" =~ ^[A-Za-z0-9.:-]+$ || "$PRINTER_ADDRESS" =~ ^[^:]*:[^:]*$ ]]; then echo "Invalid printer address: $PRINTER_ADDRESS (expected an IP address or host name without a port; a port other than 9100 goes in printer.port in the config)" >&2 exit 1 fi echo -e "\n\nINSTALL LOG FOR Uberbringer: $(date --rfc-3339=seconds)\n" >> "$LOG" info() { echo -e "\e[34m[INFO]\e[39m $1" echo "[INFO] $1" >> "$LOG" } warn() { echo -e "\e[33m[WARN]\e[39m $1" echo "[WARN] $1" >> "$LOG" } debug() { if [[ -n "${DEBUG:-}" ]]; then echo -e "\e[96m[DEBUG]\e[39m $1" fi echo "[DEBUG] $1" >> "$LOG" } # fatal writes to stderr so its message is not swallowed when it runs inside a # command substitution. fatal() { echo -e "\e[31m[FATAL]\e[39m $1" >&2 echo "[FATAL] $1" >> "$LOG" exit 1 } require() { command -v "$1" > /dev/null 2>&1 || fatal "Couldn't find $1 - please install it and rerun the script." } cleanup() { if [[ -n "$WORK_DIR" ]]; then rm -rf "$WORK_DIR" fi } detect_arch() { case "$(uname -m)" in x86_64) echo "amd64" ;; aarch64 | arm64) echo "arm64" ;; armv7l) echo "armv7" ;; armv6l) echo "armv6" ;; *) fatal "Unsupported architecture: $(uname -m)" ;; esac } # apt_install installs or upgrades packages without asking anything. Its # output goes to the log, where a question would go unseen, so dpkg keeps a # changed configuration file such as the Caddyfile instead of asking, and # nothing is read from the terminal. apt_install() { apt-get install -y -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold \ "$@" < /dev/null >> "$LOG" 2>&1 } install_base_packages() { info "Installing curl and gnupg..." export DEBIAN_FRONTEND=noninteractive # A broken third-party source makes the update fail even when the # packages below are installed or still installable, so only the install # is fatal. apt-get update >> "$LOG" 2>&1 || warn "apt-get update failed; trying the install anyway (see $LOG)." apt_install curl gnupg || fatal "apt-get install failed; see $LOG." require curl require sha256sum require systemctl require runuser } # download_release fetches the release archive and checksums.txt into # WORK_DIR, verifies the archive and unpacks it there. download_release() { local arch archive arch="$(detect_arch)" archive="uberbringer_linux_${arch}.tar" info "Downloading ${archive} from ${RELEASE_URL}..." curl -fsSL -o "$WORK_DIR/checksums.txt" "$RELEASE_URL/checksums.txt" || fatal "Couldn't download checksums.txt from $RELEASE_URL." curl -fsSL -o "$WORK_DIR/$archive" "$RELEASE_URL/$archive" || fatal "Couldn't download $archive from $RELEASE_URL." info "Verifying ${archive}..." # A leading * on the file name marks a binary-mode checksum line. awk -v f="$archive" '$2 == f || $2 == "*" f' "$WORK_DIR/checksums.txt" > "$WORK_DIR/archive.sha256" [[ -s "$WORK_DIR/archive.sha256" ]] || fatal "checksums.txt has no entry for $archive." (cd "$WORK_DIR" && sha256sum --check --strict --quiet archive.sha256) >> "$LOG" 2>&1 || fatal "$archive does not match checksums.txt; nothing was installed." mkdir "$WORK_DIR/release" tar -xf "$WORK_DIR/$archive" -C "$WORK_DIR/release" [[ -f "$WORK_DIR/release/uberbringer" ]] || fatal "$archive does not contain the uberbringer binary." [[ -f "$WORK_DIR/release/packaging/uberbringer.service" ]] || fatal "$archive does not contain packaging/uberbringer.service; this script installs v0.2.0 or later." } install_binary() { install -m 0755 "$WORK_DIR/release/uberbringer" "$BIN" local version # Run from its installed path: WORK_DIR may be on a noexec /tmp. version="$("$BIN" version)" || fatal "$BIN does not run on this host." info "Installed $version" } create_service_user() { if ! id "$SERVICE_USER" > /dev/null 2>&1; then info "Creating system user $SERVICE_USER..." useradd --system --no-create-home --shell /usr/sbin/nologin "$SERVICE_USER" fi } write_config() { mkdir -p "$CONFIG_DIR" if [[ -f "$CONFIG" ]]; then info "Keeping existing $CONFIG; edit printer.address there to change the printer." return fi info "Creating Uberbringer config..." local secret secret="$("$BIN" secret)" # The config holds the API secret, so it is never readable by others, not # even between being written and being chmodded. ( umask 027 cat < "$CONFIG" [webserver] bind_ip = "127.0.0.1" port = 8080 [api] secret = "$secret" [printer] address = "$PRINTER_ADDRESS" [ntfy] # The unit's StateDirectory; ntfy subscriptions keep their state here. state_dir = "/var/lib/uberbringer" EOT ) chown root:"$SERVICE_USER" "$CONFIG" chmod 0640 "$CONFIG" CONFIG_CREATED=1 } # write_initial_token saves the first bearer token to a root-only file instead # of printing it, so it does not end up in terminal scrollback or the log. It # runs right after the config is created, because a re-run after a later step # failed keeps that config and writes no token. write_initial_token() { if [[ "$CONFIG_CREATED" -ne 1 ]]; then return fi rm -f "$TOKEN_FILE" ( umask 077 "$BIN" token --config "$CONFIG" > "$TOKEN_FILE" ) debug "Wrote the first API token to $TOKEN_FILE." } # config_get prints one setting as the installed binary reads it from the # config. It fails, with the reason on stderr, when the config does not # load. config_get() { "$BIN" config get --config "$CONFIG" "$1" } # read_settings checks the config before the service is restarted, and takes # from it the body limit and the address Caddy proxies to. read_settings() { local bind_ip port BODY_LIMIT="$(config_get webserver.body_limit)" || fatal "$CONFIG does not load (the reason is above). Fix it and rerun; the service was not restarted." bind_ip="$(config_get webserver.bind_ip)" port="$(config_get webserver.port)" case "$bind_ip" in 0.0.0.0) UPSTREAM="127.0.0.1:$port" ;; ::) UPSTREAM="[::1]:$port" ;; *:*) UPSTREAM="[$bind_ip]:$port" ;; *) UPSTREAM="$bind_ip:$port" ;; esac } # install_service installs the unit, restarts the service, which reads its # config only at startup, and waits for it to answer. install_service() { install -D -m 0644 "$WORK_DIR/release/packaging/uberbringer.service" "$UNIT_FILE" systemctl daemon-reload systemctl enable uberbringer >> "$LOG" 2>&1 || fatal "Enabling uberbringer.service failed; see $LOG." systemctl restart uberbringer || fatal "Restarting uberbringer.service failed; see 'journalctl -u uberbringer'." wait_for_daemon } # wait_for_daemon waits up to 15 seconds for the daemon to answer. systemd # reports the service started as soon as the process runs, before it has # opened its port or failed. wait_for_daemon() { local attempt for attempt in {1..30}; do if curl -fs -o /dev/null --max-time 2 "http://$UPSTREAM/"; then debug "Überbringer answered on $UPSTREAM after $attempt attempts." return fi sleep 0.5 done fatal "Überbringer did not answer on $UPSTREAM; see 'journalctl -u uberbringer'." } # install_caddy installs or upgrades Caddy's Debian package from Caddy's # signed apt repository. The key and the source list are fetched into # WORK_DIR first, so a failed download leaves the installed ones as they # were. install_caddy() { info "Installing Caddy from its apt repository..." # Optional keyring helpers; curl and gnupg are what the steps below need. apt_install debian-keyring debian-archive-keyring apt-transport-https || debug "Optional keyring packages are unavailable; continuing." curl -fsSL --proto '=https' --tlsv1.2 -o "$WORK_DIR/caddy.key" "$CADDY_REPO/gpg.key" && gpg --dearmor --yes -o "$WORK_DIR/caddy.gpg" "$WORK_DIR/caddy.key" || fatal "Couldn't fetch Caddy's signing key." curl -fsSL --proto '=https' --tlsv1.2 -o "$WORK_DIR/caddy.list" "$CADDY_REPO/debian.deb.txt" || fatal "Couldn't fetch Caddy's apt source list." install -m 0644 "$WORK_DIR/caddy.gpg" "$CADDY_KEYRING" install -m 0644 "$WORK_DIR/caddy.list" "$CADDY_SOURCES" # Only Caddy's source is updated, and a failure is fatal: without its # index, apt would install the distribution's older caddy package. apt-get update -o Dir::Etc::sourcelist="$CADDY_SOURCES" -o Dir::Etc::sourceparts=- \ -o APT::Get::List-Cleanup=0 >> "$LOG" 2>&1 || fatal "Couldn't read Caddy's apt repository; see $LOG." apt_install caddy || fatal "Installing Caddy failed; see $LOG." require caddy } # managed_caddyfile prints the Caddyfile this script writes. Once the # operator edits it, it no longer matches and is kept. managed_caddyfile() { printf '%s\n' \ "# Written by Überbringer's install.sh. Your edits are kept: a re-run only" \ "# adds the import below if nothing imports it. Global options go at the" \ "# top, above every import and site." \ "$CADDY_IMPORT" } # caddyfile_is_package_default reports whether the Caddyfile is the caddy # package's file, unchanged, by the checksum dpkg recorded for it. caddyfile_is_package_default() { local packaged current packaged="$(dpkg-query -W -f='${Conffiles}\n' caddy 2> /dev/null | awk -v f="$CADDYFILE" '$1 == f { print $2; exit }' || true)" [[ -n "$packaged" ]] || return 1 current="$(md5sum "$CADDYFILE" | awk '{ print $1 }')" [[ "$current" == "$packaged" ]] } # caddyfile_imports_site reports whether a line of the Caddyfile imports the # site file, by its path or by a glob over /etc/caddy. caddyfile_imports_site() { tr -d '\r' < "$CADDYFILE" | grep -qE '^[[:space:]]*import[[:space:]]+/etc/caddy/(uberbringer\.caddy|\*\.caddy|\*)([[:space:]]|#|$)' } # validate_caddy checks the configuration as the caddy user, with its home, # so the files validation opens or creates are the caddy user's, as they are # for caddy.service. Caddy's output goes to WORK_DIR and the log. validate_caddy() { local home status=0 home="$(getent passwd caddy | cut -d: -f6)" runuser -u caddy -- env HOME="${home:-/var/lib/caddy}" \ caddy validate --config "$CADDYFILE" --adapter caddyfile > "$WORK_DIR/caddy-validate.log" 2>&1 || status=$? cat "$WORK_DIR/caddy-validate.log" >> "$LOG" return "$status" } # write_caddy_site writes Überbringer's site file and makes the Caddyfile # import it, then validates the result. If Caddy rejects it, both files are # put back as they were. write_caddy_site() { info "Configuring Caddy for $DOMAIN..." local backup="$WORK_DIR/caddy-backup" mkdir -p "$backup" if [[ -f "$CADDY_SITE" ]]; then cp -p "$CADDY_SITE" "$backup/site"; fi if [[ -f "$CADDYFILE" ]]; then cp -p "$CADDYFILE" "$backup/Caddyfile"; fi install -d -o caddy -g caddy /var/log/caddy # Created as the caddy user's file before anything opens it. if [[ ! -e "$CADDY_LOG" ]]; then install -o caddy -g caddy -m 0640 /dev/null "$CADDY_LOG" fi cat < "$CADDY_SITE" # Written by Überbringer's install.sh, which rewrites it on every run. (uberbringer_headers) { header { Strict-Transport-Security "max-age=31536000; includeSubDomains" X-Frame-Options DENY X-Content-Type-Options nosniff Referrer-Policy no-referrer -Server } } $DOMAIN { tls $ACME_EMAIL request_body { # webserver.body_limit from $CONFIG, in bytes. max_size $BODY_LIMIT } # webserver.bind_ip and webserver.port from $CONFIG. reverse_proxy $UPSTREAM { # Überbringer takes the client's address from X-Real-IP for # per-client rate limits. header_up X-Real-IP {remote_host} } import uberbringer_headers # Caddy refuses a body over max_size before Überbringer sees it, so the # refusal is the JSON error Überbringer would have sent. handle_errors 413 { import uberbringer_headers header Content-Type application/json header Cache-Control no-store respond \`{"error":"request body is too large","code":"body_too_large"}\` 413 } # Any other error, such as a 502 while Überbringer restarts, is passed # on, so Caddy logs its cause. handle_errors { error "{err.message}" {err.status_code} } log { output file $CADDY_LOG # Query strings are dropped: a misdirected client may put a token # in one. format filter { request>uri regexp "[?].*\$" "" } } } EOT chmod 0644 "$CADDY_SITE" # A missing Caddyfile, the package's untouched one and the one this # script wrote are replaced. An edited Caddyfile only gains the import # line, and keeps its owner and mode. if [[ ! -f "$CADDYFILE" ]] || cmp -s "$CADDYFILE" <(managed_caddyfile) || caddyfile_is_package_default; then if [[ -f "$CADDYFILE" ]] && ! cmp -s "$CADDYFILE" <(managed_caddyfile); then cp -p "$CADDYFILE" "$CADDYFILE.default" info "Replacing the package's default Caddyfile (kept as $CADDYFILE.default)..." fi managed_caddyfile > "$CADDYFILE" chmod 0644 "$CADDYFILE" elif ! caddyfile_imports_site; then cp -p "$CADDYFILE" "$CADDYFILE.bak" printf '\n%s\n' "$CADDY_IMPORT" >> "$CADDYFILE" info "Added '$CADDY_IMPORT' to your $CADDYFILE (previous copy kept as $CADDYFILE.bak)." fi if ! validate_caddy; then if [[ -f "$backup/site" ]]; then cp -p "$backup/site" "$CADDY_SITE"; else rm -f "$CADDY_SITE"; fi if [[ -f "$backup/Caddyfile" ]]; then cp -p "$backup/Caddyfile" "$CADDYFILE"; else rm -f "$CADDYFILE"; fi local reason reason="$(grep -m1 '^Error:' "$WORK_DIR/caddy-validate.log" || true)" fatal "Caddy rejected the configuration, so $CADDYFILE and $CADDY_SITE were put back as they were. ${reason:-See $LOG for the error from Caddy.}" fi } start_caddy() { systemctl enable caddy >> "$LOG" 2>&1 || fatal "Enabling caddy.service failed; see $LOG." if systemctl is-active --quiet caddy; then systemctl reload caddy || fatal "Reloading Caddy failed; see 'journalctl -u caddy'." else systemctl restart caddy || fatal "Caddy did not start; see 'journalctl -u caddy' (ports 80 and 443 must be free)." fi info "Caddy serves https://$DOMAIN and obtains or renews its certificate itself. If the site does not answer within a minute, see 'journalctl -u caddy': the domain's DNS must point here, and ports 80 and 443 must be reachable." } token_notice() { if [[ "$CONFIG_CREATED" -eq 1 ]]; then info "The first API token is in $TOKEN_FILE (readable by root only). Copy it to your client, then delete the file." return fi if [[ -s "$TOKEN_FILE" ]]; then warn "$TOKEN_FILE still holds the first API token; delete it once your client has it." fi info "Issue API tokens with: $BIN token --config $CONFIG --subject " } main() { info "Script loaded, starting the install process..." install_base_packages WORK_DIR="$(mktemp -d)" trap cleanup EXIT # Nothing else is installed unless the release downloads and matches its # checksum. download_release install_binary create_service_user write_config write_initial_token read_settings install_service install_caddy write_caddy_site start_caddy info "Uberbringer service is now installed." info "Override unit settings with 'systemctl edit uberbringer'; drop-ins survive re-runs of this script." token_notice } main