#!/usr/bin/env bash # Enroll using a locally prepared package and a short-lived root-only key file. set -euo pipefail export LC_ALL=C fail() { printf 'ERROR: %s\n' "$*" >&2; return 1; } validate_host() { local host=$1 label octet [[ -n "$host" && ${#host} -le 253 && "$host" != .* && "$host" != *. && "$host" != *..* ]] || { fail 'Invalid Headscale URL host'; return 1; } if [[ "$host" =~ ^[0-9]+(\.[0-9]+){3}$ ]]; then local octets=() IFS=. read -r -a octets <<< "$host" for octet in "${octets[@]}"; do [[ "$octet" =~ ^(0|[1-9][0-9]{0,2})$ ]] && ((10#$octet <= 255)) || { fail 'Invalid Headscale IPv4 host'; return 1; } done return 0 fi [[ "$host" =~ ^[A-Za-z0-9.-]+$ ]] || { fail 'Invalid Headscale URL host'; return 1; } local labels=() IFS=. read -r -a labels <<< "$host" for label in "${labels[@]}"; do [[ "$label" =~ ^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?$ ]] || { fail 'Invalid Headscale URL host label'; return 1; } done } validate_tags() { # Tailscale tags are not DNS labels: letters, digits and dashes are valid # after the first letter, with no DNS length or final-character limit. [[ -z "$1" || "$1" =~ ^tag:[A-Za-z][A-Za-z0-9-]*(,tag:[A-Za-z][A-Za-z0-9-]*)*$ ]] || { fail 'Invalid authorized tags'; return 1; } } main() { local version='' package='' sha='' login='' login_port='' name='' auth='' tags='' action='' while (($#)); do case "$1" in --help|-h) echo 'Usage: bash tailscale.sh --check|--apply --version VERSION --package LOCAL_DEB --sha256 SHA --login-server HTTPS_URL --hostname NAME [--auth-key-file /run/platform-secrets/KEY] [--tags tag:NAME,...]'; return 0;; --check|--apply) [[ -z "$action" ]] || return 1; action=$1; shift;; --version|--package|--sha256|--login-server|--hostname|--auth-key-file|--tags) (($# >= 2)) || return 1 case "$1" in --version) version=$2;; --package) package=$2;; --sha256) sha=$2;; --login-server) login=$2;; --hostname) name=$2;; --auth-key-file) auth=$2;; --tags) tags=$2;; esac; shift 2;; *) fail "Unknown argument: $1"; return 1;; esac done local word='[a-z][a-z0-9]{0,15}' [[ $EUID == 0 && ( "$action" == --check || "$action" == --apply ) && "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ && "$sha" =~ ^[a-f0-9]{64}$ && "$name" =~ ^(dev|test|stage|prod)-$word-$word(-$word)?-(0[1-9]|[1-9][0-9])$ ]] || { fail 'Explicit root/action/version/Headscale/hostname inputs required'; return 1; } if [[ "$login" =~ ^https://([^/:?#]+)(:([0-9]{1,5}))?/?$ ]]; then local login_host=${BASH_REMATCH[1]} login_port=${BASH_REMATCH[3]} validate_host "$login_host" if [[ -n "$login_port" ]]; then [[ "$login_port" =~ ^[0-9]{1,5}$ ]] && ((10#$login_port >= 1 && 10#$login_port <= 65535)) || { fail 'Invalid Headscale port'; return 1; } fi login=${login%/} else fail 'Explicit HTTPS Headscale URL required'; return 1 fi validate_tags "$tags" [[ -f "$package" && ! -L "$package" ]] || { fail 'Prepared Tailscale DEB required'; return 1; } printf '%s %s\n' "$sha" "$package" | sha256sum -c - >/dev/null [[ $(dpkg-deb -f "$package" Package) == tailscale && $(dpkg-deb -f "$package" Version) == "$version" && $(dpkg-deb -f "$package" Architecture) == amd64 ]] || { fail 'Package identity or architecture differs'; return 1; } if command -v tailscale >/dev/null; then [[ $(tailscale version | head -n 1) == "$version" ]] || { fail 'Existing version differs; use explicit maintenance'; return 1; }; fi if [[ -n "$auth" ]]; then [[ "$auth" == /run/platform-secrets/* && "$auth" != */../* && "$auth" != */./* && -f "$auth" && ! -L "$auth" && $(stat -c %u "$auth") == 0 && $(stat -c %a "$auth") == 600 && ! -L /run/platform-secrets ]] || { fail 'Use a root-owned 0600 temporary enrollment key file'; return 1; } fi [[ "$action" == --apply ]] || { echo 'Local inputs verified; network enrollment not checked.'; return 0; } umask 077 exec 9>>/run/lock/platform-tailscale.lock; flock -n 9 || { fail 'Enrollment is already running'; return 1; } local task cleanup status='' state task=$(mktemp -d) printf -v cleanup 'rm -rf -- %q' "$task" if [[ -n "$auth" ]]; then printf -v cleanup '%s; rm -f -- %q' "$cleanup" "$auth"; fi trap "$cleanup" EXIT if ! command -v tailscale >/dev/null; then apt-get -o DPkg::Lock::Timeout=60 install -y "$package"; fi systemctl enable --now tailscaled if ! tailscale status --json > "$task/status.json" 2> "$task/error"; then fail 'Cannot inspect the existing Tailscale identity; do not reset it'; return 1 fi state=$(jq -er .BackendState "$task/status.json") || { fail 'Tailscale returned an invalid status document'; return 1; } if [[ "$state" == Running ]]; then tailscale debug prefs > "$task/prefs.json" jq -e --arg url "$login" --arg name "$name" '(.ControlURL | if type == "string" then rtrimstr("/") else "" end) == $url and .Hostname == $name' "$task/prefs.json" >/dev/null || { fail 'Existing node belongs to another controller or name'; return 1; } echo 'Existing connected identity reused; enrollment key not consumed.' elif [[ "$state" == NeedsLogin ]]; then [[ -n "$auth" ]] || { fail 'Provide a short-lived single-use Headscale enrollment key'; return 1; } local up_args=(up --login-server="$login" --hostname="$name" --accept-routes=true --auth-key="file:$auth") [[ -z "$tags" ]] || up_args+=(--advertise-tags="$tags") if ! tailscale "${up_args[@]}" > "$task/enroll-output" 2>&1; then fail 'Enrollment failed; inspect Headscale and the original node identity before retrying'; return 1 fi else fail 'Existing backend is not ready for first enrollment; inspect it without resetting identity'; return 1; fi tailscale status --json > "$task/status.json" || { fail 'Tailscale enrollment status is unavailable'; return 1; } jq -e '.BackendState == "Running" and (.Self.TailscaleIPs | length > 0)' "$task/status.json" >/dev/null || { fail 'Tailscale did not reach Running with an address'; return 1; } tailscale debug prefs > "$task/prefs.json" || { fail 'Tailscale preferences are unavailable'; return 1; } jq -e --arg url "$login" --arg name "$name" '(.ControlURL | if type == "string" then rtrimstr("/") else "" end) == $url and .Hostname == $name' "$task/prefs.json" >/dev/null || { fail 'Enrolled node belongs to another controller or name'; return 1; } echo 'Node enrollment checked. Service /32 addressing, exact route approval and cross-host access still require separate verification.' rm -rf -- "$task" [[ -z "$auth" ]] || rm -f -- "$auth" trap - EXIT } if [[ ${BASH_SOURCE[0]:-} == "$0" || -z ${BASH_SOURCE[0]:-} ]]; then main "$@"; fi