Harden installer temp staging, inline Python isolation, and asset checks

Download the Go toolchain during install.sh --source to an explicit path inside an owner-only temp directory via create_temp_archive_path and wget -O instead of unpacking a fixed name in shared /tmp.

Run all inline python3 invocations in install.sh, scripts/install.sh, and scripts/uninstall-sensor-proxy.sh in isolated mode (-I) so root never imports attacker-planted modules from a shared working directory or PYTHONPATH.

Declare PULSE_RELEASE_ASSET in install.sh and scripts/pulse-auto-update.sh and validate both in scripts/validate-release.sh. Strictly enforce the install.sh asset declaration in scripts/pulse-auto-update.sh and reject mismatched asset declarations in install.sh while allowing pre-rollout unstamped releases until a stamped stable release publishes as releases/latest.

Contract-Neutral: Security hardening of installer verification and privilege boundaries without public contract delta
This commit is contained in:
rcourtman
2026-11-24 10:15:00 +00:00
parent 9f64c65729
commit 3c812b827f
16 changed files with 465 additions and 88 deletions

View File

@@ -93,6 +93,11 @@ DOCKER_IMAGE_REPO="${DOCKER_IMAGE_REPO:-rcourtman/pulse}"
INSTALL_SIGNATURE_IDENTITY="pulse-installer"
INSTALL_SIGNATURE_NAMESPACE="pulse-install"
PINNED_RELEASE_SSH_PUBLIC_KEY="ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMZd/DaH+BldzOkq1A8KVTcFk73nAyrE8aJOyf7i00jm pulse-installer"
# Release asset identity. Every asset of every release is signed with the same
# key, identity and namespace, so a signature alone does not say which asset
# the signed bytes are. verify_release_signature checks this exact line inside
# the signed bytes before a downloaded copy of this script is run.
PULSE_RELEASE_ASSET="install.sh"
BUILD_FROM_SOURCE=false
SKIP_DOWNLOAD=false
IN_CONTAINER=false
@@ -134,6 +139,7 @@ verify_release_signature() {
local target_path="$1"
local signature_path="$2"
local context="${3:-downloaded file}"
local expected_asset="${4:-}"
local allowed_signers=""
if ! require_release_signature_verifier; then
@@ -154,6 +160,20 @@ verify_release_signature() {
fi
rm -f "$allowed_signers"
# The signature proves that Pulse published these bytes once, not which
# asset they are. When an asset declaration is present inside the signed
# bytes, require it to match the expected asset exactly so another signed
# script cannot be substituted. Missing declarations remain accepted here
# until a stamped stable release is published as releases/latest.
if [[ -n "$expected_asset" ]]; then
local declared_assets=""
declared_assets=$(grep -E '^PULSE_RELEASE_ASSET=' "$target_path" 2>/dev/null || true)
if [[ -n "$declared_assets" && "$declared_assets" != "PULSE_RELEASE_ASSET=\"${expected_asset}\"" ]]; then
echo "Signed ${context} does not declare itself as the ${expected_asset} release asset. Refusing it." >&2
return 1
fi
fi
return 0
}
@@ -2440,8 +2460,11 @@ auto_register_pve_node() {
host_input="$(hostname -f 2>/dev/null || hostname)"
fi
# The installer keeps the administrator's working directory, which may be a
# shared one such as /tmp. Every inline Python program runs isolated (-I) so
# its imports never resolve from there, PYTHONPATH or the user site directory.
local normalized_host_url
normalized_host_url=$(python3 - <<'PY' "$host_input" "$default_port"
normalized_host_url=$(python3 -I - <<'PY' "$host_input" "$default_port"
import sys, urllib.parse
raw = sys.argv[1].strip()
default_port = sys.argv[2]
@@ -2483,7 +2506,7 @@ PY
fi
local setup_payload
setup_payload=$(python3 - <<'PY' "$normalized_host_url" "$backup_perms"
setup_payload=$(python3 -I - <<'PY' "$normalized_host_url" "$backup_perms"
import json, sys
host = sys.argv[1]
backup = sys.argv[2].lower() == "true"
@@ -2518,7 +2541,7 @@ PY
local setup_token_hint
local setup_expires
local setup_expiry_state
IFS=$'\t' read -r setup_token setup_type setup_host setup_url setup_download_url setup_script_name setup_command setup_command_with_env setup_command_without_env setup_token_hint setup_expires setup_expiry_state <<<"$(python3 - "$pulse_url" "$normalized_host_url" "$backup_perms" 3<<<"$setup_response" <<'PY'
IFS=$'\t' read -r setup_token setup_type setup_host setup_url setup_download_url setup_script_name setup_command setup_command_with_env setup_command_without_env setup_token_hint setup_expires setup_expiry_state <<<"$(python3 -I - "$pulse_url" "$normalized_host_url" "$backup_perms" 3<<<"$setup_response" <<'PY'
import json, sys
import time
from urllib.parse import quote
@@ -2617,18 +2640,18 @@ PY
local backup_query=""
[[ "$backup_perms" == "true" ]] && backup_query="backup_perms=true&"
local expected_setup_url="${pulse_url}/api/setup-script?${backup_query}host=$(python3 - <<'PY' "$normalized_host_url"
local expected_setup_url="${pulse_url}/api/setup-script?${backup_query}host=$(python3 -I - <<'PY' "$normalized_host_url"
from urllib.parse import quote
import sys
print(quote(sys.argv[1], safe=''))
PY
)&pulse_url=$(python3 - <<'PY' "$pulse_url"
)&pulse_url=$(python3 -I - <<'PY' "$pulse_url"
from urllib.parse import quote
import sys
print(quote(sys.argv[1], safe=''))
PY
)&type=pve"
local expected_download_url="$(python3 - <<'PY' "$normalized_host_url" "$pulse_url" "$backup_perms" 3<<<"$setup_token"
local expected_download_url="$(python3 -I - <<'PY' "$normalized_host_url" "$pulse_url" "$backup_perms" 3<<<"$setup_token"
from urllib.parse import quote
import sys
host, pulse_url, backup_perms = sys.argv[1:]
@@ -2693,7 +2716,7 @@ PY
fi
local token_name
token_name=$(python3 - <<'PY' "$pulse_url"
token_name=$(python3 -I - <<'PY' "$pulse_url"
import re, sys, urllib.parse
raw = sys.argv[1].strip()
@@ -2752,7 +2775,7 @@ PY
fi
local register_payload
register_payload=$(python3 - "$normalized_host_url" "$token_id" "$server_name" 3<<<"$(printf '%s\n%s\n' "$token_value" "$setup_token")" <<'PY'
register_payload=$(python3 -I - "$normalized_host_url" "$token_id" "$server_name" 3<<<"$(printf '%s\n%s\n' "$token_value" "$setup_token")" <<'PY'
import json, sys
host, token_id, server_name = sys.argv[1:]
token_value, setup_token = __import__("os").fdopen(3).read().splitlines()
@@ -2788,7 +2811,7 @@ PY
local register_token_value
local register_node_id
local register_node_name
IFS=$'\t' read -r register_status register_action register_type register_source register_host register_token_id register_token_value register_node_id register_node_name <<<"$(python3 - "$register_response" <<'PY'
IFS=$'\t' read -r register_status register_action register_type register_source register_host register_token_id register_token_value register_node_id register_node_name <<<"$(python3 -I - "$register_response" <<'PY'
import json, sys
try:
data = json.loads(sys.argv[1])
@@ -2940,7 +2963,8 @@ inspect_api_tokens_for_upgrade() {
return 1
fi
python3 - "$token_file" <<'PY'
# Isolated (-I): no imports from the working directory or PYTHONPATH.
python3 -I - "$token_file" <<'PY'
import datetime
import json
import sys
@@ -3653,7 +3677,7 @@ download_container_installer() {
print_error "Failed to download container installer signature; refusing to copy or run the installer"
return 1
fi
if ! verify_release_signature "$staged_installer" "$staged_signature" "downloaded container installer"; then
if ! verify_release_signature "$staged_installer" "$staged_signature" "downloaded container installer" "install.sh"; then
return 1
fi
printf -v "$source_output" '%s' "$staged_installer"
@@ -4293,6 +4317,7 @@ build_from_source() {
local GO_INSTALLED=false
local arch=""
local go_arch=""
local go_archive=""
local service_name=""
local binary_stage=""
local version_output=""
@@ -4335,27 +4360,28 @@ build_from_source() {
;;
esac
if ! cd /tmp; then
# /tmp is writable by every local account. wget without -O keeps a file
# that already has the download's name and saves beside it, so a fixed
# name there lets another user choose what root unpacks. Download to an
# explicit path inside an owner-only directory instead.
if ! go_archive=$(create_temp_archive_path "/tmp/go${GO_MIN_VERSION}.linux-${go_arch}"); then
print_error "Failed to prepare Go installation directory"
cd "$original_dir" >/dev/null 2>&1 || true
return 1
fi
if ! wget -q "https://go.dev/dl/go${GO_MIN_VERSION}.linux-${go_arch}.tar.gz"; then
if ! wget -q -O "$go_archive" "https://go.dev/dl/go${GO_MIN_VERSION}.linux-${go_arch}.tar.gz"; then
print_error "Failed to download Go toolchain"
cd "$original_dir" >/dev/null 2>&1 || true
cleanup_temp_archive_path "$go_archive"
return 1
fi
rm -rf /usr/local/go
if ! tar -C /usr/local -xzf "go${GO_MIN_VERSION}.linux-${go_arch}.tar.gz"; then
if ! tar -C /usr/local -xzf "$go_archive"; then
print_error "Failed to extract Go toolchain"
rm -f "go${GO_MIN_VERSION}.linux-${go_arch}.tar.gz"
cd "$original_dir" >/dev/null 2>&1 || true
cleanup_temp_archive_path "$go_archive"
return 1
fi
rm -f "go${GO_MIN_VERSION}.linux-${go_arch}.tar.gz"
cd "$original_dir" >/dev/null 2>&1 || true
cleanup_temp_archive_path "$go_archive"
fi
export PATH=/usr/local/go/bin:$PATH
@@ -4708,7 +4734,7 @@ if ! curl -q -fsSL --connect-timeout 10 --max-time 60 --proto '=https' --proto-r
echo "Failed to download Pulse installer signature from \$INSTALLER_SIG_URL" >&2
exit 1
fi
if ! verify_release_signature "\$tmp_installer" "\$tmp_signature" "downloaded Pulse installer"; then
if ! verify_release_signature "\$tmp_installer" "\$tmp_signature" "downloaded Pulse installer" "install.sh"; then
exit 1
fi
# The installer owns its outcome and exit status. Help, cancellation and
@@ -4796,7 +4822,7 @@ download_auto_update_script() {
if [[ $curl_status -ne 0 ]]; then
print_warn "Failed to download signature for pulse-auto-update.sh"
rm -f "$signature_file" "$dest"
elif ! verify_release_signature "$dest" "$signature_file" "downloaded pulse-auto-update.sh"; then
elif ! verify_release_signature "$dest" "$signature_file" "downloaded pulse-auto-update.sh" "pulse-auto-update.sh"; then
rm -f "$signature_file" "$dest"
curl_status=1
else

View File

@@ -1795,7 +1795,8 @@ read_truenas_agent_removal_tasks() {
printf '\n%s' '__pulse_truenas_tasks_complete__') || return 1
# Parse the complete inventory, including indirect/other-install bootstrap
# references. No task command, name, argument or credential is returned.
python3 -c '
# Isolated (-I): no imports from the working directory or PYTHONPATH.
python3 -I -c '
import json, pathlib, sys
def unique_object(pairs):
result = {}
@@ -7152,7 +7153,7 @@ if [[ "$UNINSTALL" == "true" ]]; then
log_info "Removing TrueNAS CORE installation..."
# Remove Init/Shutdown task
if command -v midclt >/dev/null 2>&1 && command -v python3 >/dev/null 2>&1; then
TASK_ID=$(midclt call initshutdownscript.query '[["script","=","'"$TRUENAS_BOOTSTRAP_SCRIPT"'"]]' 2>/dev/null | python3 -c "import json,sys; d=json.load(sys.stdin); print(d[0]['id'] if d else '')" 2>/dev/null || echo "")
TASK_ID=$(midclt call initshutdownscript.query '[["script","=","'"$TRUENAS_BOOTSTRAP_SCRIPT"'"]]' 2>/dev/null | python3 -I -c "import json,sys; d=json.load(sys.stdin); print(d[0]['id'] if d else '')" 2>/dev/null || echo "")
if [[ -n "$TASK_ID" ]]; then
midclt call initshutdownscript.delete "$TASK_ID" >/dev/null 2>&1 || log_warn "Failed to remove Init/Shutdown task (id $TASK_ID)"
fi
@@ -8568,7 +8569,7 @@ EOF
log_info "Registering TrueNAS Init/Shutdown task..."
# Check if task already exists
EXISTING_TASK=$(midclt call initshutdownscript.query '[["script","=","'"$TRUENAS_BOOTSTRAP_SCRIPT"'"]]' 2>/dev/null | python3 -c "import json,sys; d=json.load(sys.stdin); print(d[0]['id'] if d else '')" 2>/dev/null || echo "")
EXISTING_TASK=$(midclt call initshutdownscript.query '[["script","=","'"$TRUENAS_BOOTSTRAP_SCRIPT"'"]]' 2>/dev/null | python3 -I -c "import json,sys; d=json.load(sys.stdin); print(d[0]['id'] if d else '')" 2>/dev/null || echo "")
if [[ -n "$EXISTING_TASK" ]]; then
log_info "Init/Shutdown task already exists (id $EXISTING_TASK), updating..."

View File

@@ -97,6 +97,7 @@ else:
INSTALLER = r'''#!/bin/bash
set -euo pipefail
PULSE_RELEASE_ASSET="install.sh"
[[ $# == 2 && "$1" == --version ]]
case "$2" in v0.0.1|v0.0.2) ;; *) exit 97 ;; esac
source "$PULSE_NATIVE_ROOT/installer-definitions"

View File

@@ -1617,6 +1617,12 @@ func TestReleaseValidationRequiresSignedSidecars(t *testing.T) {
`Pulse Unified Agent Installer`,
`bash "$install_sh_path" --help`,
`Install specific version (e.g.`,
// Update helpers refuse a signed script that declares the wrong asset
// identity, and auto-updaters require the declaration.
`Validating release scripts declare their asset identity`,
`for script_asset in install.sh pulse-auto-update.sh; do`,
`declared_assets="$(grep -E '^PULSE_RELEASE_ASSET=' "$script_asset" || true)"`,
`if [ "$declared_assets" != "PULSE_RELEASE_ASSET=\"${script_asset}\"" ]; then`,
// README key drift guard — across v6 rc.2 → rc.5 the README pinned a
// stale ed25519 key that did not verify install.sh.sshsig, so anyone
// following the secure-install path saw "Could not verify signature".

View File

@@ -4359,6 +4359,76 @@ func TestAPIDeregistrationCurlWithoutToken(t *testing.T) {
}
}
// plantCallerPythonModules fills dir with modules named like the standard
// library ones the installers' inline Python imports. Each leaves a
// "<module>.py.imported" file beside itself when Python loads it.
func plantCallerPythonModules(t *testing.T, dir string) {
t.Helper()
if err := os.MkdirAll(dir, 0700); err != nil {
t.Fatal(err)
}
for _, module := range []string{"datetime", "ipaddress", "json", "pathlib", "re", "time", "urllib"} {
writeTestFile(t, filepath.Join(dir, module+".py"), []byte("open(__file__ + '.imported', 'w').close()\n"), 0600)
}
}
func assertCallerPythonModulesUnused(t *testing.T, dir string) {
t.Helper()
imported, err := filepath.Glob(filepath.Join(dir, "*.imported"))
if err != nil || len(imported) != 0 {
t.Errorf("inline Python loaded modules from the caller's directory or PYTHONPATH: %v, %v", imported, err)
}
}
// Administrators start these scripts as root from whatever directory their
// shell is in, often a shared one such as /tmp. "python3 -" and "python3 -c"
// search that directory before the standard library unless -I is given.
func TestInstallerInlinePythonStartsIsolated(t *testing.T) {
invocation := regexp.MustCompile(`\bpython3[ \t]+-\S*`)
for _, script := range []string{
repoFile("install.sh"),
repoFile("scripts", "install.sh"),
repoFile("scripts", "uninstall-sensor-proxy.sh"),
} {
content, err := os.ReadFile(script)
if err != nil {
t.Fatal(err)
}
for line, text := range strings.Split(string(content), "\n") {
for _, found := range invocation.FindAllString(text, -1) {
if strings.Fields(found)[1] != "-I" {
t.Errorf("%s:%d: %q does not start Python isolated (-I)", script, line+1, found)
}
}
}
}
}
func TestInstallSHTrueNASTaskInventoryIgnoresCallerPythonModules(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Unix installer")
}
caller := t.TempDir()
plantCallerPythonModules(t, caller)
script := `set -euo pipefail
timeout() { shift 3; "$@"; }
midclt() {
printf '%s\n' '[{"id":7,"type":"SCRIPT","script":"/fixture/bootstrap-pulse-agent.sh","command":"","when":"POSTINIT","enabled":true,"timeout":30,"comment":"Pulse Agent Bootstrap"}]'
}
TRUENAS_BOOTSTRAP_SCRIPT=/fixture/bootstrap-pulse-agent.sh
` + extractInstallShellFunction(t, "read_truenas_agent_removal_tasks") + `
read_truenas_agent_removal_tasks
`
cmd := exec.Command("bash", "-c", script)
cmd.Dir = caller
cmd.Env = append(os.Environ(), "PYTHONPATH="+caller)
out, err := cmd.CombinedOutput()
if err != nil || string(out) != "7 true\ncomplete\n" {
t.Fatalf("owned boot-task inventory changed: %v\n%s", err, out)
}
assertCallerPythonModulesUnused(t, caller)
}
// Fixture cases use the same checked-in installer for the life of this test
// process. Share its immutable function text, not generated scripts or fixture
// state: each case still builds its own harness and runs all its assertions.
@@ -6908,6 +6978,7 @@ case "$url" in
cat > "$out" <<'INSTALLER'
#!/usr/bin/env bash
set -eu
PULSE_RELEASE_ASSET="install.sh"
[[ "$*" == "--version v9.9.9" ]]
[[ "$PULSE_SERVICE_NAME" == pulse-url-fixture ]]
[[ "$PULSE_INSTALL_DIR" == "$FIXTURE_DIR/install" ]]

View File

@@ -49,12 +49,12 @@ func TestManualUpdateChannelAdmission(t *testing.T) {
}
selectionFunctions += string(body) + "\n"
}
installer := filepath.Join(assets, "install.sh")
// The real installer reads configuration again unless the helper forwards
// an explicit channel. Use its actual selection functions to catch that
// crossing rather than accepting helper arguments alone as the outcome.
fixture := `#!/bin/bash
set -eu
PULSE_RELEASE_ASSET="install.sh"
CONFIG_DIR="$PULSE_CONFIG_DIR"
FORCE_CHANNEL=""
FORCE_VERSION=""
@@ -74,11 +74,26 @@ if [[ -n "$MANUAL_UPDATE_OUTPUT" ]]; then
fi
exit "$MANUAL_UPDATE_EXIT"
`
if err := os.WriteFile(installer, []byte(fixture), 0600); err != nil {
t.Fatal(err)
// Every release asset carries a signature from the same key and namespace.
// Signed assets declaring another release asset must be refused, while
// unstamped pre-rollout installers remain accepted until a stamped stable
// release is published as releases/latest.
const identity = `PULSE_RELEASE_ASSET="install.sh"` + "\n"
signedAssets := map[string]string{
"install.sh": fixture,
"earlier-install.sh": strings.Replace(fixture, identity, "", 1),
"pulse-auto-update.sh": strings.Replace(fixture, identity, `PULSE_RELEASE_ASSET="pulse-auto-update.sh"`+"\n", 1),
}
if out, err := exec.Command("ssh-keygen", "-q", "-Y", "sign", "-f", key, "-n", "pulse-install", installer).CombinedOutput(); err != nil {
t.Fatalf("sign fixture installer: %v\n%s", err, out)
for name, body := range signedAssets {
if name != "install.sh" && body == fixture {
t.Fatalf("fixture %s still declares the installer identity", name)
}
if err := os.WriteFile(filepath.Join(assets, name), []byte(body), 0600); err != nil {
t.Fatal(err)
}
if out, err := exec.Command("ssh-keygen", "-q", "-Y", "sign", "-f", key, "-n", "pulse-install", filepath.Join(assets, name)).CombinedOutput(); err != nil {
t.Fatalf("sign fixture %s: %v\n%s", name, err, out)
}
}
cases := []struct {
@@ -90,6 +105,7 @@ exit "$MANUAL_UPDATE_EXIT"
directory bool
brokenLink bool
badSignature bool
servedAsset string
installerOutput string
installerExit int
}{
@@ -129,6 +145,8 @@ exit "$MANUAL_UPDATE_EXIT"
{name: "source_marker_over_invalid", config: `{`, marker: "maintenance\n", want: []string{"--source", "maintenance"}},
{name: "explicit_channel_over_source_marker", config: `{`, marker: "main\n", args: []string{"--stable"}, want: []string{"--stable"}},
{name: "signature_still_required", config: `{"updateChannel":"rc"}`, badSignature: true, blocked: true},
{name: "signed_unstamped_latest_still_allowed", config: `{"updateChannel":"rc"}`, servedAsset: "earlier-install.sh", want: []string{"--rc"}},
{name: "signed_other_asset_is_refused", config: `{"updateChannel":"stable"}`, servedAsset: "pulse-auto-update.sh", blocked: true},
{name: "help_is_not_an_update", config: `{`, args: []string{"--help"}, want: []string{"--help"}, installerOutput: "Usage: fixture installer [OPTIONS]"},
{name: "cancel_is_not_an_update", missingConfig: true, installerOutput: "Installation cancelled"},
{name: "removal_does_not_promise_restart", missingConfig: true, installerOutput: "Pulse removed successfully"},
@@ -193,8 +211,8 @@ done
[[ -n "$url" && -n "$dest" && "$https_only" == true && "$https_redirects_only" == true ]] || exit 97
printf '%s\n' "$url" >> "$MANUAL_UPDATE_TRANSPORT"
case "$url" in
*.sshsig) if [[ "$BAD_SIGNATURE" == true ]]; then printf invalid > "$dest"; else cp "$FIXTURE_ASSETS/install.sh.sig" "$dest"; fi ;;
*/install.sh) cp "$FIXTURE_ASSETS/install.sh" "$dest" ;;
*.sshsig) if [[ "$BAD_SIGNATURE" == true ]]; then printf invalid > "$dest"; else cp "$FIXTURE_ASSETS/$SERVED_ASSET.sig" "$dest"; fi ;;
*/install.sh) cp "$FIXTURE_ASSETS/$SERVED_ASSET" "$dest" ;;
*) exit 96 ;;
esac
`
@@ -208,9 +226,13 @@ esac
calls := filepath.Join(dir, "calls")
transport := filepath.Join(dir, "transport")
channel := filepath.Join(dir, "channel")
servedAsset := tc.servedAsset
if servedAsset == "" {
servedAsset = "install.sh"
}
cmd := exec.Command(bash, append([]string{helper}, tc.args...)...)
cmd.Env = append(os.Environ(), "PATH="+path, "FIXTURE_ASSETS="+assets, "MANUAL_UPDATE_CALLS="+calls, "MANUAL_UPDATE_TRANSPORT="+transport, "MANUAL_UPDATE_CHANNEL="+channel,
"BAD_SIGNATURE="+map[bool]string{true: "true", false: "false"}[tc.badSignature],
"BAD_SIGNATURE="+map[bool]string{true: "true", false: "false"}[tc.badSignature], "SERVED_ASSET="+servedAsset,
"MANUAL_UPDATE_OUTPUT="+tc.installerOutput, "MANUAL_UPDATE_EXIT="+strconv.Itoa(tc.installerExit))
out, runErr := cmd.CombinedOutput()
if tc.blocked {
@@ -220,7 +242,7 @@ esac
if _, err := os.Stat(calls); !os.IsNotExist(err) {
t.Fatalf("rejected helper executed installer: %v\n%s", err, out)
}
if tc.badSignature {
if tc.badSignature || tc.servedAsset != "" {
// A transport-fixture refusal must not masquerade as proof
// that the actual SSH verifier rejected a bad signature.
got, err := os.ReadFile(transport)
@@ -228,9 +250,14 @@ esac
if err != nil || string(got) != assetURL+"\n"+assetURL+".sshsig\n" {
t.Fatalf("signature control did not fetch both signed inputs: %v, %q\n%s", err, got, out)
}
if !strings.Contains(string(out), "Cryptographic signature verification failed") {
signatureRefused := strings.Contains(string(out), "Cryptographic signature verification failed")
identityRefused := strings.Contains(string(out), "does not declare itself as the install.sh release asset")
if tc.badSignature && !signatureRefused {
t.Fatalf("signature control did not reach the actual verifier: %s", out)
}
if tc.servedAsset != "" && (signatureRefused || !identityRefused) {
t.Fatalf("validly signed %s was not refused for its identity: %s", tc.servedAsset, out)
}
} else {
if _, err := os.Stat(transport); !os.IsNotExist(err) {
t.Fatalf("invalid preference reached download: %v\n%s", err, out)

View File

@@ -952,6 +952,7 @@ echo "AFTER_CALLER"
}
const autoUpdateTransactionInstaller = `set -euo pipefail
PULSE_RELEASE_ASSET="install.sh"
printf 'executed\n' > "$FIXTURE_DIR/installer-executed"
printf 'false\n' > "$FIXTURE_DIR/active"
[[ "$FAULT" != stop ]] || printf 'true\n' > "$FIXTURE_DIR/active"
@@ -998,38 +999,62 @@ exit 0
// and still runs the real installer and signature verifier through curl's
// fixture transport. The signing key never leaves this setup's private path.
type signedAutoUpdateTransactionFixture struct {
publicKey string
signature []byte
publicKey string
signature []byte
undeclaredInstaller string
undeclaredSignature []byte
wrongAssetInstaller string
wrongAssetSignature []byte
}
func signAutoUpdateTransactionFixture(t *testing.T, sshKeygen string) signedAutoUpdateTransactionFixture {
t.Helper()
dir := t.TempDir()
key := filepath.Join(dir, "fixture-key")
installer := filepath.Join(dir, "installer")
if err := os.WriteFile(installer, []byte(autoUpdateTransactionInstaller), 0600); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if out, err := exec.CommandContext(ctx, sshKeygen, "-q", "-t", "ed25519", "-N", "", "-f", key).CombinedOutput(); err != nil {
t.Fatalf("generate transaction fixture signer: %v\n%s", err, out)
}
if out, err := exec.CommandContext(ctx, sshKeygen, "-Y", "sign", "-f", key, "-n", "pulse-install", installer).CombinedOutput(); err != nil {
t.Fatalf("sign transaction fixture: %v\n%s", err, out)
sign := func(name, content string) []byte {
t.Helper()
p := filepath.Join(dir, name)
if err := os.WriteFile(p, []byte(content), 0600); err != nil {
t.Fatal(err)
}
if out, err := exec.CommandContext(ctx, sshKeygen, "-Y", "sign", "-f", key, "-n", "pulse-install", p).CombinedOutput(); err != nil {
t.Fatalf("sign transaction fixture %s: %v\n%s", name, err, out)
}
sig, err := os.ReadFile(p + ".sig")
if err != nil {
t.Fatal(err)
}
if len(sig) == 0 {
t.Fatalf("empty transaction fixture signature for %s", name)
}
return sig
}
const assetLine = `PULSE_RELEASE_ASSET="install.sh"` + "\n"
undeclared := strings.Replace(autoUpdateTransactionInstaller, assetLine, "", 1)
wrongAsset := strings.Replace(autoUpdateTransactionInstaller, assetLine, `PULSE_RELEASE_ASSET="pulse-auto-update.sh"`+"\n", 1)
if undeclared == autoUpdateTransactionInstaller || wrongAsset == autoUpdateTransactionInstaller {
t.Fatal("transaction fixture missing PULSE_RELEASE_ASSET declaration")
}
publicKey, err := os.ReadFile(key + ".pub")
if err != nil {
t.Fatal(err)
}
signature, err := os.ReadFile(installer + ".sig")
if err != nil {
t.Fatal(err)
if len(strings.TrimSpace(string(publicKey))) == 0 {
t.Fatal("empty transaction fixture public key")
}
if len(signature) == 0 || len(strings.TrimSpace(string(publicKey))) == 0 {
t.Fatal("empty transaction fixture signature or public key")
return signedAutoUpdateTransactionFixture{
publicKey: strings.TrimRight(string(publicKey), "\n"),
signature: sign("installer", autoUpdateTransactionInstaller),
undeclaredInstaller: undeclared,
undeclaredSignature: sign("installer-undeclared", undeclared),
wrongAssetInstaller: wrongAsset,
wrongAssetSignature: sign("installer-wrong-asset", wrongAsset),
}
return signedAutoUpdateTransactionFixture{publicKey: strings.TrimRight(string(publicKey), "\n"), signature: signature}
}
// Exercise the complete sourced updater in its real conditional-call context.
@@ -1064,6 +1089,8 @@ func TestAutoUpdateBackupTransaction(t *testing.T) {
{name: "installer_download_failure", fault: "download_installer", preflight: true},
{name: "signature_download_failure", fault: "download_signature", preflight: true},
{name: "invalid_signature", fault: "invalid_signature", preflight: true},
{name: "signed_installer_without_identity", fault: "undeclared_installer", preflight: true},
{name: "signed_wrong_asset_installer", fault: "wrong_asset_installer", preflight: true},
{name: "installer_failure", outcome: "failure"},
{name: "wrong_version", outcome: "mismatch"},
{name: "failed_version_probe", outcome: "probe_failure"},
@@ -1124,14 +1151,22 @@ func runAutoUpdateTransactionScenario(t *testing.T, fixture signedAutoUpdateTran
}
dir := t.TempDir()
download := autoUpdateTransactionInstaller
if fault == "invalid_signature" {
sig := fixture.signature
switch fault {
case "invalid_signature":
// Keep the original signature so rejection proves real verification.
download += "tampered\n"
case "undeclared_installer":
download = fixture.undeclaredInstaller
sig = fixture.undeclaredSignature
case "wrong_asset_installer":
download = fixture.wrongAssetInstaller
sig = fixture.wrongAssetSignature
}
if err := os.WriteFile(filepath.Join(dir, "installer"), []byte(download), 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "installer.sig"), fixture.signature, 0600); err != nil {
if err := os.WriteFile(filepath.Join(dir, "installer.sig"), sig, 0600); err != nil {
t.Fatal(err)
}
script := `

View File

@@ -28,29 +28,39 @@ import (
func TestRootInstallerDownloadCurlConfigIsolation(t *testing.T) {
assets := t.TempDir()
key := filepath.Join(assets, "key")
payload := []byte("inert transport fixture; never executed\n")
file := filepath.Join(assets, "payload")
writeTestFile(t, file, payload, 0600)
for _, args := range [][]string{
{"-q", "-t", "ed25519", "-N", "", "-f", key},
{"-q", "-Y", "sign", "-f", key, "-n", "pulse-install", file},
} {
if out, err := exec.Command("ssh-keygen", args...).CombinedOutput(); err != nil {
t.Fatalf("synthetic signature: %v\n%s", err, out)
}
if out, err := exec.Command("ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", key).CombinedOutput(); err != nil {
t.Fatalf("synthetic signing key: %v\n%s", err, out)
}
public, err := os.ReadFile(key + ".pub")
if err != nil {
t.Fatal(err)
}
signature, err := os.ReadFile(file + ".sig")
if err != nil {
t.Fatal(err)
// One key and namespace sign both assets, as in a release. Each names
// itself inside its signed bytes so another signed asset cannot replace it.
payloads := map[string][]byte{
"installer": []byte("PULSE_RELEASE_ASSET=\"install.sh\"\ninert transport fixture, never executed\n"),
"helper": []byte("PULSE_RELEASE_ASSET=\"pulse-auto-update.sh\"\ninert transport fixture, never executed\n"),
}
signatures := map[string][]byte{}
for name, body := range payloads {
file := filepath.Join(assets, name)
writeTestFile(t, file, body, 0600)
if out, err := exec.Command("ssh-keygen", "-q", "-Y", "sign", "-f", key, "-n", "pulse-install", file).CombinedOutput(); err != nil {
t.Fatalf("synthetic signature: %v\n%s", err, out)
}
if signatures[name], err = os.ReadFile(file + ".sig"); err != nil {
t.Fatal(err)
}
}
for _, phase := range []string{"installer", "helper"} {
for _, noTimeout := range []bool{false, true} {
for _, mode := range []string{"trusted", "untrusted-ca", "http-error", "redirect", "bad-signature", "environment-proxy"} {
for _, mode := range []string{"trusted", "untrusted-ca", "http-error", "redirect", "bad-signature", "other-signed-asset", "environment-proxy"} {
t.Run(fmt.Sprintf("%s/no-timeout-%t/%s", phase, noTimeout, mode), func(t *testing.T) {
served := phase
if mode == "other-signed-asset" {
served = map[string]string{"installer": "helper", "helper": "installer"}[phase]
}
payload, signature := payloads[served], signatures[served]
root := t.TempDir()
var mu sync.Mutex
var requests []string
@@ -150,7 +160,7 @@ fi
env = append(env, proxyEnv...)
exit := runRootCurlFixture(t, script, env)
accepted, readErr := os.ReadFile(filepath.Join(root, "accepted"))
ok := mode != "untrusted-ca" && mode != "http-error" && mode != "bad-signature"
ok := mode != "untrusted-ca" && mode != "http-error" && mode != "bad-signature" && mode != "other-signed-asset"
if ok {
if exit != 0 || readErr != nil || !bytes.Equal(accepted, payload) {
t.Fatalf("signed transport rejected: exit=%d read=%v payload=%q", exit, readErr, accepted)
@@ -169,7 +179,7 @@ fi
want = 3 // Existing script-owned attempts, not curlrc retries.
} else if mode == "redirect" {
want = 4
} else if mode == "bad-signature" && phase == "helper" {
} else if (mode == "bad-signature" || mode == "other-signed-asset") && phase == "helper" {
want = 6 // Three existing signed-pair attempts, never acceptance.
}
if len(got) != want || hasInjected || strings.Contains(strings.Join(got, "\n"), "/ambient") {

View File

@@ -357,6 +357,122 @@ func TestRootInstallScriptStagesUpdateBeforeStoppingService(t *testing.T) {
}
}
// A source build that has to fetch the Go toolchain runs as root and used to
// unpack a fixed name in shared /tmp. The fixture relocates /tmp and replaces
// only the network, the toolchain unpack and the clone. The download must be
// the archive that is unpacked even when that name was planted beforehand.
func TestRootInstallScriptSourceBuildIgnoresPlantedGoArchive(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Unix installer fixture")
}
sourceInstall := extractRootInstallShellFunction(t, "build_from_source")
version := regexp.MustCompile(`GO_MIN_VERSION="([^"]+)"`).FindStringSubmatch(sourceInstall)
if version == nil {
t.Fatal("build_from_source no longer pins GO_MIN_VERSION")
}
fixture := t.TempDir()
sharedTmp := filepath.Join(fixture, "tmp")
if err := os.Mkdir(sharedTmp, 0777); err != nil {
t.Fatal(err)
}
planted := filepath.Join(sharedTmp, "go"+version[1]+".linux-amd64.tar.gz")
if err := os.WriteFile(planted, []byte("planted\n"), 0644); err != nil {
t.Fatal(err)
}
script := `
set -uo pipefail
GITHUB_REPO=fixture/Pulse
print_info() { :; }
print_error() { printf '%s\n' "$*" >&2; }
` + extractRootInstallShellFunction(t, "create_temp_archive_path") + `
` + extractRootInstallShellFunction(t, "cleanup_temp_archive_path") + `
` + sourceInstall + `
apt-get() { return 0; }
uname() { printf 'x86_64\n'; }
# No toolchain on PATH selects the download branch.
command() {
if [[ "$1" == -v && "$2" == go ]]; then return 1; fi
builtin command "$@"
}
cd() {
if [[ "$1" == /tmp ]]; then set -- "$SHARED_TMP"; fi
builtin cd "$@"
}
mktemp() { command mktemp "${@/#\/tmp\//$SHARED_TMP/}"; }
# Like wget, save under the URL's name unless -O names the output, and
# never replace a file that already has that name.
wget() {
local output="" url=""
while (($#)); do
case "$1" in
-O) output="$2"; shift ;;
-*) ;;
*) url="$1" ;;
esac
shift
done
if [[ -z "$output" ]]; then
output="${url##*/}"
[[ ! -e "$output" ]] || output="$output.1"
fi
printf 'downloaded %s\n' "$url" > "$output"
}
tar() {
local archive=""
while (($#)); do
case "$1" in
-xzf) archive="$2"; shift ;;
esac
shift
done
command cat "$archive" > "$FIXTURE/unpacked"
command ls -ld "$(dirname "$archive")" | command cut -c1-10 > "$FIXTURE/stage-mode"
}
rm() {
if [[ "$*" == *'/usr/local/go'* ]]; then return 0; fi
command rm "$@"
}
git() { return 1; }
if build_from_source main; then
echo "fixture clone unexpectedly succeeded" >&2
exit 1
fi
`
cmd := exec.Command("bash", "-c", script)
cmd.Env = append(os.Environ(), "FIXTURE="+fixture, "SHARED_TMP="+sharedTmp)
out, err := cmd.CombinedOutput()
if err != nil || !strings.Contains(string(out), "Failed to clone repository") {
t.Fatalf("source build fixture did not reach the clone: %v\n%s", err, out)
}
unpacked, err := os.ReadFile(filepath.Join(fixture, "unpacked"))
if err != nil {
t.Fatalf("toolchain archive was not unpacked: %v\n%s", err, out)
}
want := "downloaded https://go.dev/dl/go" + version[1] + ".linux-amd64.tar.gz\n"
if string(unpacked) != want {
t.Fatalf("unpacked archive = %q, want the download %q", unpacked, want)
}
if mode, err := os.ReadFile(filepath.Join(fixture, "stage-mode")); err != nil || strings.TrimSpace(string(mode)) != "drwx------" {
t.Fatalf("toolchain archive was staged in a directory with mode %q (%v), want owner-only", mode, err)
}
if content, err := os.ReadFile(planted); err != nil || string(content) != "planted\n" {
t.Fatalf("another user's file was changed or removed: %q, %v", content, err)
}
entries, err := os.ReadDir(sharedTmp)
if err != nil {
t.Fatal(err)
}
if len(entries) != 1 {
names := make([]string, 0, len(entries))
for _, entry := range entries {
names = append(names, entry.Name())
}
t.Fatalf("source build left staging behind in /tmp: %v", names)
}
}
func TestRootInstallScriptInstallsSignatureVerificationDependencies(t *testing.T) {
content, err := os.ReadFile(filepath.Join("..", "..", "install.sh"))
if err != nil {
@@ -786,8 +902,12 @@ func TestRootInstallScriptV5ToV6PreflightAcceptsLegacyHostAgentScope(t *testing.
run_upgrade_readiness_preflight v5.1.23 v6.0.0
`
// An upgrade started from a shared directory must not read its modules.
caller := t.TempDir()
plantCallerPythonModules(t, caller)
cmd := exec.Command("bash", "-c", script)
cmd.Env = append(os.Environ(), "CONFIG_DIR="+configDir)
cmd.Dir = caller
cmd.Env = append(os.Environ(), "CONFIG_DIR="+configDir, "PYTHONPATH="+caller)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("bash: %v\n%s", err, out)
@@ -795,6 +915,7 @@ func TestRootInstallScriptV5ToV6PreflightAcceptsLegacyHostAgentScope(t *testing.
if !strings.Contains(string(out), "Agent reporting token scope is present") {
t.Fatalf("expected success output, got:\n%s", out)
}
assertCallerPythonModulesUnused(t, caller)
}
func TestRootInstallScriptAutoRegisterUsesSecureContractShape(t *testing.T) {
@@ -1066,15 +1187,33 @@ func TestRootInstallScriptRequiresSignedReleaseDownloads(t *testing.T) {
`Failed to download signature for Pulse release`,
`verify_release_signature "$archive_path" "$signature_file" "downloaded Pulse release"`,
`INSTALLER_SIG_URL="\${INSTALLER_URL}.sshsig"`,
`verify_release_signature "\$tmp_installer" "\$tmp_signature" "downloaded Pulse installer"`,
`verify_release_signature "\$tmp_installer" "\$tmp_signature" "downloaded Pulse installer" "install.sh"`,
`Failed to download signature for pulse-auto-update.sh`,
`verify_release_signature "$dest" "$signature_file" "downloaded pulse-auto-update.sh"`,
`verify_release_signature "$dest" "$signature_file" "downloaded pulse-auto-update.sh" "pulse-auto-update.sh"`,
`verify_release_signature "$staged_installer" "$staged_signature" "downloaded container installer" "install.sh"`,
`declared_assets=$(grep -E '^PULSE_RELEASE_ASSET=' "$target_path" 2>/dev/null || true)`,
}
for _, needle := range required {
if !strings.Contains(script, needle) {
t.Fatalf("root install.sh missing signed-release verification contract: %s", needle)
}
}
requireSingleReleaseAssetDeclaration(t, script, "install.sh")
}
// A script is admitted as a release asset only through one whole line naming
// it. A second declaration would let it pass as another signed asset too.
func requireSingleReleaseAssetDeclaration(t *testing.T, script, asset string) {
t.Helper()
var declared []string
for _, line := range strings.Split(script, "\n") {
if strings.HasPrefix(line, "PULSE_RELEASE_ASSET=") {
declared = append(declared, line)
}
}
if want := `PULSE_RELEASE_ASSET="` + asset + `"`; len(declared) != 1 || declared[0] != want {
t.Fatalf("%s must declare its release asset identity exactly once as %s, got %q", asset, want, declared)
}
}
func TestPulseAutoUpdateScriptSupportsInstanceScopedServerInstalls(t *testing.T) {
@@ -1115,7 +1254,8 @@ func TestPulseAutoUpdateScriptRequiresSignedInstallerDownloads(t *testing.T) {
`verify_release_signature() {`,
`local install_signature_url="${install_script_url}.sshsig"`,
`Failed to download installer signature from $install_signature_url`,
`verify_release_signature "$installer_tmp" "$signature_tmp" "downloaded Pulse installer"`,
`verify_release_signature "$installer_tmp" "$signature_tmp" "downloaded Pulse installer" "install.sh"`,
`declared_assets=$(grep -E '^PULSE_RELEASE_ASSET=' "$target_path" 2>/dev/null || true)`,
`Installer signature verified`,
}
for _, needle := range required {
@@ -1123,6 +1263,7 @@ func TestPulseAutoUpdateScriptRequiresSignedInstallerDownloads(t *testing.T) {
t.Fatalf("pulse-auto-update.sh missing signed-installer verification contract: %s", needle)
}
}
requireSingleReleaseAssetDeclaration(t, script, "pulse-auto-update.sh")
}
func TestOperatorInstallDocsAvoidUnverifiedBootstrapAndFloatingImageTags(t *testing.T) {
@@ -3149,7 +3290,7 @@ func TestRootManualUpdateDownloadDeadlines(t *testing.T) {
key := filepath.Join(assets, "key")
installer := filepath.Join(assets, "install.sh")
const installerResult = "Signed fixture installer returned"
if err := os.WriteFile(installer, []byte("#!/bin/bash\nprintf '%s\\n' EXECUTED \"$@\" > \"$FIXTURE/executed\"\nprintf '%s\\n' '"+installerResult+"'\n"), 0600); err != nil {
if err := os.WriteFile(installer, []byte("#!/bin/bash\nPULSE_RELEASE_ASSET=\"install.sh\"\nprintf '%s\\n' EXECUTED \"$@\" > \"$FIXTURE/executed\"\nprintf '%s\\n' '"+installerResult+"'\n"), 0600); err != nil {
t.Fatal(err)
}
for _, args := range [][]string{
@@ -3308,7 +3449,7 @@ func TestRootManualUpdateHTTPSOnly(t *testing.T) {
assets := t.TempDir()
key := filepath.Join(assets, "key")
installer := filepath.Join(assets, "installer")
const payload = "#!/bin/bash\nprintf '%s\\n' \"$@\" > \"$PUBLICATION_ROOT/executed\"\n"
const payload = "#!/bin/bash\nPULSE_RELEASE_ASSET=\"install.sh\"\nprintf '%s\\n' \"$@\" > \"$PUBLICATION_ROOT/executed\"\n"
if err := os.WriteFile(installer, []byte(payload), 0o600); err != nil {
t.Fatal(err)
}

View File

@@ -67,8 +67,13 @@ func TestRootInstallerRegistrationDiagnostics(t *testing.T) {
if strings.HasPrefix(mode, "smoke-") {
exitCode = strings.TrimPrefix(mode, "smoke-")
}
// The installer keeps the administrator's working directory, which may
// be shared (/tmp). Modules there or on PYTHONPATH are not installer code.
caller := filepath.Join(root, "caller")
plantCallerPythonModules(t, caller)
env := append(rootCurlFixtureEnvironment(t, root, host), "FIXTURE_CURL_EXIT="+exitCode,
"PULSE_PVE_HOST_URL="+host, "PULSE_SKIP_AUTO_NODE=", "PULSE_AUTO_BACKUP_PERMS=true")
"PULSE_PVE_HOST_URL="+host, "PULSE_SKIP_AUTO_NODE=", "PULSE_AUTO_BACKUP_PERMS=true",
"PYTHONPATH="+caller)
script := `source "$ROOT_INSTALLER_SOURCE"
print_info() { :; }
print_warn() { printf 'WARN:%s\n' "$*"; }
@@ -113,6 +118,7 @@ IN_CONTAINER=false
AUTO_NODE_REGISTERED=false
AUTO_NODE_REGISTERED_NAME=unchanged
AUTO_NODE_REGISTER_ERROR=
cd "$FIXTURE_ROOT/caller"
auto_register_pve_node 600 127.0.0.1 7655 > "$FIXTURE_ROOT/output" 2>&1
printf '%s\n%s\n%s\n' "$AUTO_NODE_REGISTERED" "$AUTO_NODE_REGISTERED_NAME" "$AUTO_NODE_REGISTER_ERROR" > "$FIXTURE_ROOT/result"
`
@@ -166,6 +172,7 @@ printf '%s\n%s\n%s\n' "$AUTO_NODE_REGISTERED" "$AUTO_NODE_REGISTERED_NAME" "$AUT
}
}
assertRootCurlFixtureUnchanged(t, root, filepath.Join(root, "ambient-trace"), saved)
assertCallerPythonModulesUnused(t, caller)
t.Logf("%s: synthetic response; %s; no saved-state or request-identity change", mode, fmt.Sprintf("curl exit %s", exitCode))
})
}

View File

@@ -377,7 +377,16 @@ func TestUninstallSensorProxyClusterInventoryUsesEveryValidatedNode(t *testing.T
if err := os.WriteFile(filepath.Join(dir, "inventory"), []byte(`[{"node":"pve-b"},{"node":"pve-a"},{"node":"pve-b"},{"node":"pve-v6"}]`), 0600); err != nil {
t.Fatal(err)
}
out, code := runSensorProxySafetyShell(t, repoFile("scripts", "uninstall-sensor-proxy.sh"), dir, "success", proxyInventoryFixture)
// The documented "curl | bash" run keeps the administrator's working
// directory. Modules left in a shared one must not join the validators.
script, err := filepath.Abs(repoFile("scripts", "uninstall-sensor-proxy.sh"))
if err != nil {
t.Fatal(err)
}
caller := filepath.Join(dir, "caller")
plantCallerPythonModules(t, caller)
out, code := runSensorProxySafetyShell(t, script, dir, "success", `cd "$FIXTURE_DIR/caller"
`+proxyInventoryFixture)
if code != 0 {
t.Fatalf("exit %d: %s", code, out)
}
@@ -385,6 +394,7 @@ func TestUninstallSensorProxyClusterInventoryUsesEveryValidatedNode(t *testing.T
if err != nil || string(got) != "local\nremote 192.0.2.11\nremote 2001:db8::12\n" {
t.Fatalf("incomplete or duplicated cleanup: %q, %v", got, err)
}
assertCallerPythonModulesUnused(t, caller)
}
func TestUninstallSensorProxyIncompleteInventoryNeverStartsKeyCleanup(t *testing.T) {

View File

@@ -17,6 +17,11 @@ MAX_LOG_SIZE=10485760 # 10MB
INSTALL_SIGNATURE_IDENTITY="pulse-installer"
INSTALL_SIGNATURE_NAMESPACE="pulse-install"
PINNED_RELEASE_SSH_PUBLIC_KEY="ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMZd/DaH+BldzOkq1A8KVTcFk73nAyrE8aJOyf7i00jm pulse-installer"
# Release asset identity. Every asset of every release is signed with the same
# key, identity and namespace, so a signature alone does not say which asset
# the signed bytes are. verify_release_signature requires this exact line
# inside the signed bytes before a downloaded copy of this script is run.
PULSE_RELEASE_ASSET="pulse-auto-update.sh"
log_stdout() {
local level=$1 timestamp=""
@@ -64,6 +69,7 @@ verify_release_signature() {
local target_path="$1"
local signature_path="$2"
local context="${3:-downloaded file}"
local expected_asset="${4:-}"
local allowed_signers=""
if ! require_release_signature_verifier; then
@@ -84,6 +90,19 @@ verify_release_signature() {
fi
rm -f "$allowed_signers"
# The signature proves that Pulse published these bytes once, not which
# asset or release they are. A script that is about to be run must also
# name itself inside the signed bytes. A missing or mismatched declaration
# is a refusal because auto-updates only advance to newer releases.
if [[ -n "$expected_asset" ]]; then
local declared_assets=""
declared_assets=$(grep -E '^PULSE_RELEASE_ASSET=' "$target_path" 2>/dev/null || true)
if [[ "$declared_assets" != "PULSE_RELEASE_ASSET=\"${expected_asset}\"" ]]; then
log error "Signed ${context} does not declare itself as the ${expected_asset} release asset. Refusing it."
return 1
fi
fi
return 0
}
@@ -785,7 +804,7 @@ perform_update() {
log error "Failed to download installer signature from $install_signature_url"
return 1
fi
if ! verify_release_signature "$installer_tmp" "$signature_tmp" "downloaded Pulse installer"; then
if ! verify_release_signature "$installer_tmp" "$signature_tmp" "downloaded Pulse installer" "install.sh"; then
return 1
fi
log info "Installer signature verified"

View File

@@ -155,7 +155,8 @@ class NativeContracts(unittest.TestCase):
path.write_text(native.TRANSPORT)
path.chmod(0o755)
installer = root / "installer"
installer.write_text('#!/bin/bash\nprintf "%s\\n" "$@" > "$PULSE_NATIVE_ROOT/executed"\n')
installer.write_text('#!/bin/bash\nPULSE_RELEASE_ASSET="install.sh"\n'
'printf "%s\\n" "$@" > "$PULSE_NATIVE_ROOT/executed"\n')
key = root / "key"
subprocess.run(["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", str(key)],
check=True, capture_output=True)

View File

@@ -16,6 +16,10 @@ from unittest import mock
ROOT = Path(__file__).resolve().parents[2]
INSTALLER = Path(os.environ.get("PULSE_INSTALLER_UNDER_TEST", ROOT / "install.sh"))
# Every release asset is signed with the same key and namespace. A signed copy
# declaring another release asset must be refused as the container installer.
SIGNED_INSTALLER = b'#!/bin/bash\nPULSE_RELEASE_ASSET="install.sh"\n# inert signed fixture\n'
WRONG_ASSET_INSTALLER = b'#!/bin/bash\nPULSE_RELEASE_ASSET="pulse-auto-update.sh"\n# inert signed fixture\n'
HARNESS = r'''
source "$INSTALLER"
@@ -241,7 +245,8 @@ class ServerInstallerTemporaryInputsTest(unittest.TestCase):
(fixture / "shared").chmod(0o1777)
(fixture / "install").mkdir()
(fixture / "install/BUILD_FROM_SOURCE").write_text("old marker")
(fixture / "installer-input").write_text("#!/bin/bash\n# inert signed fixture\n")
(fixture / "installer-input").write_bytes(
WRONG_ASSET_INSTALLER if fault == "wrong_asset_installer" else SIGNED_INSTALLER)
key = fixture / "signing-key"
subprocess.run(["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", str(key)],
check=True, capture_output=True)
@@ -351,8 +356,8 @@ class ServerInstallerTemporaryInputsTest(unittest.TestCase):
def test_bootstrap_checks_real_signature_before_copy(self):
r, o = self.exercise("bootstrap")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual(o["copied"], b"#!/bin/bash\n# inert signed fixture\n")
self.assertEqual(o["caller-script"], b"#!/bin/bash\n# inert signed fixture\n")
self.assertEqual(o["copied"], SIGNED_INSTALLER)
self.assertEqual(o["caller-script"], SIGNED_INSTALLER)
self.assertEqual(o["transport"], [
"https://github.com/rcourtman/Pulse/releases/download/v6.6.0/install.sh",
"https://github.com/rcourtman/Pulse/releases/download/v6.6.0/install.sh.sshsig"])
@@ -360,7 +365,8 @@ class ServerInstallerTemporaryInputsTest(unittest.TestCase):
def test_bootstrap_fails_closed_and_cleans_every_owned_input(self):
for fault in ("metadata", "verifier", "allocation", "script_transport",
"signature_transport", "missing_signature", "bad_signature"):
"signature_transport", "missing_signature", "bad_signature",
"wrong_asset_installer"):
with self.subTest(fault=fault):
r, o = self.exercise("bootstrap", fault)
self.assertNotEqual(r.returncode, 0, r.stdout + r.stderr)
@@ -383,12 +389,12 @@ class ServerInstallerTemporaryInputsTest(unittest.TestCase):
def test_production_container_bootstrap_copies_only_the_verified_installer(self):
r, o = self.exercise("connected_container")
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
self.assertEqual(o["copied"], b"#!/bin/bash\n# inert signed fixture\n")
self.assertEqual(o["copied"], SIGNED_INSTALLER)
self.assertIn("EXECUTE", o["calls"])
self.assertEqual(o["shared_entries"], [])
def test_production_container_never_copies_invalid_or_unavailable_signed_input(self):
for fault in ("bad_signature", "script_transport", "signature_transport", "missing_signature", "script_interrupt"):
for fault in ("bad_signature", "wrong_asset_installer", "script_transport", "signature_transport", "missing_signature", "script_interrupt"):
with self.subTest(fault=fault):
r, o = self.exercise("connected_container", fault)
self.assertEqual(r.returncode, 143 if fault == "script_interrupt" else 1,
@@ -409,8 +415,8 @@ class ServerInstallerTemporaryInputsTest(unittest.TestCase):
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
self.assertEqual(o["transport"], [])
self.assertEqual(o["override"], (b"caller archive", b"caller signature"))
self.assertEqual(o["copied"], b"#!/bin/bash\n# inert signed fixture\n")
self.assertEqual(o["caller-script"], b"#!/bin/bash\n# inert signed fixture\n")
self.assertEqual(o["copied"], SIGNED_INSTALLER)
self.assertEqual(o["caller-script"], SIGNED_INSTALLER)
self.assertEqual(o["shared_entries"], [])

View File

@@ -72,7 +72,7 @@ resolve_path() {
fi
if command -v python3 >/dev/null 2>&1; then
python3 - "$path" <<'PY'
python3 -I - "$path" <<'PY'
import os
import sys
print(os.path.realpath(sys.argv[1]))
@@ -209,8 +209,10 @@ is_local_host() {
# The program is passed with -c so stdin remains the complete API response.
# Validate every row before emitting any identities; a partial list is unsafe.
# Inline Python runs isolated (-I): this script is started from the caller's
# working directory, and modules there or on PYTHONPATH must not be imported.
sensor_proxy_inventory() {
python3 -c '
python3 -I -c '
import json, re, sys
field = sys.argv[1]
try:
@@ -249,7 +251,7 @@ discover_cluster_node_addresses() {
if [[ -z "$node_ip" ]]; then
node_ip=$(getent hosts "$node" 2>/dev/null | awk 'NR==1 {print $1}') || node_ip=""
fi
if [[ -z "$node_ip" ]] || ! node_ip=$(python3 -c '
if [[ -z "$node_ip" ]] || ! node_ip=$(python3 -I -c '
import ipaddress, sys
try:
print(ipaddress.ip_address(sys.argv[1]))

View File

@@ -539,6 +539,20 @@ if ! echo "$install_help_output" | grep -qF "Install specific version (e.g."; th
fi
success "install.sh is the Pulse server installer (handles --version, --help prints server help)"
# The update helpers run a downloaded script only when it is signed and names
# itself as the asset it was fetched as, because one key and namespace sign
# every asset of every release. A release whose script lacks that line would be
# refused by auto-updaters, and a second line could pass as another asset.
info "Validating release scripts declare their asset identity..."
for script_asset in install.sh pulse-auto-update.sh; do
declared_assets="$(grep -E '^PULSE_RELEASE_ASSET=' "$script_asset" || true)"
if [ "$declared_assets" != "PULSE_RELEASE_ASSET=\"${script_asset}\"" ]; then
error "${script_asset} must declare PULSE_RELEASE_ASSET=\"${script_asset}\" exactly once. Update helpers refuse a signed script with missing or mismatched identity."
exit 1
fi
done
success "install.sh and pulse-auto-update.sh declare their release asset identity"
# Validate tarball contents
section "Validating tarball contents"
tar_arches=(linux-amd64 linux-arm64 linux-armv7 linux-armv6 linux-386)