Files
arnaud.dartois 383205b9fc
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 38m21s
Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Successful in 22m18s
Heimdall Gitea / Build and scan server image (push) Successful in 8m54s
Heimdall Gitea / Build and scan agent image (push) Successful in 6m40s
Heimdall Gitea / Publish versioned installer release (push) Skipped
Heimdall Gitea / CI policy (push) Successful in 3s
Fix signed release metadata and Linux Agent deployment (#415)
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-14 11:59:38 +01:00

211 lines
13 KiB
Bash
Executable File

#!/usr/bin/env bash
# install-agent.sh — Heimdall Agent installer for Linux
set -euo pipefail
CENTRAL_URL="" SITE_TOKEN="" CENTRAL_URL_FILE="" SITE_TOKEN_FILE="" AGENT_NAME="" STATE_DIR="/var/lib/heimdall" UPDATE_PUBLIC_KEY="" ALLOW_INSECURE_HTTP=false RUN_MODE=false INSTALL_ONLY=false
INSTALL_ROOT="/opt/heimdall/agent" SERVICE_NAME="heimdall-agent" SERVICE_USER="heimdall"
while [[ $# -gt 0 ]]; do case "$1" in --central-url-file) CENTRAL_URL_FILE="$2"; shift 2;; --site-token-file) SITE_TOKEN_FILE="$2"; shift 2;; --central-url|--site-token) echo "Error: pass enrollment settings through protected files, not command-line values" >&2; exit 1;; --update-public-key) UPDATE_PUBLIC_KEY="$2"; shift 2;; --agent-name) AGENT_NAME="$2"; shift 2;; --state-dir) STATE_DIR="$2"; shift 2;; --allow-insecure-http) ALLOW_INSECURE_HTTP=true; shift;; --run) RUN_MODE=true; shift;; --install-only) INSTALL_ONLY=true; shift;; -h|--help) echo "Usage: $0 --central-url-file PATH --site-token-file PATH [--agent-name NAME] [--run | --install-only] [--update-public-key LOCAL_PEM] [--state-dir PATH] [--allow-insecure-http]"; exit 0;; *) echo "Unknown: $1" >&2; exit 1;; esac; done
read_protected_value() {
local path="$1" label="$2" mode
[[ -n "$path" && -f "$path" && ! -L "$path" ]] || { echo "Error: $label must reference a regular protected file" >&2; exit 1; }
mode=$(stat -c '%a' "$path")
(( (8#$mode & 077) == 0 )) || { echo "Error: $label file must not be accessible by group or others" >&2; exit 1; }
cat -- "$path"
}
[[ -n "$CENTRAL_URL_FILE" && -n "$SITE_TOKEN_FILE" ]] || { echo "Error: --central-url-file and --site-token-file are required" >&2; exit 1; }
CENTRAL_URL="$(read_protected_value "$CENTRAL_URL_FILE" 'Central URL')"
SITE_TOKEN="$(read_protected_value "$SITE_TOKEN_FILE" 'site token')"
[[ -n "$CENTRAL_URL" && -n "$SITE_TOKEN" ]] || { echo "Error: protected Central URL and site token files must be non-empty" >&2; exit 1; }
[[ "$RUN_MODE" == true && "$INSTALL_ONLY" == true ]] && { echo '--run and --install-only cannot be combined' >&2; exit 1; }
if [[ -n "$UPDATE_PUBLIC_KEY" && ! -f "$UPDATE_PUBLIC_KEY" ]]; then echo 'Publisher public key file is missing' >&2; exit 1; fi
CENTRAL_URL="${CENTRAL_URL%/}"
if [[ "$CENTRAL_URL" != https://* && ! ( "$ALLOW_INSECURE_HTTP" == true && "$CENTRAL_URL" == http://* ) ]]; then
echo "Error: Central URL must use HTTPS (or explicitly opt in with --allow-insecure-http on an isolated network)" >&2
exit 1
fi
ARCH=$(uname -m); case "$ARCH" in x86_64|amd64) PLATFORM="linux-x64";; aarch64|arm64) PLATFORM="linux-arm64";; armv7l|armhf) PLATFORM="linux-arm";; *) echo "Unsupported: $ARCH" >&2; exit 1;; esac
echo "Installing Heimdall Agent for $PLATFORM..."
TMP_DIR=$(mktemp -d); trap 'rm -rf "$TMP_DIR"' EXIT
missing=()
for tool in curl jq openssl python3; do command -v "$tool" >/dev/null || missing+=("$tool"); done
if ((${#missing[@]})); then
if command -v apt-get >/dev/null; then
apt-get update -qq
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "${missing[@]}"
elif command -v dnf >/dev/null; then
dnf install -y "${missing[@]}"
elif command -v apk >/dev/null; then
apk add --no-cache "${missing[@]}"
else
echo "Install these prerequisites and rerun: ${missing[*]}" >&2
exit 1
fi
fi
if command -v dotnet >/dev/null; then
DOTNET_BIN=$(command -v dotnet)
else
DOTNET_BIN="/opt/heimdall/dotnet/dotnet"
curl -fsSL --proto '=https' --proto-redir '=https' https://dot.net/v1/dotnet-install.sh -o "$TMP_DIR/dotnet-install.sh"
install -d -m 755 /opt/heimdall/dotnet
bash "$TMP_DIR/dotnet-install.sh" --channel 10.0 --runtime aspnetcore --install-dir /opt/heimdall/dotnet
fi
"$DOTNET_BIN" --list-runtimes | grep -q '^Microsoft.AspNetCore.App 10\.' || {
echo 'A compatible ASP.NET Core 10 runtime is required' >&2; exit 1;
}
RELEASE_METADATA_URL="$CENTRAL_URL/api/updates/latest"
for attempt in 1 2 3; do
CURL_PROTOCOL=https
[[ "$CENTRAL_URL" == https://* ]] || CURL_PROTOCOL=http
printf '%s' "$RELEASE_METADATA_URL" | python3 -c 'import json,sys; open(sys.argv[1],"w").write("url = "+json.dumps(sys.stdin.read())+"\n")' "$TMP_DIR/release-metadata.curl"
chmod 600 "$TMP_DIR/release-metadata.curl"
HTTP_STATUS=$(curl -sS --proto "$CURL_PROTOCOL" \
--connect-timeout 10 --max-time 30 \
-w '%{http_code}' --config "$TMP_DIR/release-metadata.curl" -o "$TMP_DIR/release.json") && CURL_STATUS=0 || CURL_STATUS=$?
if [[ "$CURL_STATUS" -eq 0 && "$HTTP_STATUS" =~ ^2[0-9][0-9]$ ]]; then
break
fi
if [[ "$CURL_STATUS" -ne 0 && "$HTTP_STATUS" == 000 ]] || [[ "$HTTP_STATUS" =~ ^(408|425|429|5[0-9][0-9])$ ]]; then
if [[ "$attempt" -lt 3 ]]; then
delay=$((attempt * 2))
echo "Release metadata request failed temporarily (attempt $attempt/3); retrying in ${delay}s." >&2
sleep "$delay"
continue
fi
fi
echo "Failed to fetch release metadata from Central (HTTP ${HTTP_STATUS:-000}; curl exit ${CURL_STATUS})." >&2
exit 1
done
if [[ -z "$UPDATE_PUBLIC_KEY" ]]; then
jq -er '.updatePublicKeyPem | select(type == "string" and length > 0 and length <= 4096)' "$TMP_DIR/release.json" > "$TMP_DIR/update-public-key.pem" || {
echo 'Central release metadata has no valid publisher public key' >&2; exit 1;
}
UPDATE_PUBLIC_KEY="$TMP_DIR/update-public-key.pem"
fi
openssl pkey -pubin -in "$UPDATE_PUBLIC_KEY" -noout >/dev/null || { echo 'Invalid publisher public key' >&2; exit 1; }
openssl pkey -pubin -in "$UPDATE_PUBLIC_KEY" -text -noout 2>/dev/null | grep -q 'ASN1 OID: prime256v1' || {
echo 'Publisher public key must use ECDSA P-256' >&2
exit 1
}
jq -r '.signedManifest // empty' "$TMP_DIR/release.json" | base64 -d > "$TMP_DIR/manifest.json" || { echo 'Invalid signed manifest encoding' >&2; exit 1; }
jq -r '.manifestSignature // empty' "$TMP_DIR/release.json" | base64 -d > "$TMP_DIR/manifest.sig" || { echo 'Invalid release signature encoding' >&2; exit 1; }
openssl dgst -sha256 -verify "$UPDATE_PUBLIC_KEY" -signature "$TMP_DIR/manifest.sig" "$TMP_DIR/manifest.json" >/dev/null || { echo 'Release signature verification failed' >&2; exit 1; }
VERSION=$(jq -r '.version' "$TMP_DIR/manifest.json")
[[ "$VERSION" == "$(jq -r '.version' "$TMP_DIR/release.json")" && "$VERSION" =~ ^v?[0-9]+\.[0-9]+\.[0-9]+([._-][0-9A-Za-z.-]+)?$ ]] || { echo 'Invalid signed release version' >&2; exit 1; }
ASSET_PLATFORM=$(jq -r --arg platform "$PLATFORM" 'if .assets[$platform] then $platform elif .assets.portable then "portable" else empty end' "$TMP_DIR/manifest.json")
[[ -n "$ASSET_PLATFORM" ]] || { echo "No signed archive for $PLATFORM" >&2; exit 1; }
EXPECTED_SHA256=$(jq -r --arg platform "$ASSET_PLATFORM" '.assets[$platform]' "$TMP_DIR/manifest.json")
DOWNLOAD_URL=$(jq -r --arg platform "$ASSET_PLATFORM" '.assets[$platform].url // empty' "$TMP_DIR/release.json")
RELEASE_SHA256=$(jq -r --arg platform "$ASSET_PLATFORM" '.assets[$platform].sha256 // empty' "$TMP_DIR/release.json")
[[ "$EXPECTED_SHA256" =~ ^[[:xdigit:]]{64}$ && "${EXPECTED_SHA256,,}" == "${RELEASE_SHA256,,}" && "$DOWNLOAD_URL" == https://* ]] || { echo 'Release archive differs from signed manifest' >&2; exit 1; }
curl -fsSL --proto '=https' --proto-redir '=https' "$DOWNLOAD_URL" -o "$TMP_DIR/agent.tar.gz" || { echo "Download failed" >&2; exit 1; }
ACTUAL=$(sha256sum "$TMP_DIR/agent.tar.gz" | cut -d' ' -f1); [[ "${ACTUAL,,}" == "${EXPECTED_SHA256,,}" ]] || { echo "SHA256 mismatch" >&2; exit 1; }
echo "Signed archive verified: $VERSION"
mkdir -p "$TMP_DIR/agent"
python3 - "$TMP_DIR/agent.tar.gz" "$TMP_DIR/agent" <<'PY'
import pathlib, shutil, sys, tarfile
root=pathlib.Path(sys.argv[2]).resolve()
with tarfile.open(sys.argv[1], 'r:gz') as archive:
members=archive.getmembers()
if len(members)>20000 or sum(m.size for m in members)>2_000_000_000:
raise SystemExit('Archive exceeds extraction limits')
for member in members:
if not (member.isfile() or member.isdir()):
raise SystemExit('Archive contains a link or unsupported entry')
target=(root/member.name).resolve()
if target!=root and root not in target.parents:
raise SystemExit('Archive path escapes extraction root')
if member.isdir():
target.mkdir(parents=True,exist_ok=True)
else:
target.parent.mkdir(parents=True,exist_ok=True)
with archive.extractfile(member) as source, open(target,'xb') as output:
shutil.copyfileobj(source,output)
PY
[[ -f "$TMP_DIR/agent/Heimdall.Agent.dll" ]] || { echo 'Archive has no agent assembly' >&2; exit 1; }
printf '%s' "$CENTRAL_URL" | python3 -c 'import json,pathlib,sys; p=pathlib.Path(sys.argv[1]); raw=p.read_text() if p.exists() else "{}";
try: d=json.loads(raw)
except json.JSONDecodeError: d={}
d.setdefault("Agent",{})["CentralUrl"]=sys.stdin.read(); p.write_text(json.dumps(d,indent=2)+"\n")' "$TMP_DIR/agent/appsettings.json"
chmod 640 "$TMP_DIR/agent/appsettings.json"
id "$SERVICE_USER" &>/dev/null || sudo useradd --system --no-create-home --shell /usr/sbin/nologin "$SERVICE_USER" 2>/dev/null || true
sudo mkdir -p "$STATE_DIR" && sudo chown "$SERVICE_USER:$SERVICE_USER" "$STATE_DIR" && sudo chmod 700 "$STATE_DIR"
sudo install -d -o "$SERVICE_USER" -g "$SERVICE_USER" -m 750 "$INSTALL_ROOT" "$INSTALL_ROOT/releases"
[[ ! -e "$INSTALL_ROOT/releases/$VERSION" ]] || { echo 'Release already installed' >&2; exit 1; }
sudo mv "$TMP_DIR/agent" "$INSTALL_ROOT/releases/$VERSION"
sudo chown -R "$SERVICE_USER:$SERVICE_USER" "$INSTALL_ROOT/releases/$VERSION"
sudo ln -sfn "$INSTALL_ROOT/releases/$VERSION" "$INSTALL_ROOT/current"
sudo install -d -o root -g root -m 755 /etc/heimdall
sudo install -o root -g root -m 644 "$UPDATE_PUBLIC_KEY" /etc/heimdall/update-public-key.pem
sudo install -d -o root -g root -m 755 /usr/local/libexec
SUPERVISOR_SOURCE="$(dirname "$0")/agent-supervisor.py"
if [[ ! -f "$SUPERVISOR_SOURCE" ]]; then
SUPERVISOR_SOURCE="$TMP_DIR/agent-supervisor.py"
printf '%s' "$CENTRAL_URL/install/agent-supervisor.py" | python3 -c 'import json,sys; open(sys.argv[1],"w").write("url = "+json.dumps(sys.stdin.read())+"\n")' "$TMP_DIR/supervisor.curl"
chmod 600 "$TMP_DIR/supervisor.curl"
curl -fsS --config "$TMP_DIR/supervisor.curl" -o "$SUPERVISOR_SOURCE" || {
echo 'Failed to download the Heimdall Agent supervisor from Central' >&2; exit 1;
}
fi
sudo install -o root -g root -m 755 "$SUPERVISOR_SOURCE" /usr/local/libexec/heimdall-agent-supervisor.py
sudo install -d -o root -g root -m 700 /etc/heimdall/credentials
printf '%s' "$SITE_TOKEN" | sudo tee /etc/heimdall/credentials/site-token >/dev/null
sudo chmod 600 /etc/heimdall/credentials/site-token
sudo install -d -o "$SERVICE_USER" -g "$SERVICE_USER" -m 700 "$STATE_DIR/credentials"
printf '%s' "$SITE_TOKEN" | sudo tee "$STATE_DIR/credentials/site-token" >/dev/null
sudo chown "$SERVICE_USER:$SERVICE_USER" "$STATE_DIR/credentials/site-token"
sudo chmod 600 "$STATE_DIR/credentials/site-token"
AGENT_NAME_CREDENTIAL=""
if [[ -n "$AGENT_NAME" ]]; then
printf '%s' "$AGENT_NAME" | sudo tee /etc/heimdall/credentials/agent-name >/dev/null
sudo chmod 600 /etc/heimdall/credentials/agent-name
printf '%s' "$AGENT_NAME" | sudo tee "$STATE_DIR/credentials/agent-name" >/dev/null
sudo chown "$SERVICE_USER:$SERVICE_USER" "$STATE_DIR/credentials/agent-name"
sudo chmod 600 "$STATE_DIR/credentials/agent-name"
AGENT_NAME_CREDENTIAL="LoadCredential=agent-name:/etc/heimdall/credentials/agent-name"
fi
if [[ "$RUN_MODE" == true ]]; then
echo "Starting Heimdall Agent $VERSION in foreground; press Ctrl+C to stop."
sudo -u "$SERVICE_USER" env \
CREDENTIALS_DIRECTORY="$STATE_DIR/credentials" \
ASPNETCORE_URLS=http://127.0.0.1:8081 \
HEIMDALL_DOTNET="$DOTNET_BIN" \
ASPNETCORE_ENVIRONMENT=Production \
Agent__AgentName="$AGENT_NAME" \
Agent__AllowInsecureHttp="$ALLOW_INSECURE_HTTP" \
Agent__StateDirectory="$STATE_DIR" \
Agent__UpdateInstallRoot="$INSTALL_ROOT" \
Agent__UpdatePublicKeyPath=/etc/heimdall/update-public-key.pem \
/usr/bin/python3 /usr/local/libexec/heimdall-agent-supervisor.py
exit $?
fi
cat <<EOF | sudo tee /etc/systemd/system/$SERVICE_NAME.service >/dev/null
[Unit]
Description=Heimdall Agent
After=network-online.target
[Service]
Type=simple
User=$SERVICE_USER
ExecStart=/usr/bin/python3 /usr/local/libexec/heimdall-agent-supervisor.py
WorkingDirectory=$INSTALL_ROOT/current
Restart=always
RestartSec=5
Environment=ASPNETCORE_URLS=http://127.0.0.1:8081
Environment=HEIMDALL_DOTNET=$DOTNET_BIN
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=Agent__AllowInsecureHttp=$ALLOW_INSECURE_HTTP
Environment=Agent__StateDirectory=$STATE_DIR
Environment=Agent__UpdateInstallRoot=$INSTALL_ROOT
Environment=Agent__UpdatePublicKeyPath=/etc/heimdall/update-public-key.pem
LoadCredential=site-token:/etc/heimdall/credentials/site-token
$AGENT_NAME_CREDENTIAL
[Install]
WantedBy=multi-user.target
EOF
sudo chmod 600 "/etc/systemd/system/$SERVICE_NAME.service"
sudo systemctl daemon-reload && sudo systemctl enable "$SERVICE_NAME"
if [[ "$INSTALL_ONLY" == true ]]; then
echo "Installed version $VERSION and enabled $SERVICE_NAME. Start it with: sudo systemctl start $SERVICE_NAME"
else
sudo systemctl start "$SERVICE_NAME"
echo "Done! Version: $VERSION, Service: $SERVICE_NAME"
fi