From 98c42ca7c1c9d21cf1bd895a0995ef06b6abfffc Mon Sep 17 00:00:00 2001 From: ruihan Date: Mon, 6 Jul 2026 01:32:02 +0000 Subject: [PATCH 01/17] fix: redirect low-level logging functions to STDERR --- lib/colors.sh | 4 ++-- unleash-standalone.sh | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/colors.sh b/lib/colors.sh index c08d231..54c27a2 100644 --- a/lib/colors.sh +++ b/lib/colors.sh @@ -32,7 +32,7 @@ log() { local ts ts=$(date '+%H:%M:%S') - echo -e "${color}[${label}]${NC} ${msg}" + echo -e "${color}[${label}]${NC} ${msg}" >&2 if [ -n "$LOG_FILE" ]; then echo "[${ts}] [${label}] ${msg}" >> "$LOG_FILE" 2>/dev/null || true @@ -40,7 +40,7 @@ log() { } error_exit() { - log "ERROR" "$1" >&2 + log "ERROR" "$1" exit 1 } diff --git a/unleash-standalone.sh b/unleash-standalone.sh index 347311c..1e0d4d8 100755 --- a/unleash-standalone.sh +++ b/unleash-standalone.sh @@ -35,7 +35,7 @@ log() { local ts ts=$(date '+%H:%M:%S') - echo -e "${color}[${label}]${NC} ${msg}" + echo -e "${color}[${label}]${NC} ${msg}" >&2 if [ -n "$LOG_FILE" ]; then echo "[${ts}] [${label}] ${msg}" >> "$LOG_FILE" 2>/dev/null || true @@ -43,7 +43,7 @@ log() { } error_exit() { - log "ERROR" "$1" >&2 + log "ERROR" "$1" exit 1 } From d0a797db619e83b40807a668988446dfd695acaf Mon Sep 17 00:00:00 2001 From: ruihan Date: Fri, 30 Oct 2026 03:51:08 -0300 Subject: [PATCH 02/17] test(logging): keep helper output free of diagnostics --- tests/test_colors.bats | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/tests/test_colors.bats b/tests/test_colors.bats index 424b12f..e61000a 100644 --- a/tests/test_colors.bats +++ b/tests/test_colors.bats @@ -2,6 +2,7 @@ # Tests for colors.sh - run with: bats tests/test_colors.bats setup() { + bats_require_minimum_version 1.5.0 load '../lib/colors.sh' TEST_LOG=$(mktemp) } @@ -39,3 +40,33 @@ teardown() { [ "$status" -eq 0 ] echo "$output" | grep -q "Test Title" } + +@test "diagnostics use stderr without contaminating helper return values" { + local source_file + for source_file in lib/colors.sh unleash-standalone.sh; do + run --separate-stderr bash -u -c ' + source <(sed "/^error_exit()/,\$d" "$1") + volume_path() { + log INFO "Locating Data volume" + log OK "Data volume found" + printf "%s\n" "/Volumes/Work Data" + } + result=$(volume_path) + printf "%s\n" "$result" + ' bash "$BATS_TEST_DIRNAME/../$source_file" + + [ "$status" -eq 0 ] + [ "$output" = "/Volumes/Work Data" ] + [[ "$stderr" == *"Locating Data volume"* ]] + [[ "$stderr" == *"Data volume found"* ]] + done +} + +@test "diagnostics still reach the log file when stdout is captured" { + LOG_FILE="$TEST_LOG" + local result + result=$(log WARN "Review the selected volume" 2>/dev/null) + + [ -z "$result" ] + grep -q 'Review the selected volume' "$TEST_LOG" +} From 7ca3d4f2d47b7a5d737b80f1326a139d3428de0f Mon Sep 17 00:00:00 2001 From: ruihan Date: Fri, 30 Oct 2026 03:56:14 -0300 Subject: [PATCH 03/17] fix(suppression): preserve access to Rosetta configuration --- lib/suppress.sh | 1 - tests/test_rosetta.bats | 19 +++++++++++++++++++ unleash-standalone.sh | 1 - 3 files changed, 19 insertions(+), 2 deletions(-) create mode 100644 tests/test_rosetta.bats diff --git a/lib/suppress.sh b/lib/suppress.sh index 2c513f5..223d54d 100644 --- a/lib/suppress.sh +++ b/lib/suppress.sh @@ -50,7 +50,6 @@ suppress_enrollment() { gdmf.apple.com ax.init-content.apple.com init-content.apple.com - configuration.apple.com xp.apple.com gs.apple.com tb.apple.com diff --git a/tests/test_rosetta.bats b/tests/test_rosetta.bats new file mode 100644 index 0000000..1403de8 --- /dev/null +++ b/tests/test_rosetta.bats @@ -0,0 +1,19 @@ +#!/usr/bin/env bats + +@test "suppression does not add hosts blocks for Rosetta configuration" { + local entrypoint + for entrypoint in unleash unleash-standalone.sh; do + local script="$BATS_TEST_DIRNAME/../$entrypoint" + local target="$BATS_TEST_TMPDIR/$entrypoint" + mkdir -p "$target/private/etc" + printf '127.0.0.1 localhost\n' > "$target/private/etc/hosts" + run bash -u -c ' + source <(sed '\''/^main "\$@"$/d'\'' "$1") + PB=: + suppress_enrollment "$2" + ' "$script" "$script" "$target" + [ "$status" -eq 0 ] + ! grep -q 'configuration[.]apple[.]com' "$target/private/etc/hosts" + grep -q '^127.0.0.1 localhost$' "$target/private/etc/hosts" + done +} diff --git a/unleash-standalone.sh b/unleash-standalone.sh index 347311c..ea129e0 100755 --- a/unleash-standalone.sh +++ b/unleash-standalone.sh @@ -459,7 +459,6 @@ suppress_enrollment() { gdmf.apple.com ax.init-content.apple.com init-content.apple.com - configuration.apple.com xp.apple.com gs.apple.com tb.apple.com From 993db74118030a947074e6ffce1b563858b4f9fc Mon Sep 17 00:00:00 2001 From: ruihan Date: Fri, 30 Oct 2026 03:56:33 -0300 Subject: [PATCH 04/17] test(suppression): assert the Rosetta block lookup status --- tests/test_rosetta.bats | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/test_rosetta.bats b/tests/test_rosetta.bats index 1403de8..2999dbf 100644 --- a/tests/test_rosetta.bats +++ b/tests/test_rosetta.bats @@ -13,7 +13,8 @@ suppress_enrollment "$2" ' "$script" "$script" "$target" [ "$status" -eq 0 ] - ! grep -q 'configuration[.]apple[.]com' "$target/private/etc/hosts" + run grep -q 'configuration[.]apple[.]com' "$target/private/etc/hosts" + [ "$status" -eq 1 ] grep -q '^127.0.0.1 localhost$' "$target/private/etc/hosts" done } From 8a560b8e6ef38768520841d118ddcf73c698ff2b Mon Sep 17 00:00:00 2001 From: ruihan Date: Fri, 30 Oct 2026 04:21:56 -0300 Subject: [PATCH 05/17] fix(validation): restore isolated local checks --- Makefile | 21 +--- README.md | 3 + lib/colors.sh | 7 +- lib/config.sh | 32 +++-- lib/detect.sh | 7 +- lib/discord.sh | 4 +- lib/firewall.sh | 36 +++--- lib/harden.sh | 28 +++-- lib/heal.sh | 8 +- lib/history.sh | 6 +- lib/ma_detect.sh | 29 +++-- lib/monitor.sh | 12 +- lib/predict.sh | 6 +- lib/remediate.sh | 1 - lib/report.sh | 4 +- lib/selfupdate.sh | 2 +- lib/status.sh | 28 +++-- lib/suppress.sh | 3 +- lib/validate.sh | 4 +- lib/vpn.sh | 12 +- lib/whitelist.sh | 14 +-- scripts/check-shell.py | 59 ++++++++++ tests/helpers/platform.py | 76 ++++++++++++ tests/setup_suite.bash | 20 ++++ tests/test_colors.bats | 7 ++ tests/test_config.bats | 19 +++ tests/test_detect.bats | 20 ++-- tests/test_harden.bats | 8 +- tests/test_history.bats | 6 +- tests/test_lint.bats | 48 ++++++++ tests/test_ma_detect.bats | 16 ++- tests/test_monitor.bats | 4 +- tests/test_status.bats | 13 +++ tests/test_suppress.bats | 8 +- unleash | 5 +- unleash-standalone.sh | 237 +++++++++++++++++++++++--------------- 36 files changed, 586 insertions(+), 227 deletions(-) create mode 100644 scripts/check-shell.py create mode 100644 tests/helpers/platform.py create mode 100644 tests/setup_suite.bash create mode 100644 tests/test_lint.bats diff --git a/Makefile b/Makefile index 3b0d058..43ae970 100644 --- a/Makefile +++ b/Makefile @@ -1,8 +1,7 @@ .PHONY: lint test build clean ci lint: - shellcheck unleash lib/*.sh 2>/dev/null || brew install shellcheck && shellcheck unleash lib/*.sh - bash -n unleash lib/*.sh + python3 scripts/check-shell.py test: bats tests/*.bats @@ -13,18 +12,6 @@ build: clean: rm -f unleash-standalone.sh -ci: - @echo "=== ShellCheck ===" && \ - for f in unleash lib/*.sh examples/*.sh; do \ - [ -f "$$f" ] || continue; \ - echo " $$f"; shellcheck -S warning "$$f" || fail=1; \ - done && \ - echo "=== Bash Syntax ===" && \ - for f in unleash lib/*.sh examples/*.sh; do \ - [ -f "$$f" ] || continue; \ - bash -n "$$f" || fail=1; \ - done && \ - echo "=== Markdown ===" && \ - npx markdownlint-cli '*.md' || true && \ - echo "=== All checks done ===" && \ - [ -z "$$fail" ] || exit 1 +ci: lint test + @echo "=== Markdown ===" + npx markdownlint-cli '*.md' || true diff --git a/README.md b/README.md index dc83972..420f732 100644 --- a/README.md +++ b/README.md @@ -475,6 +475,9 @@ MA copies user-level caches, preferences, and launch agents. Unleash handles thi ## Contributing +Run `make ci` with Bash, Python 3.9+, ShellCheck, and Bats (validated with Bats 1.12). +The test suite uses temporary volumes and inert macOS command fixtures; it does not validate behavior on real Mac hardware. + See CONTRIBUTING.md. PRs welcome, especially for: - New macOS version compatibility diff --git a/lib/colors.sh b/lib/colors.sh index c08d231..c81ef86 100644 --- a/lib/colors.sh +++ b/lib/colors.sh @@ -68,7 +68,8 @@ header() { local title="$1" local len="${#title}" local line - line=$(printf '%*s' "$((len + 4))" | tr ' ' '═') + line=$(printf '%*s' "$((len + 4))" '') + line="${line// /═}" echo "" echo -e "${CYAN}╔${line}╗${NC}" echo -e "${CYAN}║ ${title} ║${NC}" @@ -107,7 +108,7 @@ prompt_default() { local prompt_text="$2" local default="$3" local value - read -p "${CYAN}${prompt_text}${NC} (default '${default}'): " value + read -r -p "${CYAN}${prompt_text}${NC} (default '${default}'): " value value="${value:=$default}" eval "$var_name=\"$value\"" } @@ -115,6 +116,6 @@ prompt_default() { confirm() { local prompt="$1" local response - read -p "${prompt} (y/N): " response + read -r -p "${prompt} (y/N): " response [[ "$response" =~ ^[Yy]$ ]] } diff --git a/lib/config.sh b/lib/config.sh index e0134c3..bd7a8a2 100644 --- a/lib/config.sh +++ b/lib/config.sh @@ -2,10 +2,9 @@ CONFIG_FILE="$HOME/.unleash.conf" load_config() { [ -f "$CONFIG_FILE" ] || return 0 - - while IFS='=' read -r key value; do + local key value + while IFS='=' read -r key value || [ -n "$key" ]; do key="${key// /}" - value="${value// /}" [ -z "$key" ] && continue case "$key" in WEBHOOK) DISCORD_WEBHOOK="$value" ;; @@ -15,18 +14,29 @@ load_config() { done < "$CONFIG_FILE" } -save_config() { +_rewrite_config() { local key="$1" local value="$2" local tmp - [ -f "$CONFIG_FILE" ] || touch "$CONFIG_FILE" - - if grep -q "^${key}=" "$CONFIG_FILE" 2>/dev/null; then - sed -i '' "s/^${key}=.*/${key}=${value}/" "$CONFIG_FILE" - else - echo "${key}=${value}" >> "$CONFIG_FILE" + tmp=$(mktemp "${CONFIG_FILE}.XXXXXX") || return 1 + if ! UNLEASH_CONFIG_KEY="$key" UNLEASH_CONFIG_VALUE="$value" \ + UNLEASH_CONFIG_OPERATION="${3:-set}" awk ' + BEGIN { key=ENVIRON["UNLEASH_CONFIG_KEY"]; value=ENVIRON["UNLEASH_CONFIG_VALUE"]; + operation=ENVIRON["UNLEASH_CONFIG_OPERATION"] } + index($0, key "=")==1 { if (!found++ && operation=="set") print key "=" value; next } + { print } + END { if (!found && operation=="set") print key "=" value } + ' "$CONFIG_FILE" > "$tmp"; then + rm -f "$tmp" + return 1 fi + mv "$tmp" "$CONFIG_FILE" +} + +save_config() { + local key="$1" value="$2" + _rewrite_config "$key" "$value" || return 1 success "Saved $key to $CONFIG_FILE" } @@ -56,7 +66,7 @@ cmd_config() { local key="$3" [ -z "$key" ] && { info "Usage: ./unleash config unset KEY"; return 1; } if [ -f "$CONFIG_FILE" ]; then - sed -i '' "/^${key}=/d" "$CONFIG_FILE" + _rewrite_config "$key" "" unset || return 1 success "Removed $key from config" fi ;; diff --git a/lib/detect.sh b/lib/detect.sh index 831353e..21fee6e 100644 --- a/lib/detect.sh +++ b/lib/detect.sh @@ -32,7 +32,8 @@ resolve_data_volume() { warn "Auto-detection failed. Available disks:" diskutil list >&2 echo "" - read -p "Enter Data volume identifier (e.g. disk3s1): " id /dev/null; then info "pf.conf already has Unleash anchor" else - echo "" >> "$pf_conf" - echo "# Added by unleash — MDM block" >> "$pf_conf" - echo "$anchor_line" >> "$pf_conf" - echo "$load_line" >> "$pf_conf" + printf '\n%s\n%s\n%s\n' "# Added by unleash — MDM block" "$anchor_line" "$load_line" >> "$pf_conf" success "pf.conf updated" fi else @@ -79,8 +78,11 @@ ANCHOR step "Loading pf rules..." if command -v pfctl &>/dev/null; then - pfctl -e -f "$pf_conf" 2>/dev/null && success "pf enabled and rules loaded" \ - || warn "pfctl failed — try: sudo pfctl -e -f $pf_conf" + if pfctl -e -f "$pf_conf" 2>/dev/null; then + success "pf enabled and rules loaded" + else + warn "pfctl failed — try: sudo pfctl -e -f $pf_conf" + fi else warn "pfctl not available" fi @@ -105,8 +107,14 @@ remove_pf_mdm_block() { local pf_conf="${root}${FIREWALL_CONF}" if [ -f "$pf_conf" ]; then - sed -i '' '/# Added by unleash/d' "$pf_conf" 2>/dev/null || true - sed -i '' '/com\.unleash/d' "$pf_conf" 2>/dev/null || true + local tmp_conf + tmp_conf=$(mktemp "${pf_conf}.XXXXXX") || return 1 + if ! cp -p "$pf_conf" "$tmp_conf" \ + || ! sed '/# Added by unleash/d; /com\.unleash/d' "$pf_conf" > "$tmp_conf" \ + || ! mv "$tmp_conf" "$pf_conf"; then + rm -f "$tmp_conf" + return 1 + fi success "pf.conf cleaned" fi @@ -124,9 +132,11 @@ pf_status() { if command -v pfctl &>/dev/null; then pfctl -si 2>/dev/null | grep -E "Status|Enabled" || echo " pf not enabled" echo "" - pfctl -a "$FIREWALL_ANCHOR" -s rules 2>/dev/null \ - && info "Unleash MDM anchor rules:" \ - || info "No Unleash MDM anchor loaded" + if pfctl -a "$FIREWALL_ANCHOR" -s rules 2>/dev/null; then + info "Unleash MDM anchor rules:" + else + info "No Unleash MDM anchor loaded" + fi else warn "pfctl not available" fi diff --git a/lib/harden.sh b/lib/harden.sh index 058bc33..3cd7e17 100644 --- a/lib/harden.sh +++ b/lib/harden.sh @@ -14,8 +14,11 @@ harden_live_os() { local installed installed=$(profiles -C -output=xml 2>/dev/null | grep -c "ProfileDisplayName" || true) if [ "$installed" -gt 0 ]; then - sudo profiles -D -F 2>/dev/null && success "Forced profile removal" \ - || warn "Profile removal failed" + if sudo profiles -D -F 2>/dev/null; then + success "Forced profile removal" + else + warn "Profile removal failed" + fi else info "No installed profiles to remove" fi @@ -24,8 +27,8 @@ harden_live_os() { fi step "Cleaning user LaunchAgents..." - local home - for home in /Users/*/; do + local home users_root="${1:-}/Users" + for home in "$users_root/"*/; do [ -d "$home/Library/LaunchAgents" ] || continue local cleaned=0 for agent in "$home/Library/LaunchAgents/"*; do @@ -35,8 +38,11 @@ harden_live_os() { cleaned=$((cleaned + 1)) fi done - [ "$cleaned" -gt 0 ] && success "$(basename "$home"): removed $cleaned agent(s)" \ - || info "$(basename "$home"): clean" + if [ "$cleaned" -gt 0 ]; then + success "$(basename "$home"): removed $cleaned agent(s)" + else + info "$(basename "$home"): clean" + fi done step "Flushing DNS cache..." @@ -70,9 +76,11 @@ harden_live_os() { step "Disabling iCloud Private Relay (DoH source)..." if command -v defaults &>/dev/null; then - sudo defaults write /Library/Preferences/com.apple.networkextensions.plist PrivateRelayEnabled -bool false 2>/dev/null \ - && success "Private Relay disabled" \ - || info "Private Relay not configurable (expected on some configs)" + if sudo defaults write /Library/Preferences/com.apple.networkextensions.plist PrivateRelayEnabled -bool false 2>/dev/null; then + success "Private Relay disabled" + else + info "Private Relay not configurable (expected on some configs)" + fi fi echo "" @@ -96,5 +104,5 @@ harden_status() { launchctl list 2>/dev/null | grep -iE "mdm|managed|enrollment|activation" || info "None loaded" step "Running MDM processes..." - ps aux 2>/dev/null | grep -iE "mdm|managedclient|activation" | grep -v grep || info "None running" + pgrep -il "mdm|managedclient|activation" 2>/dev/null || info "None running" } diff --git a/lib/heal.sh b/lib/heal.sh index 695ac5a..08d5157 100644 --- a/lib/heal.sh +++ b/lib/heal.sh @@ -117,9 +117,11 @@ install_persist_launchdaemon() { step "Loading LaunchDaemon..." if command -v launchctl &>/dev/null; then - launchctl load "$plist_path" 2>/dev/null \ - && success "LaunchDaemon loaded (will run on next boot)" \ - || info "LaunchDaemon will load on next boot" + if launchctl load "$plist_path" 2>/dev/null; then + success "LaunchDaemon loaded (will run on next boot)" + else + info "LaunchDaemon will load on next boot" + fi else info "launchctl not available (expected in Recovery) — will load on next boot" fi diff --git a/lib/history.sh b/lib/history.sh index 309c7fe..e8092ff 100644 --- a/lib/history.sh +++ b/lib/history.sh @@ -1,7 +1,8 @@ show_history() { header "Unleash Event History" - local logs=("/var/log/unleash-monitor.log" "/var/log/unleash-heal.log" "/var/log/unleash-monitor.err") + local log_dir="${1:-/var/log}" + local logs=("$log_dir/unleash-monitor.log" "$log_dir/unleash-heal.log" "$log_dir/unleash-monitor.err") local found=false for logfile in "${logs[@]}"; do @@ -34,7 +35,8 @@ show_history() { } clear_history() { - local logs=("/var/log/unleash-monitor.log" "/var/log/unleash-heal.log" "/var/log/unleash-monitor.err") + local log_dir="${1:-/var/log}" + local logs=("$log_dir/unleash-monitor.log" "$log_dir/unleash-heal.log" "$log_dir/unleash-monitor.err") for logfile in "${logs[@]}"; do if [ -f "$logfile" ]; then : > "$logfile" diff --git a/lib/ma_detect.sh b/lib/ma_detect.sh index 7b2086e..f837866 100644 --- a/lib/ma_detect.sh +++ b/lib/ma_detect.sh @@ -1,3 +1,11 @@ +_has_matching_path() { + local path + for path in "$@"; do + [ ! -e "$path" ] || return 0 + done + return 1 +} + detect_configurator_enrollment() { local data_mount="${1:-}" @@ -80,8 +88,13 @@ detect_migration_assistant() { local user_agents="$home/Library/LaunchAgents" if [ -d "$user_agents" ]; then - local found - found=$(ls "$user_agents" 2>/dev/null | grep -ciE "mdm|enrollment|managed" || true) + local found=0 agent + for agent in "$user_agents/"*; do + [ -f "$agent" ] || continue + if printf '%s\n' "${agent##*/}" | grep -qiE 'mdm|enrollment|managed'; then + found=$((found + 1)) + fi + done if [ "$found" -gt 0 ]; then ma_indicators=$((ma_indicators + found)) details="$details $user: $found MDM LaunchAgent(s)\n" @@ -90,9 +103,7 @@ detect_migration_assistant() { local prefs="$home/Library/Preferences" if [ -d "$prefs" ]; then - local mdm_prefs - mdm_prefs=$(ls "$prefs"/com.apple.mdm* "$prefs"/com.apple.ManagedClient* 2>/dev/null | head -3 || true) - if [ -n "$mdm_prefs" ]; then + if _has_matching_path "$prefs"/com.apple.mdm* "$prefs"/com.apple.ManagedClient*; then ma_indicators=$((ma_indicators + 1)) details="$details $user: MDM preference files\n" fi @@ -106,16 +117,12 @@ detect_migration_assistant() { local caches="$home/Library/Caches" if [ -d "$caches" ]; then - local enrollment_cache - enrollment_cache=$(ls "$caches"/com.apple.enrollment* 2>/dev/null | head -3 || true) - if [ -n "$enrollment_cache" ]; then + if _has_matching_path "$caches"/com.apple.enrollment*; then ma_indicators=$((ma_indicators + 1)) details="$details $user: enrollment cache files\n" fi - local mdmd_cache - mdmd_cache=$(ls "$caches"/com.apple.mdm* 2>/dev/null | head -3 || true) - if [ -n "$mdmd_cache" ]; then + if _has_matching_path "$caches"/com.apple.mdm*; then ma_indicators=$((ma_indicators + 1)) details="$details $user: MDM cache files\n" fi diff --git a/lib/monitor.sh b/lib/monitor.sh index f5eec98..7ad2ad2 100644 --- a/lib/monitor.sh +++ b/lib/monitor.sh @@ -47,9 +47,11 @@ PLIST success "Monitor LaunchDaemon: $plist_path" if command -v launchctl &>/dev/null; then - launchctl load "$plist_path" 2>/dev/null \ - && success "Monitor loaded (starts at boot)" \ - || info "Will load on next boot" + if launchctl load "$plist_path" 2>/dev/null; then + success "Monitor loaded (starts at boot)" + else + info "Will load on next boot" + fi fi } @@ -170,7 +172,7 @@ monitor_mdm() { } stop_monitor() { - local pidfile="/tmp/unleash-monitor.pid" + local pidfile="${1:-/tmp/unleash-monitor.pid}" if [ -f "$pidfile" ]; then local pid pid=$(cat "$pidfile") @@ -187,7 +189,7 @@ stop_monitor() { } monitor_status() { - local pidfile="/tmp/unleash-monitor.pid" + local pidfile="${1:-/tmp/unleash-monitor.pid}" if [ -f "$pidfile" ] && kill -0 "$(cat "$pidfile")" 2>/dev/null; then echo -e "${GRN}Monitor running (PID $(cat "$pidfile"))${NC}" tail -5 /var/log/unleash-monitor.log 2>/dev/null || echo " (no log entries yet)" diff --git a/lib/predict.sh b/lib/predict.sh index 9a9cb6d..2d81d2d 100644 --- a/lib/predict.sh +++ b/lib/predict.sh @@ -9,7 +9,7 @@ cmd_predict() { serial="${1:-}" fi if [ -z "$serial" ]; then - read -p "Enter serial number (or press Enter to skip): " serial + read -r -p "Enter serial number (or press Enter to skip): " serial fi if [ -z "$serial" ]; then info "No serial provided. Run: ./unleash predict " @@ -33,7 +33,8 @@ H4C:School District Managed VMW:VMware Workspace ONE M5K:Addigy Managed W4P:Kandji Managed -ORGS) +ORGS + ) local match match=$(echo "$known_orgs" | grep "^$serial_prefix:" || true) @@ -49,6 +50,5 @@ ORGS) info "The device may be from a smaller org or not organizationally enrolled." fi - local check_url="https://billing.c.apple.com/check?sn=${serial}" info "For definitive ownership: https://checkcoverage.apple.com" } diff --git a/lib/remediate.sh b/lib/remediate.sh index 8bbe3f2..4015033 100644 --- a/lib/remediate.sh +++ b/lib/remediate.sh @@ -1,5 +1,4 @@ -CMD_SUGGEST="" known_orgs() { cat << 'ORGS' diff --git a/lib/report.sh b/lib/report.sh index c835609..b7af874 100644 --- a/lib/report.sh +++ b/lib/report.sh @@ -87,9 +87,9 @@ generate_report() { step "Running MDM Processes" local procs - procs=$(ps aux 2>/dev/null | grep -iE "mdm|managedclient|activation" | grep -v grep || true) + procs=$(pgrep -il "mdm|managedclient|activation" 2>/dev/null || true) if [ -n "$procs" ]; then - echo "$procs" | awk '{print " " $11 " (PID " $2 ")"}' + echo "$procs" | awk '{print " " $2 " (PID " $1 ")"}' else echo " None" fi diff --git a/lib/selfupdate.sh b/lib/selfupdate.sh index 3dfce8a..2a0fe30 100644 --- a/lib/selfupdate.sh +++ b/lib/selfupdate.sh @@ -54,7 +54,7 @@ do_self_update() { fi end_ok; echo " Latest: v$latest_tag" - if [ "v$latest_tag" = "$(echo "v$VERSION")" ]; then + if [ "v$latest_tag" = "v$VERSION" ]; then success "Already up to date (v$VERSION)" rm -rf "$tmp_dir" return 0 diff --git a/lib/status.sh b/lib/status.sh index 5c05bf5..8b6fbb6 100644 --- a/lib/status.sh +++ b/lib/status.sh @@ -79,6 +79,16 @@ check_mdm_status() { fi } +_mdm_agent_names() { + local agent + for agent in "$1/"*; do + [ -f "$agent" ] || continue + if printf '%s\n' "${agent##*/}" | grep -qiE 'mdm|enrollment|managed'; then + printf '%s\n' "${agent##*/}" + fi + done +} + deep_status() { if [ "${1:-}" = "--json" ]; then deep_status_json @@ -127,10 +137,10 @@ deep_status() { for home in /Users/*/; do [ -d "$home/Library/LaunchAgents" ] || continue local user_agents - user_agents=$(ls "$home/Library/LaunchAgents/" 2>/dev/null | grep -iE "mdm|enrollment|managed" || true) + user_agents=$(_mdm_agent_names "$home/Library/LaunchAgents") if [ -n "$user_agents" ]; then echo -e " ${YEL}$(basename "$home"):${NC}" - echo "$user_agents" | sed 's/^/ /' + while IFS= read -r agent; do printf ' %s\n' "$agent"; done <<< "$user_agents" found=$((found + 1)) fi done @@ -139,9 +149,9 @@ deep_status() { step "MDM LaunchDaemons (System)" local sys_agents - sys_agents=$(ls /Library/LaunchDaemons/ 2>/dev/null | grep -iE "mdm|enrollment|managed" || true) + sys_agents=$(_mdm_agent_names /Library/LaunchDaemons) if [ -n "$sys_agents" ]; then - echo "$sys_agents" | sed 's/^/ /' + while IFS= read -r agent; do printf ' %s\n' "$agent"; done <<< "$sys_agents" else info "No MDM LaunchDaemons found" fi @@ -149,9 +159,9 @@ deep_status() { step "Running MDM Processes" local procs - procs=$(ps aux 2>/dev/null | grep -iE "mdm|managedclient|activation" | grep -v grep || true) + procs=$(pgrep -il "mdm|managedclient|activation" 2>/dev/null || true) if [ -n "$procs" ]; then - echo "$procs" | awk '{print " " $11 " (PID " $2 ")"}' + echo "$procs" | awk '{print " " $2 " (PID " $1 ")"}' else info "No MDM processes running" fi @@ -174,7 +184,7 @@ deep_status() { step "Overall Assessment" local risk="LOW" [ "$(sudo profiles -C -output=xml 2>/dev/null | grep -c "ProfileDisplayName" || echo 0)" -gt 0 ] && risk="MEDIUM" - ps aux 2>/dev/null | grep -qiE "mdm|managedclient" && risk="HIGH" + pgrep -i "mdm|managedclient" >/dev/null 2>&1 && risk="HIGH" [ -f "$cfg/.cloudConfigRecordFound" ] && risk="CRITICAL" case "$risk" in @@ -211,9 +221,7 @@ deep_status_json() { json="${json} \"mdm_certificates\": $mdm_certs,\n" local running_procs=0 - running_procs=$(ps aux 2>/dev/null | grep -ciE "mdm|managedclient|activation" || true) - running_procs=$((running_procs - 1)) - [ "$running_procs" -lt 0 ] && running_procs=0 + running_procs=$(pgrep -il "mdm|managedclient|activation" 2>/dev/null | awk 'END {print NR}' || true) json="${json} \"running_mdm_processes\": $running_procs,\n" local risk="LOW" diff --git a/lib/suppress.sh b/lib/suppress.sh index 2c513f5..a1e391d 100644 --- a/lib/suppress.sh +++ b/lib/suppress.sh @@ -1,6 +1,6 @@ -PB=/usr/libexec/PlistBuddy +PB="${PB:-/usr/libexec/PlistBuddy}" suppress_enrollment() { local data_mount="$1" @@ -147,6 +147,7 @@ full_bypass_mode() { echo "" step "Creating temporary admin account" + local realName prompt_default realName "Full name" "Apple" local username diff --git a/lib/validate.sh b/lib/validate.sh index 2ac9e61..1f7fb01 100644 --- a/lib/validate.sh +++ b/lib/validate.sh @@ -20,7 +20,7 @@ prompt_username() { local var_name="$1" local value while true; do - read -p "Username (default 'Apple'): " value + read -r -p "Username (default 'Apple'): " value value="${value:=Apple}" if msg=$(validate_username "$value"); then eval "$var_name=\"$value\"" @@ -35,7 +35,7 @@ prompt_password() { local var_name="$1" local value while true; do - read -p "Password (default '1234'): " value + read -r -p "Password (default '1234'): " value value="${value:=1234}" if msg=$(validate_password "$value"); then eval "$var_name=\"$value\"" diff --git a/lib/vpn.sh b/lib/vpn.sh index 3588a6a..ca5e08f 100644 --- a/lib/vpn.sh +++ b/lib/vpn.sh @@ -58,14 +58,14 @@ RULES if grep -q "vpn-kill" "$pf_conf" 2>/dev/null; then info "pf.conf already has VPN kill-switch anchor" else - echo "" >> "$pf_conf" - echo "# Added by unleash — VPN kill-switch (prevents MDM leaks)" >> "$pf_conf" - echo "$anchor_line" >> "$pf_conf" - echo "$load_line" >> "$pf_conf" + printf '\n%s\n%s\n%s\n' "# Added by unleash — VPN kill-switch (prevents MDM leaks)" "$anchor_line" "$load_line" >> "$pf_conf" fi - pfctl -e -f "$pf_conf" 2>/dev/null && success "VPN kill-switch active" \ - || warn "pfctl failed" + if pfctl -e -f "$pf_conf" 2>/dev/null; then + success "VPN kill-switch active" + else + warn "pfctl failed" + fi echo "" info "What this does:" diff --git a/lib/whitelist.sh b/lib/whitelist.sh index 1f73457..ecf109e 100644 --- a/lib/whitelist.sh +++ b/lib/whitelist.sh @@ -11,7 +11,7 @@ install_selective_block() { local anchor_file="${anchor_dir}/com.unleash.selective" mkdir -p "$anchor_dir" - > "$anchor_file" + : > "$anchor_file" for d in $MDM_BLOCKLIST; do for ip in $(host -t a "$d" 2>/dev/null | awk '/has address/{print $NF}'); do @@ -33,10 +33,7 @@ install_selective_block() { if grep -q "com.unleash.selective" "$pf_conf" 2>/dev/null; then info "pf.conf already has selective anchor" else - echo "" >> "$pf_conf" - echo "# Added by unleash — selective MDM block (iCloud-safe)" >> "$pf_conf" - echo "$anchor_line" >> "$pf_conf" - echo "$load_line" >> "$pf_conf" + printf '\n%s\n%s\n%s\n' "# Added by unleash — selective MDM block (iCloud-safe)" "$anchor_line" "$load_line" >> "$pf_conf" success "pf.conf updated with selective rules" fi else @@ -56,8 +53,11 @@ EOF fi if command -v pfctl &>/dev/null; then - pfctl -e -f "$pf_conf" 2>/dev/null && success "pf rules loaded (iCloud should work)" \ - || warn "pfctl failed" + if pfctl -e -f "$pf_conf" 2>/dev/null; then + success "pf rules loaded (iCloud should work)" + else + warn "pfctl failed" + fi fi } diff --git a/scripts/check-shell.py b/scripts/check-shell.py new file mode 100644 index 0000000..3408175 --- /dev/null +++ b/scripts/check-shell.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +"""Check modules in their shared Bash context without executing the application.""" +import json +import pathlib +import re +import shlex +import shutil +import subprocess +import sys +import tempfile + +root = pathlib.Path(__file__).resolve().parents[1] +for tool in ("bash", "shellcheck"): + if not shutil.which(tool): + sys.exit(f"{tool} is required; install it before running make lint") + +entrypoint = root / "unleash" +source = entrypoint.read_text() +loader = re.search(r"^for _lib in ([a-z_ ]+); do\n.*?^done$", source, re.M | re.S) +if not loader: + sys.exit("Cannot identify the module loader in unleash") +modules = [root / "lib" / (name + ".sh") for name in loader[1].split()] +if set(modules) != set((root / "lib").glob("*.sh")): + sys.exit("The module loader and library files do not match") + +# Literal sources let ShellCheck follow shared globals and report module locations. +# Keep the loader's line count so dispatcher diagnostics retain their real lines. +literal_sources = "; ".join("source " + shlex.quote(str(path)) for path in modules) +context = source[:loader.start()] + literal_sources +context += "\n" * loader[0].count("\n") + source[loader.end():] +examples = sorted((root / "examples").glob("*.sh")) +failed = False +for path in [entrypoint, *modules, *examples, root / "unleash-standalone.sh"]: + result = subprocess.run(["bash", "-n", str(path)], check=False) + failed |= result.returncode != 0 + +with tempfile.NamedTemporaryFile(mode="w", suffix=".sh") as temporary: + temporary.write(context) + temporary.flush() + result = subprocess.run([ + "shellcheck", "--shell=bash", "--external-sources", "--check-sourced", + "--format=json", temporary.name, *map(str, examples), str(root / "unleash-standalone.sh"), + ], capture_output=True, text=True, check=False) + if result.stderr: + print(result.stderr, file=sys.stderr, end="") + failed |= result.returncode != 0 + findings = json.loads(result.stdout or "[]") + seen = set() + for finding in findings: + path = finding["file"] + if path == temporary.name: + path = str(entrypoint) + key = (path, finding["line"], finding["column"], finding["code"]) + if key in seen: + continue + seen.add(key) + print(f"{path}:{finding['line']}:{finding['column']}: " + f"{finding['level']} SC{finding['code']}: {finding['message']}") +sys.exit(1 if failed else 0) diff --git a/tests/helpers/platform.py b/tests/helpers/platform.py new file mode 100644 index 0000000..77431b4 --- /dev/null +++ b/tests/helpers/platform.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +"""Inert macOS command fixtures; mutable plist operations stay in the suite root.""" +import json +import os +import pathlib +import plistlib +import shlex +import subprocess +import sys + +name = pathlib.Path(sys.argv[0]).name +args = sys.argv[1:] +root = pathlib.Path(os.environ["UNLEASH_TEST_ROOT"]).resolve() +with (root / "platform-calls.jsonl").open("a") as log: + log.write(json.dumps([name, *args]) + "\n") + +def fixture_path(value): + path = pathlib.Path(value).resolve() + if not path.is_relative_to(root): + sys.exit(f"Fixture refused path outside the suite: {path}") + return path + +if name == "sudo": + if len(args) >= 2 and ((args[0] == "profiles" and args[1] in ("-C", "status")) + or (args[0] == "security" and args[1] == "find-identity")): + sys.exit(subprocess.call([str(pathlib.Path(sys.argv[0]).with_name(args[0])), *args[1:]])) +elif name == "profiles": + if args[:1] == ["-C"]: + sys.stdout.buffer.write(plistlib.dumps([])) + sys.exit(0) + if args[:1] == ["status"]: + print("MDM enrollment: No") + sys.exit(0) +elif name == "security" and args[:1] == ["find-identity"]: + sys.exit(0) +elif name == "plutil" and args[:4] == ["-convert", "xml1", "-o", "-"]: + sys.stdout.buffer.write(plistlib.dumps(plistlib.loads(fixture_path(args[-1]).read_bytes()))) + sys.exit(0) +elif name == "PlistBuddy": + path = fixture_path(args[-1]) + data = plistlib.loads(path.read_bytes()) + command = shlex.split(args[1]) + action = command[0] + key = command[1].lstrip(":") if len(command) > 1 else None + if action == "Print": + if key: + print(str(data[key]).lower()) + else: + sys.stdout.buffer.write(plistlib.dumps(data)) + sys.exit(0) + if action == "Add" and key in data: + sys.exit(1) + if action == "Set" and key not in data: + sys.exit(1) + if action in ("Add", "Set"): + data[key] = command[-1] == "true" + elif action == "Delete": + data.pop(key, None) + else: + sys.exit(97) + path.write_bytes(plistlib.dumps(data)) + sys.exit(0) +elif name == "launchctl" and args[:1] in (["load"], ["unload"]): + fixture_path(args[-1]) + sys.exit(0) +elif name == "host" and args[:2] == ["-t", "a"]: + print(f"{args[2]} has address 203.0.113.10") + sys.exit(0) +elif name == "dscl": + fixture_path(args[1]) + sys.exit(1) +elif name in ("diskutil", "pgrep", "pkill", "curl", "pfctl", "host"): + sys.exit(1) + +print(f"Blocked platform operation in test: {name} {' '.join(args)}", file=sys.stderr) +sys.exit(97) diff --git a/tests/setup_suite.bash b/tests/setup_suite.bash new file mode 100644 index 0000000..67a56b5 --- /dev/null +++ b/tests/setup_suite.bash @@ -0,0 +1,20 @@ +setup_suite() { + local suite_dir + suite_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + export UNLEASH_TEST_ROOT="$BATS_SUITE_TMPDIR" + export TMPDIR="$UNLEASH_TEST_ROOT/tmp" + local mock_bin="$UNLEASH_TEST_ROOT/bin" + mkdir -p "$TMPDIR" "$mock_bin" + local tool + for tool in sudo diskutil profiles security launchctl pfctl pkill pgrep killall \ + dscacheutil defaults curl host plutil PlistBuddy dscl fdesetup chflags \ + osascript ioreg ifconfig systemextensionsctl networksetup; do + cp "$suite_dir/helpers/platform.py" "$mock_bin/$tool" + chmod +x "$mock_bin/$tool" + done + export PATH="$mock_bin:$PATH" + export PB="$mock_bin/PlistBuddy" + export VERSION=2.0.0 + export SCRIPT_DIR="$suite_dir/.." + export LIB_DIR="$SCRIPT_DIR/lib" +} diff --git a/tests/test_colors.bats b/tests/test_colors.bats index 424b12f..10b6113 100644 --- a/tests/test_colors.bats +++ b/tests/test_colors.bats @@ -39,3 +39,10 @@ teardown() { [ "$status" -eq 0 ] echo "$output" | grep -q "Test Title" } + +@test "header draws a valid Unicode border for the title width" { + run header Mac + [ "$status" -eq 0 ] + [[ "$output" == *"╔═══════╗"* ]] + [[ "$output" == *"╚═══════╝"* ]] +} diff --git a/tests/test_config.bats b/tests/test_config.bats index e4c60a9..8019477 100644 --- a/tests/test_config.bats +++ b/tests/test_config.bats @@ -35,3 +35,22 @@ teardown() { run grep -c "KEY=new" "$CONFIG_FILE" [ "$output" -eq 1 ] } + +@test "config preserves spaces and literal replacement characters" { + local value='/tmp/Unleash logs/quoted "name" & \tail' + save_config LOG_FILE old + save_config LOG_FILE "$value" + LOG_FILE='' + load_config + [ "$LOG_FILE" = "$value" ] +} + +@test "config unset preserves other keys" { + save_config WEBHOOK 'https://example.com/a?x=1&y=2' + save_config LOG_LEVEL verbose + run cmd_config config unset LOG_LEVEL + [ "$status" -eq 0 ] + run grep -c '^LOG_LEVEL=' "$CONFIG_FILE" + [ "$status" -eq 1 ] + grep -q '^WEBHOOK=https://example.com/a?x=1&y=2$' "$CONFIG_FILE" +} diff --git a/tests/test_detect.bats b/tests/test_detect.bats index bc20503..11bad39 100644 --- a/tests/test_detect.bats +++ b/tests/test_detect.bats @@ -5,14 +5,11 @@ setup() { load '../lib/detect.sh' } -@test "is_root returns true when EUID is 0" { - [ "$EUID" -eq 0 ] && skip "Already root" - [ "$EUID" -ne 0 ] && skip "Not root" -} - -@test "is_root returns false when EUID is not 0" { - [ "$EUID" -ne 0 ] && skip "Not root (expected)" - [ "$EUID" -eq 0 ] && skip "Is root" +@test "is_root reports whether the effective user is root" { + local expected=1 + [ "$EUID" -ne 0 ] || expected=0 + run is_root + [ "$status" -eq "$expected" ] } @test "is_recovery returns false in normal environment" { @@ -26,6 +23,9 @@ setup() { } @test "resolve_data_volume errors on non-existent device" { - run resolve_data_volume 2>/dev/null || true - [ "$status" -eq 0 ] + read() { echo PROMPT_WAS_REACHED; return 1; } + run resolve_data_volume /dev/null || true + mkdir -p "$BATS_TEST_TMPDIR/Users/test/Library/LaunchAgents" + local agents="$BATS_TEST_TMPDIR/Users/test/Library/LaunchAgents" + echo mdm > "$agents/enrollment.plist" + echo normal > "$agents/normal.plist" + run harden_live_os "$BATS_TEST_TMPDIR" [ "$status" -eq 0 ] + [ ! -f "$agents/enrollment.plist" ] + [ -f "$agents/normal.plist" ] } @test "harden_status exits cleanly" { diff --git a/tests/test_history.bats b/tests/test_history.bats index e4aec19..e6b97ec 100644 --- a/tests/test_history.bats +++ b/tests/test_history.bats @@ -6,11 +6,13 @@ setup() { } @test "show_history exits cleanly with no logs" { - run show_history 2>/dev/null || true + run show_history "$BATS_TEST_TMPDIR" [ "$status" -eq 0 ] } @test "clear_history does not error with no logs" { - run clear_history 2>/dev/null || true + echo event > "$BATS_TEST_TMPDIR/unleash-monitor.log" + run clear_history "$BATS_TEST_TMPDIR" [ "$status" -eq 0 ] + [ ! -s "$BATS_TEST_TMPDIR/unleash-monitor.log" ] } diff --git a/tests/test_lint.bats b/tests/test_lint.bats new file mode 100644 index 0000000..9c0a66f --- /dev/null +++ b/tests/test_lint.bats @@ -0,0 +1,48 @@ +#!/usr/bin/env bats + +setup() { + PROJECT="$BATS_TEST_TMPDIR/project" + mkdir -p "$PROJECT/scripts" "$PROJECT/lib" + cp "$BATS_TEST_DIRNAME/../scripts/check-shell.py" "$PROJECT/scripts/" + cat > "$PROJECT/unleash" <<'SH' +#!/bin/bash +for _lib in sample; do + source "lib/$_lib.sh" +done +sample +SH + printf 'sample() { :; }\n' > "$PROJECT/lib/sample.sh" + printf '#!/bin/bash\n' > "$PROJECT/unleash-standalone.sh" +} + +@test "lint reports sourced module findings without executing the application" { + export LINT_TEST_MARKER="$BATS_TEST_TMPDIR/app-executed" + printf 'sample() { echo $missing; }\n: > "$LINT_TEST_MARKER"\n' > "$PROJECT/lib/sample.sh" + run python3 "$PROJECT/scripts/check-shell.py" + [ "$status" -ne 0 ] + [[ "$output" == *"lib/sample.sh:1:"* ]] + [[ "$output" == *"SC2086"* ]] + [ ! -f "$LINT_TEST_MARKER" ] +} + +@test "lint checks syntax in every library" { + printf 'sample() {\n' > "$PROJECT/lib/sample.sh" + run python3 "$PROJECT/scripts/check-shell.py" + [ "$status" -ne 0 ] + [[ "$output" == *"sample.sh"* ]] +} + +@test "lint does not install tools after an analysis failure" { + cp "$BATS_TEST_DIRNAME/../Makefile" "$PROJECT/Makefile" + local mock_bin="$BATS_TEST_TMPDIR/lint-bin" + mkdir -p "$mock_bin" + ln -s "$(command -v python3)" "$mock_bin/python3" + ln -s "$(command -v bash)" "$mock_bin/bash" + printf '#!/bin/sh\nprintf "[]"\nexit 1\n' > "$mock_bin/shellcheck" + export TEST_BREW_MARKER="$BATS_TEST_TMPDIR/brew-called" + printf '#!/bin/sh\n: > "$TEST_BREW_MARKER"\n' > "$mock_bin/brew" + chmod +x "$mock_bin/shellcheck" "$mock_bin/brew" + run env PATH="$mock_bin" "$(command -v make)" -C "$PROJECT" lint + [ "$status" -ne 0 ] + [ ! -f "$TEST_BREW_MARKER" ] +} diff --git a/tests/test_ma_detect.bats b/tests/test_ma_detect.bats index 1f2a9d0..644641c 100644 --- a/tests/test_ma_detect.bats +++ b/tests/test_ma_detect.bats @@ -3,14 +3,26 @@ setup() { load '../lib/colors.sh' load '../lib/ma_detect.sh' + mkdir -p "$BATS_TEST_TMPDIR/Users" } @test "detect_migration_assistant exits cleanly" { - run detect_migration_assistant 2>/dev/null || true + run detect_migration_assistant "$BATS_TEST_TMPDIR" [ "$status" -eq 0 ] } @test "clean_ma_artifacts does not error without users" { - run clean_ma_artifacts 2>/dev/null || true + run clean_ma_artifacts "$BATS_TEST_TMPDIR" [ "$status" -eq 0 ] } + +@test "migration audit detects enrollment and MDM cache directories" { + local caches="$BATS_TEST_TMPDIR/Users/test/Library/Caches" + mkdir -p "$caches/com.apple.enrollmenttool" "$caches/com.apple.mdm" + echo cached > "$caches/com.apple.enrollmenttool/record" + echo cached > "$caches/com.apple.mdm/record" + run detect_migration_assistant "$BATS_TEST_TMPDIR" + [ "$status" -eq 1 ] + [[ "$output" == *"enrollment cache files"* ]] + [[ "$output" == *"MDM cache files"* ]] +} diff --git a/tests/test_monitor.bats b/tests/test_monitor.bats index 60765e7..e23e640 100644 --- a/tests/test_monitor.bats +++ b/tests/test_monitor.bats @@ -11,12 +11,12 @@ teardown() { } @test "monitor_status exits cleanly when not running" { - run monitor_status 2>/dev/null || true + run monitor_status "$TEST_DIR/monitor.pid" [ "$status" -eq 0 ] } @test "stop_monitor exits cleanly when not running" { - run stop_monitor 2>/dev/null || true + run stop_monitor "$TEST_DIR/monitor.pid" [ "$status" -eq 0 ] } diff --git a/tests/test_status.bats b/tests/test_status.bats index aad8478..c258622 100644 --- a/tests/test_status.bats +++ b/tests/test_status.bats @@ -26,3 +26,16 @@ teardown() { run deep_status_json 2>/dev/null || true echo "$output" | grep -q "}" } + +@test "deep_status_json counts a single matching process without subtracting it" { + profiles() { + if [ "$1" = -C ]; then echo 'ProfileDisplayName'; + else echo 'MDM enrollment: No'; fi + } + sudo() { "$@"; } + pgrep() { echo '42 mdmclient'; } + ps() { echo 'test 42 0.0 0.0 1 1 ? S 00:00 0:00 mdmclient'; } + run deep_status_json + [ "$status" -eq 0 ] + echo "$output" | python3 -c 'import json,sys; assert json.load(sys.stdin)["running_mdm_processes"] == 1' +} diff --git a/tests/test_suppress.bats b/tests/test_suppress.bats index 300a1cd..fabc512 100644 --- a/tests/test_suppress.bats +++ b/tests/test_suppress.bats @@ -38,10 +38,16 @@ teardown() { suppress_enrollment "$TEST_DIR" 2>/dev/null || true local ldp="$TEST_DIR/private/var/db/com.apple.xpc.launchd/disabled.plist" [ -f "$ldp" ] - run /usr/libexec/PlistBuddy -c "Print :com.apple.ManagedClient.enroll" "$ldp" 2>/dev/null + run "$PB" -c "Print :com.apple.ManagedClient.enroll" "$ldp" [ "$output" = "true" ] } +@test "PlistBuddy fixture rejects writes outside the test suite" { + run "$PB" -c 'Add :test bool true' "$BATS_TEST_DIRNAME/../README.md" + [ "$status" -ne 0 ] + [[ "$output" == *"Fixture refused path outside the suite"* ]] +} + @test "dry-run mode does not write files" { DRY_RUN=true suppress_enrollment "$TEST_DIR" 2>/dev/null || true diff --git a/unleash b/unleash index 973ec3b..3739e7c 100755 --- a/unleash +++ b/unleash @@ -222,6 +222,7 @@ cmd_dualboot() { echo "" step "Creating admin account on target" + local realName prompt_default realName "Full name" "Apple" local username prompt_username username @@ -236,9 +237,7 @@ cmd_dualboot() { begin "Blocking domains" local hosts_file="$data_path/private/etc/hosts" [ -f "$hosts_file" ] || touch "$hosts_file" - echo "0.0.0.0 deviceenrollment.apple.com" >>"$hosts_file" - echo "0.0.0.0 mdmenrollment.apple.com" >>"$hosts_file" - echo "0.0.0.0 iprofiles.apple.com" >>"$hosts_file" + printf '%s\n' "0.0.0.0 deviceenrollment.apple.com" "0.0.0.0 mdmenrollment.apple.com" "0.0.0.0 iprofiles.apple.com" >>"$hosts_file" end_ok begin "Resetting config profiles" diff --git a/unleash-standalone.sh b/unleash-standalone.sh index 347311c..676a00a 100755 --- a/unleash-standalone.sh +++ b/unleash-standalone.sh @@ -71,7 +71,8 @@ header() { local title="$1" local len="${#title}" local line - line=$(printf '%*s' "$((len + 4))" | tr ' ' '═') + line=$(printf '%*s' "$((len + 4))" '') + line="${line// /═}" echo "" echo -e "${CYAN}╔${line}╗${NC}" echo -e "${CYAN}║ ${title} ║${NC}" @@ -110,7 +111,7 @@ prompt_default() { local prompt_text="$2" local default="$3" local value - read -p "${CYAN}${prompt_text}${NC} (default '${default}'): " value + read -r -p "${CYAN}${prompt_text}${NC} (default '${default}'): " value value="${value:=$default}" eval "$var_name=\"$value\"" } @@ -118,7 +119,7 @@ prompt_default() { confirm() { local prompt="$1" local response - read -p "${prompt} (y/N): " response + read -r -p "${prompt} (y/N): " response [[ "$response" =~ ^[Yy]$ ]] } @@ -126,10 +127,9 @@ CONFIG_FILE="$HOME/.unleash.conf" load_config() { [ -f "$CONFIG_FILE" ] || return 0 - - while IFS='=' read -r key value; do + local key value + while IFS='=' read -r key value || [ -n "$key" ]; do key="${key// /}" - value="${value// /}" [ -z "$key" ] && continue case "$key" in WEBHOOK) DISCORD_WEBHOOK="$value" ;; @@ -139,18 +139,29 @@ load_config() { done < "$CONFIG_FILE" } -save_config() { +_rewrite_config() { local key="$1" local value="$2" local tmp - [ -f "$CONFIG_FILE" ] || touch "$CONFIG_FILE" - - if grep -q "^${key}=" "$CONFIG_FILE" 2>/dev/null; then - sed -i '' "s/^${key}=.*/${key}=${value}/" "$CONFIG_FILE" - else - echo "${key}=${value}" >> "$CONFIG_FILE" + tmp=$(mktemp "${CONFIG_FILE}.XXXXXX") || return 1 + if ! UNLEASH_CONFIG_KEY="$key" UNLEASH_CONFIG_VALUE="$value" \ + UNLEASH_CONFIG_OPERATION="${3:-set}" awk ' + BEGIN { key=ENVIRON["UNLEASH_CONFIG_KEY"]; value=ENVIRON["UNLEASH_CONFIG_VALUE"]; + operation=ENVIRON["UNLEASH_CONFIG_OPERATION"] } + index($0, key "=")==1 { if (!found++ && operation=="set") print key "=" value; next } + { print } + END { if (!found && operation=="set") print key "=" value } + ' "$CONFIG_FILE" > "$tmp"; then + rm -f "$tmp" + return 1 fi + mv "$tmp" "$CONFIG_FILE" +} + +save_config() { + local key="$1" value="$2" + _rewrite_config "$key" "$value" || return 1 success "Saved $key to $CONFIG_FILE" } @@ -180,7 +191,7 @@ cmd_config() { local key="$3" [ -z "$key" ] && { info "Usage: ./unleash config unset KEY"; return 1; } if [ -f "$CONFIG_FILE" ]; then - sed -i '' "/^${key}=/d" "$CONFIG_FILE" + _rewrite_config "$key" "" unset || return 1 success "Removed $key from config" fi ;; @@ -224,7 +235,8 @@ resolve_data_volume() { warn "Auto-detection failed. Available disks:" diskutil list >&2 echo "" - read -p "Enter Data volume identifier (e.g. disk3s1): " id /dev/null | grep -iE "mdm|enrollment|managed" || true) + user_agents=$(_mdm_agent_names "$home/Library/LaunchAgents") if [ -n "$user_agents" ]; then echo -e " ${YEL}$(basename "$home"):${NC}" - echo "$user_agents" | sed 's/^/ /' + while IFS= read -r agent; do printf ' %s\n' "$agent"; done <<< "$user_agents" found=$((found + 1)) fi done @@ -832,9 +855,9 @@ deep_status() { step "MDM LaunchDaemons (System)" local sys_agents - sys_agents=$(ls /Library/LaunchDaemons/ 2>/dev/null | grep -iE "mdm|enrollment|managed" || true) + sys_agents=$(_mdm_agent_names /Library/LaunchDaemons) if [ -n "$sys_agents" ]; then - echo "$sys_agents" | sed 's/^/ /' + while IFS= read -r agent; do printf ' %s\n' "$agent"; done <<< "$sys_agents" else info "No MDM LaunchDaemons found" fi @@ -842,9 +865,9 @@ deep_status() { step "Running MDM Processes" local procs - procs=$(ps aux 2>/dev/null | grep -iE "mdm|managedclient|activation" | grep -v grep || true) + procs=$(pgrep -il "mdm|managedclient|activation" 2>/dev/null || true) if [ -n "$procs" ]; then - echo "$procs" | awk '{print " " $11 " (PID " $2 ")"}' + echo "$procs" | awk '{print " " $2 " (PID " $1 ")"}' else info "No MDM processes running" fi @@ -867,7 +890,7 @@ deep_status() { step "Overall Assessment" local risk="LOW" [ "$(sudo profiles -C -output=xml 2>/dev/null | grep -c "ProfileDisplayName" || echo 0)" -gt 0 ] && risk="MEDIUM" - ps aux 2>/dev/null | grep -qiE "mdm|managedclient" && risk="HIGH" + pgrep -i "mdm|managedclient" >/dev/null 2>&1 && risk="HIGH" [ -f "$cfg/.cloudConfigRecordFound" ] && risk="CRITICAL" case "$risk" in @@ -904,9 +927,7 @@ deep_status_json() { json="${json} \"mdm_certificates\": $mdm_certs,\n" local running_procs=0 - running_procs=$(ps aux 2>/dev/null | grep -ciE "mdm|managedclient|activation" || true) - running_procs=$((running_procs - 1)) - [ "$running_procs" -lt 0 ] && running_procs=0 + running_procs=$(pgrep -il "mdm|managedclient|activation" 2>/dev/null | awk 'END {print NR}' || true) json="${json} \"running_mdm_processes\": $running_procs,\n" local risk="LOW" @@ -1038,9 +1059,11 @@ install_persist_launchdaemon() { step "Loading LaunchDaemon..." if command -v launchctl &>/dev/null; then - launchctl load "$plist_path" 2>/dev/null \ - && success "LaunchDaemon loaded (will run on next boot)" \ - || info "LaunchDaemon will load on next boot" + if launchctl load "$plist_path" 2>/dev/null; then + success "LaunchDaemon loaded (will run on next boot)" + else + info "LaunchDaemon will load on next boot" + fi else info "launchctl not available (expected in Recovery) — will load on next boot" fi @@ -1073,7 +1096,8 @@ pf_backup_anchor() { local root="$1" local anchor_file="${root}${FIREWALL_ANCHOR_DIR}/${FIREWALL_ANCHOR}" [ ! -f "$anchor_file" ] && return 0 - local backup="${anchor_file}.backup.$(date +%s)" + local backup + backup="${anchor_file}.backup.$(date +%s)" cp "$anchor_file" "$backup" && info "Backed up pf anchor: $backup" } @@ -1081,7 +1105,8 @@ pf_backup_conf() { local root="$1" local pf_conf="${root}${FIREWALL_CONF}" [ ! -f "$pf_conf" ] && return 0 - local backup="${pf_conf}.backup.$(date +%s)" + local backup + backup="${pf_conf}.backup.$(date +%s)" cp "$pf_conf" "$backup" && info "Backed up pf.conf: $backup" } @@ -1117,10 +1142,7 @@ ANCHOR if grep -q "com.unleash" "$pf_conf" 2>/dev/null; then info "pf.conf already has Unleash anchor" else - echo "" >> "$pf_conf" - echo "# Added by unleash — MDM block" >> "$pf_conf" - echo "$anchor_line" >> "$pf_conf" - echo "$load_line" >> "$pf_conf" + printf '\n%s\n%s\n%s\n' "# Added by unleash — MDM block" "$anchor_line" "$load_line" >> "$pf_conf" success "pf.conf updated" fi else @@ -1145,8 +1167,11 @@ ANCHOR step "Loading pf rules..." if command -v pfctl &>/dev/null; then - pfctl -e -f "$pf_conf" 2>/dev/null && success "pf enabled and rules loaded" \ - || warn "pfctl failed — try: sudo pfctl -e -f $pf_conf" + if pfctl -e -f "$pf_conf" 2>/dev/null; then + success "pf enabled and rules loaded" + else + warn "pfctl failed — try: sudo pfctl -e -f $pf_conf" + fi else warn "pfctl not available" fi @@ -1171,8 +1196,14 @@ remove_pf_mdm_block() { local pf_conf="${root}${FIREWALL_CONF}" if [ -f "$pf_conf" ]; then - sed -i '' '/# Added by unleash/d' "$pf_conf" 2>/dev/null || true - sed -i '' '/com\.unleash/d' "$pf_conf" 2>/dev/null || true + local tmp_conf + tmp_conf=$(mktemp "${pf_conf}.XXXXXX") || return 1 + if ! cp -p "$pf_conf" "$tmp_conf" \ + || ! sed '/# Added by unleash/d; /com\.unleash/d' "$pf_conf" > "$tmp_conf" \ + || ! mv "$tmp_conf" "$pf_conf"; then + rm -f "$tmp_conf" + return 1 + fi success "pf.conf cleaned" fi @@ -1190,9 +1221,11 @@ pf_status() { if command -v pfctl &>/dev/null; then pfctl -si 2>/dev/null | grep -E "Status|Enabled" || echo " pf not enabled" echo "" - pfctl -a "$FIREWALL_ANCHOR" -s rules 2>/dev/null \ - && info "Unleash MDM anchor rules:" \ - || info "No Unleash MDM anchor loaded" + if pfctl -a "$FIREWALL_ANCHOR" -s rules 2>/dev/null; then + info "Unleash MDM anchor rules:" + else + info "No Unleash MDM anchor loaded" + fi else warn "pfctl not available" fi @@ -1214,8 +1247,11 @@ harden_live_os() { local installed installed=$(profiles -C -output=xml 2>/dev/null | grep -c "ProfileDisplayName" || true) if [ "$installed" -gt 0 ]; then - sudo profiles -D -F 2>/dev/null && success "Forced profile removal" \ - || warn "Profile removal failed" + if sudo profiles -D -F 2>/dev/null; then + success "Forced profile removal" + else + warn "Profile removal failed" + fi else info "No installed profiles to remove" fi @@ -1224,8 +1260,8 @@ harden_live_os() { fi step "Cleaning user LaunchAgents..." - local home - for home in /Users/*/; do + local home users_root="${1:-}/Users" + for home in "$users_root/"*/; do [ -d "$home/Library/LaunchAgents" ] || continue local cleaned=0 for agent in "$home/Library/LaunchAgents/"*; do @@ -1235,8 +1271,11 @@ harden_live_os() { cleaned=$((cleaned + 1)) fi done - [ "$cleaned" -gt 0 ] && success "$(basename "$home"): removed $cleaned agent(s)" \ - || info "$(basename "$home"): clean" + if [ "$cleaned" -gt 0 ]; then + success "$(basename "$home"): removed $cleaned agent(s)" + else + info "$(basename "$home"): clean" + fi done step "Flushing DNS cache..." @@ -1270,9 +1309,11 @@ harden_live_os() { step "Disabling iCloud Private Relay (DoH source)..." if command -v defaults &>/dev/null; then - sudo defaults write /Library/Preferences/com.apple.networkextensions.plist PrivateRelayEnabled -bool false 2>/dev/null \ - && success "Private Relay disabled" \ - || info "Private Relay not configurable (expected on some configs)" + if sudo defaults write /Library/Preferences/com.apple.networkextensions.plist PrivateRelayEnabled -bool false 2>/dev/null; then + success "Private Relay disabled" + else + info "Private Relay not configurable (expected on some configs)" + fi fi echo "" @@ -1296,7 +1337,7 @@ harden_status() { launchctl list 2>/dev/null | grep -iE "mdm|managed|enrollment|activation" || info "None loaded" step "Running MDM processes..." - ps aux 2>/dev/null | grep -iE "mdm|managedclient|activation" | grep -v grep || info "None running" + pgrep -il "mdm|managedclient|activation" 2>/dev/null || info "None running" } MDM_BLOCKLIST="mdmenrollment.apple.com deviceenrollment.apple.com iprofiles.apple.com" @@ -1312,7 +1353,7 @@ install_selective_block() { local anchor_file="${anchor_dir}/com.unleash.selective" mkdir -p "$anchor_dir" - > "$anchor_file" + : > "$anchor_file" for d in $MDM_BLOCKLIST; do for ip in $(host -t a "$d" 2>/dev/null | awk '/has address/{print $NF}'); do @@ -1334,10 +1375,7 @@ install_selective_block() { if grep -q "com.unleash.selective" "$pf_conf" 2>/dev/null; then info "pf.conf already has selective anchor" else - echo "" >> "$pf_conf" - echo "# Added by unleash — selective MDM block (iCloud-safe)" >> "$pf_conf" - echo "$anchor_line" >> "$pf_conf" - echo "$load_line" >> "$pf_conf" + printf '\n%s\n%s\n%s\n' "# Added by unleash — selective MDM block (iCloud-safe)" "$anchor_line" "$load_line" >> "$pf_conf" success "pf.conf updated with selective rules" fi else @@ -1357,8 +1395,11 @@ EOF fi if command -v pfctl &>/dev/null; then - pfctl -e -f "$pf_conf" 2>/dev/null && success "pf rules loaded (iCloud should work)" \ - || warn "pfctl failed" + if pfctl -e -f "$pf_conf" 2>/dev/null; then + success "pf rules loaded (iCloud should work)" + else + warn "pfctl failed" + fi fi } @@ -1548,9 +1589,11 @@ PLIST success "Monitor LaunchDaemon: $plist_path" if command -v launchctl &>/dev/null; then - launchctl load "$plist_path" 2>/dev/null \ - && success "Monitor loaded (starts at boot)" \ - || info "Will load on next boot" + if launchctl load "$plist_path" 2>/dev/null; then + success "Monitor loaded (starts at boot)" + else + info "Will load on next boot" + fi fi } @@ -1671,7 +1714,7 @@ monitor_mdm() { } stop_monitor() { - local pidfile="/tmp/unleash-monitor.pid" + local pidfile="${1:-/tmp/unleash-monitor.pid}" if [ -f "$pidfile" ]; then local pid pid=$(cat "$pidfile") @@ -1688,7 +1731,7 @@ stop_monitor() { } monitor_status() { - local pidfile="/tmp/unleash-monitor.pid" + local pidfile="${1:-/tmp/unleash-monitor.pid}" if [ -f "$pidfile" ] && kill -0 "$(cat "$pidfile")" 2>/dev/null; then echo -e "${GRN}Monitor running (PID $(cat "$pidfile"))${NC}" tail -5 /var/log/unleash-monitor.log 2>/dev/null || echo " (no log entries yet)" @@ -1700,7 +1743,8 @@ monitor_status() { show_history() { header "Unleash Event History" - local logs=("/var/log/unleash-monitor.log" "/var/log/unleash-heal.log" "/var/log/unleash-monitor.err") + local log_dir="${1:-/var/log}" + local logs=("$log_dir/unleash-monitor.log" "$log_dir/unleash-heal.log" "$log_dir/unleash-monitor.err") local found=false for logfile in "${logs[@]}"; do @@ -1733,7 +1777,8 @@ show_history() { } clear_history() { - local logs=("/var/log/unleash-monitor.log" "/var/log/unleash-heal.log" "/var/log/unleash-monitor.err") + local log_dir="${1:-/var/log}" + local logs=("$log_dir/unleash-monitor.log" "$log_dir/unleash-heal.log" "$log_dir/unleash-monitor.err") for logfile in "${logs[@]}"; do if [ -f "$logfile" ]; then : > "$logfile" @@ -1926,7 +1971,7 @@ do_self_update() { fi end_ok; echo " Latest: v$latest_tag" - if [ "v$latest_tag" = "$(echo "v$VERSION")" ]; then + if [ "v$latest_tag" = "v$VERSION" ]; then success "Already up to date (v$VERSION)" rm -rf "$tmp_dir" return 0 @@ -2166,9 +2211,9 @@ generate_report() { step "Running MDM Processes" local procs - procs=$(ps aux 2>/dev/null | grep -iE "mdm|managedclient|activation" | grep -v grep || true) + procs=$(pgrep -il "mdm|managedclient|activation" 2>/dev/null || true) if [ -n "$procs" ]; then - echo "$procs" | awk '{print " " $11 " (PID " $2 ")"}' + echo "$procs" | awk '{print " " $2 " (PID " $1 ")"}' else echo " None" fi @@ -2234,6 +2279,14 @@ generate_report_json() { echo -e "$report" } +_has_matching_path() { + local path + for path in "$@"; do + [ ! -e "$path" ] || return 0 + done + return 1 +} + detect_configurator_enrollment() { local data_mount="${1:-}" @@ -2316,8 +2369,13 @@ detect_migration_assistant() { local user_agents="$home/Library/LaunchAgents" if [ -d "$user_agents" ]; then - local found - found=$(ls "$user_agents" 2>/dev/null | grep -ciE "mdm|enrollment|managed" || true) + local found=0 agent + for agent in "$user_agents/"*; do + [ -f "$agent" ] || continue + if printf '%s\n' "${agent##*/}" | grep -qiE 'mdm|enrollment|managed'; then + found=$((found + 1)) + fi + done if [ "$found" -gt 0 ]; then ma_indicators=$((ma_indicators + found)) details="$details $user: $found MDM LaunchAgent(s)\n" @@ -2326,9 +2384,7 @@ detect_migration_assistant() { local prefs="$home/Library/Preferences" if [ -d "$prefs" ]; then - local mdm_prefs - mdm_prefs=$(ls "$prefs"/com.apple.mdm* "$prefs"/com.apple.ManagedClient* 2>/dev/null | head -3 || true) - if [ -n "$mdm_prefs" ]; then + if _has_matching_path "$prefs"/com.apple.mdm* "$prefs"/com.apple.ManagedClient*; then ma_indicators=$((ma_indicators + 1)) details="$details $user: MDM preference files\n" fi @@ -2342,16 +2398,12 @@ detect_migration_assistant() { local caches="$home/Library/Caches" if [ -d "$caches" ]; then - local enrollment_cache - enrollment_cache=$(ls "$caches"/com.apple.enrollment* 2>/dev/null | head -3 || true) - if [ -n "$enrollment_cache" ]; then + if _has_matching_path "$caches"/com.apple.enrollment*; then ma_indicators=$((ma_indicators + 1)) details="$details $user: enrollment cache files\n" fi - local mdmd_cache - mdmd_cache=$(ls "$caches"/com.apple.mdm* 2>/dev/null | head -3 || true) - if [ -n "$mdmd_cache" ]; then + if _has_matching_path "$caches"/com.apple.mdm*; then ma_indicators=$((ma_indicators + 1)) details="$details $user: MDM cache files\n" fi @@ -2549,14 +2601,14 @@ RULES if grep -q "vpn-kill" "$pf_conf" 2>/dev/null; then info "pf.conf already has VPN kill-switch anchor" else - echo "" >> "$pf_conf" - echo "# Added by unleash — VPN kill-switch (prevents MDM leaks)" >> "$pf_conf" - echo "$anchor_line" >> "$pf_conf" - echo "$load_line" >> "$pf_conf" + printf '\n%s\n%s\n%s\n' "# Added by unleash — VPN kill-switch (prevents MDM leaks)" "$anchor_line" "$load_line" >> "$pf_conf" fi - pfctl -e -f "$pf_conf" 2>/dev/null && success "VPN kill-switch active" \ - || warn "pfctl failed" + if pfctl -e -f "$pf_conf" 2>/dev/null; then + success "VPN kill-switch active" + else + warn "pfctl failed" + fi echo "" info "What this does:" @@ -2814,6 +2866,7 @@ cmd_dualboot() { echo "" step "Creating admin account on target" + local realName prompt_default realName "Full name" "Apple" local username prompt_username username @@ -2828,9 +2881,7 @@ cmd_dualboot() { begin "Blocking domains" local hosts_file="$data_path/private/etc/hosts" [ -f "$hosts_file" ] || touch "$hosts_file" - echo "0.0.0.0 deviceenrollment.apple.com" >>"$hosts_file" - echo "0.0.0.0 mdmenrollment.apple.com" >>"$hosts_file" - echo "0.0.0.0 iprofiles.apple.com" >>"$hosts_file" + printf '%s\n' "0.0.0.0 deviceenrollment.apple.com" "0.0.0.0 mdmenrollment.apple.com" "0.0.0.0 iprofiles.apple.com" >>"$hosts_file" end_ok begin "Resetting config profiles" From 7bc57d860f8dc9d45b9350038e06700ff9a8bc48 Mon Sep 17 00:00:00 2001 From: ruihan Date: Fri, 30 Oct 2026 04:31:12 -0300 Subject: [PATCH 06/17] test(fixtures): allow the active test temporary directory --- tests/helpers/platform.py | 3 ++- tests/test_suppress.bats | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/helpers/platform.py b/tests/helpers/platform.py index 77431b4..24de34f 100644 --- a/tests/helpers/platform.py +++ b/tests/helpers/platform.py @@ -16,7 +16,8 @@ with (root / "platform-calls.jsonl").open("a") as log: def fixture_path(value): path = pathlib.Path(value).resolve() - if not path.is_relative_to(root): + active_test = pathlib.Path(os.environ["BATS_TEST_TMPDIR"]).resolve() + if not (path.is_relative_to(root) or path.is_relative_to(active_test)): sys.exit(f"Fixture refused path outside the suite: {path}") return path diff --git a/tests/test_suppress.bats b/tests/test_suppress.bats index fabc512..9ccbbfe 100644 --- a/tests/test_suppress.bats +++ b/tests/test_suppress.bats @@ -34,6 +34,7 @@ teardown() { } @test "suppress_enrollment disables daemons" { + TEST_DIR="$BATS_TEST_TMPDIR/volume" DRY_RUN=false suppress_enrollment "$TEST_DIR" 2>/dev/null || true local ldp="$TEST_DIR/private/var/db/com.apple.xpc.launchd/disabled.plist" From bc91e4ecd587959148dd3f574f3da48e498680ec Mon Sep 17 00:00:00 2001 From: ruihan Date: Fri, 30 Oct 2026 04:24:42 -0300 Subject: [PATCH 07/17] fix(volumes): keep mount diagnostics out of captured paths --- lib/detect.sh | 6 ++--- tests/test_volume_output.bats | 47 +++++++++++++++++++++++++++++++++++ unleash-standalone.sh | 6 ++--- 3 files changed, 53 insertions(+), 6 deletions(-) create mode 100644 tests/test_volume_output.bats diff --git a/lib/detect.sh b/lib/detect.sh index 21fee6e..7eceb61 100644 --- a/lib/detect.sh +++ b/lib/detect.sh @@ -31,7 +31,7 @@ resolve_data_volume() { if [ -z "$id" ] || ! diskutil info "/dev/$id" >/dev/null 2>&1; then warn "Auto-detection failed. Available disks:" diskutil list >&2 - echo "" + echo "" >&2 [ -t 0 ] || error_exit "Cannot select a Data volume without a terminal." read -r -p "Enter Data volume identifier (e.g. disk3s1): " id /dev/null || true + diskutil mount "$data_dev" >&2 || true mount_pt=$(_mount_point) fi if [ -z "$mount_pt" ] || [ ! -d "$mount_pt" ]; then warn "FileVault-locked — need to unlock." echo -e "${YEL}Enter password of a user on this Mac (or FileVault recovery key):${NC}" >&2 - diskutil apfs unlockVolume "$data_dev" 2>/dev/null \ + diskutil apfs unlockVolume "$data_dev" >&2 \ || error_exit "Failed to unlock. Re-run with valid credentials." mount_pt=$(_mount_point) fi diff --git a/tests/test_volume_output.bats b/tests/test_volume_output.bats new file mode 100644 index 0000000..7bef25f --- /dev/null +++ b/tests/test_volume_output.bats @@ -0,0 +1,47 @@ +#!/usr/bin/env bats + +check_volume_output() { + local mode="$1" entrypoint + bats_require_minimum_version 1.5.0 + for entrypoint in unleash unleash-standalone.sh; do + local script="$BATS_TEST_DIRNAME/../$entrypoint" + local target="$BATS_TEST_TMPDIR/$entrypoint/Data volume" + mkdir -p "$target/private/var/db/dslocal/nodes/Default" + run --separate-stderr bash -u -c ' + source <(sed '\''/^main "\$@"$/d'\'' "$1") + target="$2"; mode="$3"; mounted="$4" + diskutil() { + case "$*" in + "apfs list") echo "+-- Volume disk5s1 (Data)" ;; + "info /dev/disk5s1") + if [ -f "$mounted" ]; then printf "Mount Point: %s\n" "$target"; + else echo "Mount Point: Not mounted"; fi ;; + "mount /dev/disk5s1") + echo "Mount attempt diagnostic" + [ "$mode" != locked ] || return 1 + touch "$mounted" ;; + "apfs unlockVolume /dev/disk5s1") + echo "Unlocking any cryptographic user" + echo "Unlocked and mounted APFS Volume" + touch "$mounted" ;; + *) return 1 ;; + esac + } + resolve_data_volume + ' "$script" "$script" "$target" "$mode" "$BATS_TEST_TMPDIR/$entrypoint.mounted" + [ "$status" -eq 0 ] + [ "$output" = "$target" ] + [[ "$stderr" == *"Mount attempt diagnostic"* ]] + if [ "$mode" = locked ]; then + [[ "$stderr" == *"Unlocked and mounted APFS Volume"* ]] + fi + done +} + +@test "mount diagnostics stay out of the selected Data volume path" { + check_volume_output unmounted +} + +@test "FileVault unlock diagnostics stay out of the selected Data volume path" { + check_volume_output locked +} diff --git a/unleash-standalone.sh b/unleash-standalone.sh index dc2bf9f..04ce5f6 100755 --- a/unleash-standalone.sh +++ b/unleash-standalone.sh @@ -234,7 +234,7 @@ resolve_data_volume() { if [ -z "$id" ] || ! diskutil info "/dev/$id" >/dev/null 2>&1; then warn "Auto-detection failed. Available disks:" diskutil list >&2 - echo "" + echo "" >&2 [ -t 0 ] || error_exit "Cannot select a Data volume without a terminal." read -r -p "Enter Data volume identifier (e.g. disk3s1): " id /dev/null || true + diskutil mount "$data_dev" >&2 || true mount_pt=$(_mount_point) fi if [ -z "$mount_pt" ] || [ ! -d "$mount_pt" ]; then warn "FileVault-locked — need to unlock." echo -e "${YEL}Enter password of a user on this Mac (or FileVault recovery key):${NC}" >&2 - diskutil apfs unlockVolume "$data_dev" 2>/dev/null \ + diskutil apfs unlockVolume "$data_dev" >&2 \ || error_exit "Failed to unlock. Re-run with valid credentials." mount_pt=$(_mount_point) fi From 579ce6cb2e559504ef3b014f423d5e9afacce7c7 Mon Sep 17 00:00:00 2001 From: ruihan Date: Fri, 30 Oct 2026 04:38:57 -0300 Subject: [PATCH 08/17] fix(cli): preserve optional argument boundaries --- lib/config.sh | 6 +- tests/test_argument_safety.bats | 102 ++++++++++++++++++++++++++++++++ unleash | 35 +++++++---- unleash-standalone.sh | 41 ++++++++----- 4 files changed, 152 insertions(+), 32 deletions(-) create mode 100644 tests/test_argument_safety.bats diff --git a/lib/config.sh b/lib/config.sh index bd7a8a2..a67956f 100644 --- a/lib/config.sh +++ b/lib/config.sh @@ -53,8 +53,8 @@ cmd_config() { cat "$CONFIG_FILE" | sed 's/^/ /' ;; set) - local key="$3" - local value="$4" + local key="${3:-}" + local value="${4:-}" [ -z "$key" ] || [ -z "$value" ] && { info "Usage: ./unleash config set KEY VALUE" info "Keys: WEBHOOK, LOG_LEVEL (verbose), LOG_FILE" @@ -63,7 +63,7 @@ cmd_config() { save_config "$key" "$value" ;; unset) - local key="$3" + local key="${3:-}" [ -z "$key" ] && { info "Usage: ./unleash config unset KEY"; return 1; } if [ -f "$CONFIG_FILE" ]; then _rewrite_config "$key" "" unset || return 1 diff --git a/tests/test_argument_safety.bats b/tests/test_argument_safety.bats new file mode 100644 index 0000000..73bf037 --- /dev/null +++ b/tests/test_argument_safety.bats @@ -0,0 +1,102 @@ +#!/usr/bin/env bats + +run_cli() { + local script="$1"; shift + local definitions="$BATS_TEST_TMPDIR/${script##*/}.functions" + sed '/^main "\$@"$/d' "$script" > "$definitions" + run "${UNLEASH_TEST_SHELL:-bash}" -u -c ' + source "$1" + shift + load_config() { :; } + is_root() { return 1; } + is_recovery() { return 1; } + cmd_interactive_normal() { printf "interactive verbose=%s\n" "$VERBOSE"; } + main "$@" + ' "$script" "$definitions" "$@" +} + +run_capture() { + local script="$1"; shift + local definitions="$BATS_TEST_TMPDIR/${script##*/}.functions" + sed '/^main "\$@"$/d' "$script" > "$definitions" + run "${UNLEASH_TEST_SHELL:-bash}" -u -c ' + source "$1" + shift + load_config() { :; } + cmd_config() { + printf "dry=%s verbose=%s log=<%s>\nargc=%s\n" "$DRY_RUN" "$VERBOSE" "$LOG_FILE" "$#" + printf "<%s>\n" "$@" + } + main "$@" + ' "$script" "$definitions" "$@" +} + +@test "optional CLI arguments reach usage or privilege guards under nounset" { + local entrypoint + for entrypoint in unleash unleash-standalone.sh; do + local script="$BATS_TEST_DIRNAME/../$entrypoint" + run_cli "$script" audit + [ "$status" -ne 0 ]; [[ "$output" == *"Audit needs sudo"* ]] + run_cli "$script" --log-file + [ "$status" -ne 0 ]; [[ "$output" == *"--log-file requires a path"* ]] + run_cli "$script" monitor --webhook + [ "$status" -ne 0 ]; [[ "$output" == *"--webhook requires a URL"* ]] + run_cli "$script" config set + [ "$status" -ne 0 ]; [[ "$output" == *"Usage: ./unleash config set KEY VALUE"* ]] + run_cli "$script" config unset + [ "$status" -ne 0 ]; [[ "$output" == *"Usage: ./unleash config unset KEY"* ]] + done +} + +@test "CLI values retain spaces quotes empty strings and literal shell syntax" { + local entrypoint value + for entrypoint in unleash unleash-standalone.sh; do + for value in 'a b $(printf injected) "quoted"' ''; do + run_capture "$BATS_TEST_DIRNAME/../$entrypoint" config set LOG_FILE "$value" + [ "$status" -eq 0 ] + local expected + expected=$(printf 'dry=false verbose=false log=<>\nargc=4\n\n\n\n<%s>' "$value") + [ "$output" = "$expected" ] + done + done +} + +@test "global flags around the command persist in the command shell" { + local entrypoint + for entrypoint in unleash unleash-standalone.sh; do + run_capture "$BATS_TEST_DIRNAME/../$entrypoint" --dry-run config --verbose set LOG_FILE value --log-file 'a b.log' + [ "$status" -eq 0 ] + [[ "$output" == 'dry=true verbose=true log='* ]] + [[ "$output" == *'argc=4'* ]] + done +} + +@test "global flags without a command preserve an empty argument list" { + local entrypoint + for entrypoint in unleash unleash-standalone.sh; do + run_cli "$BATS_TEST_DIRNAME/../$entrypoint" --verbose + [ "$status" -eq 0 ] + [ "$output" = 'interactive verbose=true' ] + done +} + +@test "CLI option terminator preserves values that look like global options" { + local entrypoint + for entrypoint in unleash unleash-standalone.sh; do + run_capture "$BATS_TEST_DIRNAME/../$entrypoint" config set LOG_LEVEL -- --verbose + [ "$status" -eq 0 ] + [[ "$output" == 'dry=false verbose=false log=<>'* ]] + [[ "$output" == *'<--verbose>' ]] + done +} + +@test "log-file rejects an empty path or another option as its missing value" { + local entrypoint value + for entrypoint in unleash unleash-standalone.sh; do + for value in '' --dry-run; do + run_cli "$BATS_TEST_DIRNAME/../$entrypoint" --log-file "$value" version + [ "$status" -ne 0 ] + [[ "$output" == *"--log-file requires a path"* ]] + done + done +} diff --git a/unleash b/unleash index 3739e7c..2c09c35 100755 --- a/unleash +++ b/unleash @@ -371,7 +371,9 @@ cmd_monitor() { while [ $# -gt 0 ]; do case "$1" in install|uninstall) args+=("$1"); shift ;; - --webhook) webhook="$2"; shift 2 ;; + --webhook) + if [ $# -lt 2 ] || [ -z "$2" ]; then error_exit "--webhook requires a URL"; fi + webhook="$2"; shift 2 ;; *) args+=("$1"); shift ;; esac done @@ -531,22 +533,29 @@ cmd_interactive_normal() { } parse_global_opts() { - local args=() + PARSED_ARGS=() while [ $# -gt 0 ]; do case "$1" in --verbose) VERBOSE=true; shift ;; --dry-run) DRY_RUN=true; shift ;; - --log-file) LOG_FILE="$2"; shift 2 ;; - *) args+=("$1"); shift ;; + --log-file) + if [ $# -lt 2 ] || [ -z "$2" ]; then error_exit "--log-file requires a path"; fi + case "$2" in --*) error_exit "--log-file requires a path" ;; esac + LOG_FILE="$2"; shift 2 ;; + --) shift; PARSED_ARGS+=("$@"); break ;; + *) PARSED_ARGS+=("$1"); shift ;; esac done - set -- "${args[@]}" - echo "$@" } main() { load_config - eval "set -- $(parse_global_opts "$@")" + parse_global_opts "$@" + if [ "${PARSED_ARGS[0]+present}" = present ]; then + set -- "${PARSED_ARGS[@]}" + else + set -- + fi # Per-command help if [ "${2:-}" = "--help" ] || [ "${2:-}" = "-h" ]; then @@ -563,7 +572,7 @@ main() { firewall|fw) cmd_firewall ;; firewall-off|fw-off) cmd_firewall_off ;; harden) cmd_harden ;; - audit) cmd_audit "$2" ;; + audit) cmd_audit "${2:-}" ;; whitelist|wl) cmd_whitelist ;; backup) cmd_backup ;; restore) cmd_restore ;; @@ -581,13 +590,13 @@ main() { version|-v|--version) cmd_version ;; init) cmd_init ;; suggest) cmd_suggest ;; - remediate) cmd_remediate "$2" ;; - predict) cmd_predict "$2" ;; - telemetry) telemetry_opt_in "$2" ;; + remediate) cmd_remediate "${2:-}" ;; + predict) cmd_predict "${2:-}" ;; + telemetry) telemetry_opt_in "${2:-}" ;; demo) run_demo ;; update) do_self_update ;; uninstall) do_uninstall ;; - report) generate_report "$2" ;; + report) generate_report "${2:-}" ;; config) cmd_config "$@" ;; vpn-kill) vpn_kill_install "$@" ;; vpn-kill-remove) vpn_kill_remove ;; @@ -599,7 +608,7 @@ main() { install_monitor_launchdaemon "" success "Reinstall complete" ;; - discord-bot) cmd_discord_bot_install "$2" "$3" ;; + discord-bot) cmd_discord_bot_install "${2:-}" "${3:-}" ;; discord-bot-stop) cmd_discord_bot_stop ;; discord-bot-status) cmd_discord_bot_status ;; help|-h|--help) show_help; exit 0 ;; diff --git a/unleash-standalone.sh b/unleash-standalone.sh index 04ce5f6..5a5e151 100755 --- a/unleash-standalone.sh +++ b/unleash-standalone.sh @@ -178,8 +178,8 @@ cmd_config() { cat "$CONFIG_FILE" | sed 's/^/ /' ;; set) - local key="$3" - local value="$4" + local key="${3:-}" + local value="${4:-}" [ -z "$key" ] || [ -z "$value" ] && { info "Usage: ./unleash config set KEY VALUE" info "Keys: WEBHOOK, LOG_LEVEL (verbose), LOG_FILE" @@ -188,7 +188,7 @@ cmd_config() { save_config "$key" "$value" ;; unset) - local key="$3" + local key="${3:-}" [ -z "$key" ] && { info "Usage: ./unleash config unset KEY"; return 1; } if [ -f "$CONFIG_FILE" ]; then _rewrite_config "$key" "" unset || return 1 @@ -3015,7 +3015,9 @@ cmd_monitor() { while [ $# -gt 0 ]; do case "$1" in install|uninstall) args+=("$1"); shift ;; - --webhook) webhook="$2"; shift 2 ;; + --webhook) + if [ $# -lt 2 ] || [ -z "$2" ]; then error_exit "--webhook requires a URL"; fi + webhook="$2"; shift 2 ;; *) args+=("$1"); shift ;; esac done @@ -3175,22 +3177,29 @@ cmd_interactive_normal() { } parse_global_opts() { - local args=() + PARSED_ARGS=() while [ $# -gt 0 ]; do case "$1" in --verbose) VERBOSE=true; shift ;; --dry-run) DRY_RUN=true; shift ;; - --log-file) LOG_FILE="$2"; shift 2 ;; - *) args+=("$1"); shift ;; + --log-file) + if [ $# -lt 2 ] || [ -z "$2" ]; then error_exit "--log-file requires a path"; fi + case "$2" in --*) error_exit "--log-file requires a path" ;; esac + LOG_FILE="$2"; shift 2 ;; + --) shift; PARSED_ARGS+=("$@"); break ;; + *) PARSED_ARGS+=("$1"); shift ;; esac done - set -- "${args[@]}" - echo "$@" } main() { load_config - eval "set -- $(parse_global_opts "$@")" + parse_global_opts "$@" + if [ "${PARSED_ARGS[0]+present}" = present ]; then + set -- "${PARSED_ARGS[@]}" + else + set -- + fi # Per-command help if [ "${2:-}" = "--help" ] || [ "${2:-}" = "-h" ]; then @@ -3207,7 +3216,7 @@ main() { firewall|fw) cmd_firewall ;; firewall-off|fw-off) cmd_firewall_off ;; harden) cmd_harden ;; - audit) cmd_audit "$2" ;; + audit) cmd_audit "${2:-}" ;; whitelist|wl) cmd_whitelist ;; backup) cmd_backup ;; restore) cmd_restore ;; @@ -3225,13 +3234,13 @@ main() { version|-v|--version) cmd_version ;; init) cmd_init ;; suggest) cmd_suggest ;; - remediate) cmd_remediate "$2" ;; - predict) cmd_predict "$2" ;; - telemetry) telemetry_opt_in "$2" ;; + remediate) cmd_remediate "${2:-}" ;; + predict) cmd_predict "${2:-}" ;; + telemetry) telemetry_opt_in "${2:-}" ;; demo) run_demo ;; update) do_self_update ;; uninstall) do_uninstall ;; - report) generate_report "$2" ;; + report) generate_report "${2:-}" ;; config) cmd_config "$@" ;; vpn-kill) vpn_kill_install "$@" ;; vpn-kill-remove) vpn_kill_remove ;; @@ -3243,7 +3252,7 @@ main() { install_monitor_launchdaemon "" success "Reinstall complete" ;; - discord-bot) cmd_discord_bot_install "$2" "$3" ;; + discord-bot) cmd_discord_bot_install "${2:-}" "${3:-}" ;; discord-bot-stop) cmd_discord_bot_stop ;; discord-bot-status) cmd_discord_bot_status ;; help|-h|--help) show_help; exit 0 ;; From f4ff96bfd36bd69108a42f294664a5f8e5abf091 Mon Sep 17 00:00:00 2001 From: ruihan Date: Fri, 30 Oct 2026 04:44:00 -0300 Subject: [PATCH 09/17] fix(persistence): invoke the installed script path literally --- examples/build-standalone.sh | 4 +++- lib/heal.sh | 10 +++------ lib/launchd.sh | 7 +++++++ tests/test_persistence.bats | 39 ++++++++++++++++++++++++++++++++++++ unleash | 3 ++- unleash-standalone.sh | 20 +++++++++++------- 6 files changed, 67 insertions(+), 16 deletions(-) create mode 100644 lib/launchd.sh create mode 100644 tests/test_persistence.bats diff --git a/examples/build-standalone.sh b/examples/build-standalone.sh index c11b6c4..f11ce8e 100755 --- a/examples/build-standalone.sh +++ b/examples/build-standalone.sh @@ -9,9 +9,11 @@ cat > "$OUT" << HEADER #!/bin/bash set -euo pipefail VERSION="$VERSION" +SCRIPT_DIR="\$(cd "\$(dirname "\$0")" && pwd)" +SCRIPT_PATH="\$SCRIPT_DIR/\$(basename "\$0")" HEADER -for lib in colors config detect validate dscl suppress backup status heal firewall harden whitelist check monitor history doctor selfupdate uninstall report ma_detect demo vpn; do +for lib in colors config detect validate dscl suppress backup status launchd heal firewall harden whitelist check monitor history doctor selfupdate uninstall report ma_detect demo vpn; do tail -n +1 "$SCRIPT_DIR/lib/$lib.sh" >> "$OUT" echo "" >> "$OUT" done diff --git a/lib/heal.sh b/lib/heal.sh index 08d5157..cfa8567 100644 --- a/lib/heal.sh +++ b/lib/heal.sh @@ -70,11 +70,7 @@ install_persist_launchdaemon() { root="$(_persist_mount_root "$data_mount")" local unleash_src - if [ -n "$SCRIPT_DIR" ]; then - unleash_src="$SCRIPT_DIR/unleash" - else - unleash_src="$(cd "$(dirname "$0")" && pwd)/unleash" - fi + unleash_src=$(_launchd_script_path) step "Installing LaunchDaemon for boot-time persistence..." @@ -93,8 +89,8 @@ install_persist_launchdaemon() { ProgramArguments /bin/bash - -c - ${unleash_src} heal + ${unleash_src} + heal RunAtLoad diff --git a/lib/launchd.sh b/lib/launchd.sh new file mode 100644 index 0000000..197a44c --- /dev/null +++ b/lib/launchd.sh @@ -0,0 +1,7 @@ +_launchd_script_path() { + local script_path="${SCRIPT_PATH:-}" + if [ -z "$script_path" ]; then + script_path="$(cd "$(dirname "$0")" && pwd)/$(basename "$0")" + fi + printf '%s' "$script_path" | sed 's/&/\&/g; s//\>/g' +} diff --git a/tests/test_persistence.bats b/tests/test_persistence.bats new file mode 100644 index 0000000..31e6706 --- /dev/null +++ b/tests/test_persistence.bats @@ -0,0 +1,39 @@ +#!/usr/bin/env bats + +@test "persistence invokes renamed scripts with spaces and XML text literally" { + local entrypoint + for entrypoint in unleash unleash-standalone.sh; do + local folder="$BATS_TEST_TMPDIR/$entrypoint/Tool Folder & \"quoted\"" + local target="$BATS_TEST_TMPDIR/$entrypoint/Target" + local script="$folder/renamed standalone.sh" + local definitions="$BATS_TEST_TMPDIR/$entrypoint.functions" + mkdir -p "$folder" "$target/Library" + printf '#!/bin/bash\nprintf "ACTION=%%s\\n" "$1"\n' > "$script" + if [ "$entrypoint" = unleash ]; then + ln -s "$BATS_TEST_DIRNAME/../lib" "$folder/lib" + fi + sed '/^main "\$@"$/d' "$BATS_TEST_DIRNAME/../$entrypoint" > "$definitions" + run "${UNLEASH_TEST_SHELL:-bash}" -u -c ' + unset SCRIPT_DIR SCRIPT_PATH + source "$1" + expected="$2/Library/LaunchDaemons" + mkdir() { + [ "$#" -eq 2 ] && [ "$1" = -p ] && [ "$2" = "$expected" ] || return 97 + command mkdir "$@" + } + install_persist_launchdaemon "$2" + ' "$script" "$definitions" "$target" + [ "$status" -eq 0 ] + run python3 - "$target/Library/LaunchDaemons/com.unleash.heal.plist" "$script" <<'PY' +import plistlib,subprocess,sys +with open(sys.argv[1],'rb') as source: + data=plistlib.load(source) +expected=['/bin/bash',sys.argv[2],'heal'] +assert data['ProgramArguments']==expected, data['ProgramArguments'] +result=subprocess.run(expected,capture_output=True,text=True,timeout=5) +assert result.returncode==0, result.stderr +assert result.stdout=='ACTION=heal\n', result.stdout +PY + [ "$status" -eq 0 ] + done +} diff --git a/unleash b/unleash index 2c09c35..93e1d35 100755 --- a/unleash +++ b/unleash @@ -4,9 +4,10 @@ set -euo pipefail VERSION="2.0.0" SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +SCRIPT_PATH="$SCRIPT_DIR/$(basename "$0")" LIB_DIR="$SCRIPT_DIR/lib" -for _lib in colors config detect validate dscl suppress backup status heal firewall harden whitelist check monitor history doctor selfupdate uninstall report ma_detect demo vpn init suggest remediate telemetry predict discord; do +for _lib in colors config detect validate dscl suppress backup status launchd heal firewall harden whitelist check monitor history doctor selfupdate uninstall report ma_detect demo vpn init suggest remediate telemetry predict discord; do _lib_path="$LIB_DIR/$_lib.sh" if [ -f "$_lib_path" ]; then source "$_lib_path" diff --git a/unleash-standalone.sh b/unleash-standalone.sh index 5a5e151..b5a1bde 100755 --- a/unleash-standalone.sh +++ b/unleash-standalone.sh @@ -1,6 +1,8 @@ #!/bin/bash set -euo pipefail VERSION="2.0.0" +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +SCRIPT_PATH="$SCRIPT_DIR/$(basename "$0")" RED='\033[1;31m' GRN='\033[1;32m' BLU='\033[1;34m' @@ -940,6 +942,14 @@ deep_status_json() { echo -e "$json" } +_launchd_script_path() { + local script_path="${SCRIPT_PATH:-}" + if [ -z "$script_path" ]; then + script_path="$(cd "$(dirname "$0")" && pwd)/$(basename "$0")" + fi + printf '%s' "$script_path" | sed 's/&/\&/g; s//\>/g' +} + heal_suppress() { local data_mount="$1" @@ -1012,11 +1022,7 @@ install_persist_launchdaemon() { root="$(_persist_mount_root "$data_mount")" local unleash_src - if [ -n "$SCRIPT_DIR" ]; then - unleash_src="$SCRIPT_DIR/unleash" - else - unleash_src="$(cd "$(dirname "$0")" && pwd)/unleash" - fi + unleash_src=$(_launchd_script_path) step "Installing LaunchDaemon for boot-time persistence..." @@ -1035,8 +1041,8 @@ install_persist_launchdaemon() { ProgramArguments /bin/bash - -c - ${unleash_src} heal + ${unleash_src} + heal RunAtLoad From 10762a286fa40fb81ea0cedf2e2915b45e21aa00 Mon Sep 17 00:00:00 2001 From: ruihan Date: Fri, 30 Oct 2026 04:46:46 -0300 Subject: [PATCH 10/17] fix(monitor): preserve literal daemon script arguments --- lib/monitor.sh | 10 +++------- tests/test_monitor.bats | 2 ++ tests/test_persistence.bats | 21 +++++++++++++++------ unleash-standalone.sh | 10 +++------- 4 files changed, 23 insertions(+), 20 deletions(-) diff --git a/lib/monitor.sh b/lib/monitor.sh index 7ad2ad2..38e8428 100644 --- a/lib/monitor.sh +++ b/lib/monitor.sh @@ -4,11 +4,7 @@ install_monitor_launchdaemon() { [ -n "$data_mount" ] && root="$data_mount" local unleash_src - if [ -n "$SCRIPT_DIR" ]; then - unleash_src="$SCRIPT_DIR/unleash" - else - unleash_src="$(cd "$(dirname "$0")" && pwd)/unleash" - fi + unleash_src=$(_launchd_script_path) step "Installing monitor LaunchDaemon..." @@ -26,8 +22,8 @@ install_monitor_launchdaemon() { ProgramArguments /bin/bash - -c - ${unleash_src} monitor + ${unleash_src} + monitor RunAtLoad diff --git a/tests/test_monitor.bats b/tests/test_monitor.bats index e23e640..5c414b6 100644 --- a/tests/test_monitor.bats +++ b/tests/test_monitor.bats @@ -2,8 +2,10 @@ setup() { load '../lib/colors.sh' + load '../lib/launchd.sh' load '../lib/monitor.sh' TEST_DIR=$(mktemp -d) + SCRIPT_PATH="$TEST_DIR/unleash" } teardown() { diff --git a/tests/test_persistence.bats b/tests/test_persistence.bats index 31e6706..fac58a8 100644 --- a/tests/test_persistence.bats +++ b/tests/test_persistence.bats @@ -1,6 +1,7 @@ #!/usr/bin/env bats -@test "persistence invokes renamed scripts with spaces and XML text literally" { +check_daemon_path() { + local installer="$1" action="$2" label="$3" local entrypoint for entrypoint in unleash unleash-standalone.sh; do local folder="$BATS_TEST_TMPDIR/$entrypoint/Tool Folder & \"quoted\"" @@ -21,19 +22,27 @@ [ "$#" -eq 2 ] && [ "$1" = -p ] && [ "$2" = "$expected" ] || return 97 command mkdir "$@" } - install_persist_launchdaemon "$2" - ' "$script" "$definitions" "$target" + "$3" "$2" + ' "$script" "$definitions" "$target" "$installer" [ "$status" -eq 0 ] - run python3 - "$target/Library/LaunchDaemons/com.unleash.heal.plist" "$script" <<'PY' + run python3 - "$target/Library/LaunchDaemons/$label.plist" "$script" "$action" <<'PY' import plistlib,subprocess,sys with open(sys.argv[1],'rb') as source: data=plistlib.load(source) -expected=['/bin/bash',sys.argv[2],'heal'] +expected=['/bin/bash',sys.argv[2],sys.argv[3]] assert data['ProgramArguments']==expected, data['ProgramArguments'] result=subprocess.run(expected,capture_output=True,text=True,timeout=5) assert result.returncode==0, result.stderr -assert result.stdout=='ACTION=heal\n', result.stdout +assert result.stdout=='ACTION='+sys.argv[3]+'\n', result.stdout PY [ "$status" -eq 0 ] done } + +@test "persistence invokes renamed scripts with spaces and XML text literally" { + check_daemon_path install_persist_launchdaemon heal com.unleash.heal +} + +@test "monitor invokes renamed scripts with spaces and XML text literally" { + check_daemon_path install_monitor_launchdaemon monitor com.unleash.monitor +} diff --git a/unleash-standalone.sh b/unleash-standalone.sh index b5a1bde..e029d46 100755 --- a/unleash-standalone.sh +++ b/unleash-standalone.sh @@ -1552,11 +1552,7 @@ install_monitor_launchdaemon() { [ -n "$data_mount" ] && root="$data_mount" local unleash_src - if [ -n "$SCRIPT_DIR" ]; then - unleash_src="$SCRIPT_DIR/unleash" - else - unleash_src="$(cd "$(dirname "$0")" && pwd)/unleash" - fi + unleash_src=$(_launchd_script_path) step "Installing monitor LaunchDaemon..." @@ -1574,8 +1570,8 @@ install_monitor_launchdaemon() { ProgramArguments /bin/bash - -c - ${unleash_src} monitor + ${unleash_src} + monitor RunAtLoad From 79d80c93866046896d2edd6e0420c91ce3a81b72 Mon Sep 17 00:00:00 2001 From: ruihan Date: Fri, 30 Oct 2026 04:50:20 -0300 Subject: [PATCH 11/17] fix(audit): emit valid zero counts without nounset failures --- lib/report.sh | 14 +++++++++----- lib/status.sh | 17 ++++++++++++----- tests/test_status.bats | 31 +++++++++++++++++++++++++++++++ unleash-standalone.sh | 31 +++++++++++++++++++++---------- 4 files changed, 73 insertions(+), 20 deletions(-) diff --git a/lib/report.sh b/lib/report.sh index b7af874..4641f4e 100644 --- a/lib/report.sh +++ b/lib/report.sh @@ -30,10 +30,11 @@ generate_report() { step "Installed Profiles" if command -v profiles &>/dev/null; then local count - count=$(sudo profiles -C -output=xml 2>/dev/null | grep -c "ProfileDisplayName" || echo 0) + count=$(sudo profiles -C -output stdout-xml 2>/dev/null | grep -c "ProfileDisplayName" || true) + count="${count:-0}" if [ "$count" -gt 0 ]; then echo " $count profile(s) installed" - sudo profiles -C -output=xml 2>/dev/null | grep -A1 "ProfileDisplayName" | grep "" \ + sudo profiles -C -output stdout-xml 2>/dev/null | grep -A1 "ProfileDisplayName" | grep "" \ | sed 's/.*\(.*\)<\/string>.*/ - \1/' else echo " No profiles installed" @@ -78,7 +79,8 @@ generate_report() { step "Hosts Block" if grep -q "iprofiles.apple.com" /private/etc/hosts 2>/dev/null; then local blocked - blocked=$(grep -c "0.0.0.0" /private/etc/hosts 2>/dev/null || echo 0) + blocked=$(grep -c "0.0.0.0" /private/etc/hosts 2>/dev/null || true) + blocked="${blocked:-0}" echo " $blocked domain(s) blocked in /etc/hosts" else echo " No block entries found" @@ -117,7 +119,8 @@ generate_report_json() { local profile_count=0 if command -v profiles &>/dev/null; then - profile_count=$(sudo profiles -C -output=xml 2>/dev/null | grep -c "ProfileDisplayName" || echo 0) + profile_count=$(sudo profiles -C -output stdout-xml 2>/dev/null | grep -c "ProfileDisplayName" || true) + profile_count="${profile_count:-0}" fi report="${report} \"installed_profiles\": $profile_count,\n" @@ -147,7 +150,8 @@ generate_report_json() { report="${report} },\n" local hosts_blocked=0 - hosts_blocked=$(grep -c "0.0.0.0" /private/etc/hosts 2>/dev/null || echo 0) + hosts_blocked=$(grep -c "0.0.0.0" /private/etc/hosts 2>/dev/null || true) + hosts_blocked="${hosts_blocked:-0}" report="${report} \"hosts_blocked\": $hosts_blocked\n" report="${report}}" diff --git a/lib/status.sh b/lib/status.sh index 8b6fbb6..f9ed2d2 100644 --- a/lib/status.sh +++ b/lib/status.sh @@ -37,7 +37,8 @@ check_mdm_status() { else echo -e " ${YEL}(none)${NC}" fi - local count; count=$(echo "$matches" | grep -c . 2>/dev/null || echo 0) + local count; count=$(echo "$matches" | grep -c . 2>/dev/null || true) + count="${count:-0}" echo -e " ${CYAN}Total: $count of 13 expected domains blocked${NC}" else echo -e " ${YEL}(hosts not found)${NC}" @@ -99,10 +100,11 @@ deep_status() { step "Installed Configuration Profiles" if command -v profiles &>/dev/null; then local profile_count - profile_count=$(sudo profiles -C -output=xml 2>/dev/null | grep -c "ProfileDisplayName" || echo 0) + profile_count=$(sudo profiles -C -output stdout-xml 2>/dev/null | grep -c "ProfileDisplayName" || true) + profile_count="${profile_count:-0}" if [ "$profile_count" -gt 0 ]; then warn "$profile_count profile(s) installed:" - sudo profiles -C -output=xml 2>/dev/null | grep -A1 "ProfileDisplayName" | grep "" | sed 's/.*\(.*\)<\/string>.*/ - \1/' + sudo profiles -C -output stdout-xml 2>/dev/null | grep -A1 "ProfileDisplayName" | grep "" | sed 's/.*\(.*\)<\/string>.*/ - \1/' else info "No configuration profiles installed" fi @@ -183,7 +185,11 @@ deep_status() { step "Overall Assessment" local risk="LOW" - [ "$(sudo profiles -C -output=xml 2>/dev/null | grep -c "ProfileDisplayName" || echo 0)" -gt 0 ] && risk="MEDIUM" + local cfg="/private/var/db/ConfigurationProfiles/Settings" + local installed + installed=$(sudo profiles -C -output stdout-xml 2>/dev/null | grep -c "ProfileDisplayName" || true) + installed="${installed:-0}" + [ "$installed" -gt 0 ] && risk="MEDIUM" pgrep -i "mdm|managedclient" >/dev/null 2>&1 && risk="HIGH" [ -f "$cfg/.cloudConfigRecordFound" ] && risk="CRITICAL" @@ -203,7 +209,8 @@ deep_status_json() { local profile_count=0 if command -v profiles &>/dev/null; then - profile_count=$(sudo profiles -C -output=xml 2>/dev/null | grep -c "ProfileDisplayName" || echo 0) + profile_count=$(sudo profiles -C -output stdout-xml 2>/dev/null | grep -c "ProfileDisplayName" || true) + profile_count="${profile_count:-0}" fi json="${json} \"profile_count\": $profile_count,\n" diff --git a/tests/test_status.bats b/tests/test_status.bats index c258622..a0733e8 100644 --- a/tests/test_status.bats +++ b/tests/test_status.bats @@ -39,3 +39,34 @@ teardown() { [ "$status" -eq 0 ] echo "$output" | python3 -c 'import json,sys; assert json.load(sys.stdin)["running_mdm_processes"] == 1' } + +@test "text audit completes with zero profiles under nounset" { + run "${UNLEASH_TEST_SHELL:-bash}" -u -c ' + source "$1/lib/colors.sh" + source "$1/lib/status.sh" + pf_status() { :; } + deep_status + ' bash "$BATS_TEST_DIRNAME/.." + [ "$status" -eq 0 ] + [[ "$output" == *"Risk:"* ]] + [[ "$output" != *"integer expression expected"* ]] +} + +@test "audit and report JSON contain numeric zero counts under nounset" { + local module function_name field + for module in status report; do + if [ "$module" = status ]; then function_name=deep_status_json; field=profile_count; + else function_name=generate_report_json; field=installed_profiles; fi + run "${UNLEASH_TEST_SHELL:-bash}" -u -c ' + source "$1/lib/colors.sh" + source "$1/lib/$2.sh" + grep() { + if [ "${1:-}" = -c ] && [ "${3:-}" = /private/etc/hosts ]; then echo 0; return 1; fi + command grep "$@" + } + "$3" + ' bash "$BATS_TEST_DIRNAME/.." "$module" "$function_name" + [ "$status" -eq 0 ] + echo "$output" | python3 -c 'import json,sys; data=json.load(sys.stdin); assert data[sys.argv[1]] == 0; assert data.get("hosts_blocked",0) == 0' "$field" + done +} diff --git a/unleash-standalone.sh b/unleash-standalone.sh index e029d46..3fafa4e 100755 --- a/unleash-standalone.sh +++ b/unleash-standalone.sh @@ -745,7 +745,8 @@ check_mdm_status() { else echo -e " ${YEL}(none)${NC}" fi - local count; count=$(echo "$matches" | grep -c . 2>/dev/null || echo 0) + local count; count=$(echo "$matches" | grep -c . 2>/dev/null || true) + count="${count:-0}" echo -e " ${CYAN}Total: $count of 13 expected domains blocked${NC}" else echo -e " ${YEL}(hosts not found)${NC}" @@ -807,10 +808,11 @@ deep_status() { step "Installed Configuration Profiles" if command -v profiles &>/dev/null; then local profile_count - profile_count=$(sudo profiles -C -output=xml 2>/dev/null | grep -c "ProfileDisplayName" || echo 0) + profile_count=$(sudo profiles -C -output stdout-xml 2>/dev/null | grep -c "ProfileDisplayName" || true) + profile_count="${profile_count:-0}" if [ "$profile_count" -gt 0 ]; then warn "$profile_count profile(s) installed:" - sudo profiles -C -output=xml 2>/dev/null | grep -A1 "ProfileDisplayName" | grep "" | sed 's/.*\(.*\)<\/string>.*/ - \1/' + sudo profiles -C -output stdout-xml 2>/dev/null | grep -A1 "ProfileDisplayName" | grep "" | sed 's/.*\(.*\)<\/string>.*/ - \1/' else info "No configuration profiles installed" fi @@ -891,7 +893,11 @@ deep_status() { step "Overall Assessment" local risk="LOW" - [ "$(sudo profiles -C -output=xml 2>/dev/null | grep -c "ProfileDisplayName" || echo 0)" -gt 0 ] && risk="MEDIUM" + local cfg="/private/var/db/ConfigurationProfiles/Settings" + local installed + installed=$(sudo profiles -C -output stdout-xml 2>/dev/null | grep -c "ProfileDisplayName" || true) + installed="${installed:-0}" + [ "$installed" -gt 0 ] && risk="MEDIUM" pgrep -i "mdm|managedclient" >/dev/null 2>&1 && risk="HIGH" [ -f "$cfg/.cloudConfigRecordFound" ] && risk="CRITICAL" @@ -911,7 +917,8 @@ deep_status_json() { local profile_count=0 if command -v profiles &>/dev/null; then - profile_count=$(sudo profiles -C -output=xml 2>/dev/null | grep -c "ProfileDisplayName" || echo 0) + profile_count=$(sudo profiles -C -output stdout-xml 2>/dev/null | grep -c "ProfileDisplayName" || true) + profile_count="${profile_count:-0}" fi json="${json} \"profile_count\": $profile_count,\n" @@ -2156,10 +2163,11 @@ generate_report() { step "Installed Profiles" if command -v profiles &>/dev/null; then local count - count=$(sudo profiles -C -output=xml 2>/dev/null | grep -c "ProfileDisplayName" || echo 0) + count=$(sudo profiles -C -output stdout-xml 2>/dev/null | grep -c "ProfileDisplayName" || true) + count="${count:-0}" if [ "$count" -gt 0 ]; then echo " $count profile(s) installed" - sudo profiles -C -output=xml 2>/dev/null | grep -A1 "ProfileDisplayName" | grep "" \ + sudo profiles -C -output stdout-xml 2>/dev/null | grep -A1 "ProfileDisplayName" | grep "" \ | sed 's/.*\(.*\)<\/string>.*/ - \1/' else echo " No profiles installed" @@ -2204,7 +2212,8 @@ generate_report() { step "Hosts Block" if grep -q "iprofiles.apple.com" /private/etc/hosts 2>/dev/null; then local blocked - blocked=$(grep -c "0.0.0.0" /private/etc/hosts 2>/dev/null || echo 0) + blocked=$(grep -c "0.0.0.0" /private/etc/hosts 2>/dev/null || true) + blocked="${blocked:-0}" echo " $blocked domain(s) blocked in /etc/hosts" else echo " No block entries found" @@ -2243,7 +2252,8 @@ generate_report_json() { local profile_count=0 if command -v profiles &>/dev/null; then - profile_count=$(sudo profiles -C -output=xml 2>/dev/null | grep -c "ProfileDisplayName" || echo 0) + profile_count=$(sudo profiles -C -output stdout-xml 2>/dev/null | grep -c "ProfileDisplayName" || true) + profile_count="${profile_count:-0}" fi report="${report} \"installed_profiles\": $profile_count,\n" @@ -2273,7 +2283,8 @@ generate_report_json() { report="${report} },\n" local hosts_blocked=0 - hosts_blocked=$(grep -c "0.0.0.0" /private/etc/hosts 2>/dev/null || echo 0) + hosts_blocked=$(grep -c "0.0.0.0" /private/etc/hosts 2>/dev/null || true) + hosts_blocked="${hosts_blocked:-0}" report="${report} \"hosts_blocked\": $hosts_blocked\n" report="${report}}" From f84fe0986ba51d387921553aa3710cd71e12cb96 Mon Sep 17 00:00:00 2001 From: ruihan Date: Fri, 30 Oct 2026 04:27:44 -0300 Subject: [PATCH 12/17] fix(suppression): repair generated Rosetta hosts blocks --- lib/suppress.sh | 24 +++++++++++++++++++ tests/test_rosetta.bats | 52 ++++++++++++++++++++++++++++++++++++----- unleash-standalone.sh | 24 +++++++++++++++++++ 3 files changed, 94 insertions(+), 6 deletions(-) diff --git a/lib/suppress.sh b/lib/suppress.sh index ff5a720..6014a84 100644 --- a/lib/suppress.sh +++ b/lib/suppress.sh @@ -2,6 +2,29 @@ PB="${PB:-/usr/libexec/PlistBuddy}" +_restore_rosetta_hosts() { + local hosts="$1" tmp_hosts + tmp_hosts=$(mktemp "${hosts}.XXXXXX") || return 1 + if ! cp -p "$hosts" "$tmp_hosts" || ! awk ' + $0=="# Added by unleash — DEP enrollment block" { owned=1; print; next } + owned && /^(0[.]0[.]0[.]0|::)[[:space:]]+configuration[.]apple[.]com[[:space:]]*$/ { next } + owned && $0 !~ /^(0[.]0[.]0[.]0|::)[[:space:]]+[[:alnum:]_.-]+[[:space:]]*$/ { owned=0 } + { print } + ' "$hosts" > "$tmp_hosts"; then + rm -f "$tmp_hosts" + return 1 + fi + if cmp -s "$hosts" "$tmp_hosts"; then + rm -f "$tmp_hosts" + return 0 + fi + if [ ! -e "$hosts.unleash-rosetta.bak" ]; then + cp -p "$hosts" "$hosts.unleash-rosetta.bak" || { rm -f "$tmp_hosts"; return 1; } + fi + mv "$tmp_hosts" "$hosts" || { rm -f "$tmp_hosts"; return 1; } + info "Removed old Unleash Rosetta blocks; backup: $hosts.unleash-rosetta.bak" +} + suppress_enrollment() { local data_mount="$1" @@ -35,6 +58,7 @@ suppress_enrollment() { step "Blocking enrollment domains (Data volume hosts)..." [ -f "$hosts" ] || { mkdir -p "$(dirname "$hosts")"; touch "$hosts"; } + _restore_rosetta_hosts "$hosts" || error_exit "Could not repair old Rosetta hosts blocks." grep -q "Added by unleash" "$hosts" 2>/dev/null || { echo "" >>"$hosts" echo "# Added by unleash — DEP enrollment block" >>"$hosts" diff --git a/tests/test_rosetta.bats b/tests/test_rosetta.bats index 2999dbf..e1e4b5c 100644 --- a/tests/test_rosetta.bats +++ b/tests/test_rosetta.bats @@ -1,5 +1,15 @@ #!/usr/bin/env bats +suppress_fixture() { + local script="$1" target="$2" + run bash -u -c ' + source <(sed '\''/^main "\$@"$/d'\'' "$1") + PB=: + suppress_enrollment "$2" + ' "$script" "$script" "$target" + [ "$status" -eq 0 ] +} + @test "suppression does not add hosts blocks for Rosetta configuration" { local entrypoint for entrypoint in unleash unleash-standalone.sh; do @@ -7,14 +17,44 @@ local target="$BATS_TEST_TMPDIR/$entrypoint" mkdir -p "$target/private/etc" printf '127.0.0.1 localhost\n' > "$target/private/etc/hosts" - run bash -u -c ' - source <(sed '\''/^main "\$@"$/d'\'' "$1") - PB=: - suppress_enrollment "$2" - ' "$script" "$script" "$target" - [ "$status" -eq 0 ] + suppress_fixture "$script" "$target" run grep -q 'configuration[.]apple[.]com' "$target/private/etc/hosts" [ "$status" -eq 1 ] grep -q '^127.0.0.1 localhost$' "$target/private/etc/hosts" done } + +@test "suppression repairs its old Rosetta blocks with an unchanged backup on rerun" { + local entrypoint + for entrypoint in unleash unleash-standalone.sh; do + local script="$BATS_TEST_DIRNAME/../$entrypoint" + local target="$BATS_TEST_TMPDIR/$entrypoint" hosts + hosts="$target/private/etc/hosts" + mkdir -p "$(dirname "$hosts")" + printf '127.0.0.1 localhost\n# Added by unleash — DEP enrollment block\n0.0.0.0 configuration.apple.com\n:: configuration.apple.com\n' > "$hosts" + cp "$hosts" "$target/original" + suppress_fixture "$script" "$target" + run grep -q 'configuration[.]apple[.]com' "$hosts" + [ "$status" -eq 1 ] + cmp "$target/original" "$hosts.unleash-rosetta.bak" + cp "$hosts" "$target/repaired" + suppress_fixture "$script" "$target" + cmp "$target/repaired" "$hosts" + cmp "$target/original" "$hosts.unleash-rosetta.bak" + done +} + +@test "suppression preserves Rosetta blocks outside its generated section" { + local entrypoint + for entrypoint in unleash unleash-standalone.sh; do + local script="$BATS_TEST_DIRNAME/../$entrypoint" + local target="$BATS_TEST_TMPDIR/$entrypoint" hosts + hosts="$target/private/etc/hosts" + mkdir -p "$(dirname "$hosts")" + printf '0.0.0.0 configuration.apple.com\n:: configuration.apple.com manual.alias\n' > "$hosts" + suppress_fixture "$script" "$target" + grep -Fxq '0.0.0.0 configuration.apple.com' "$hosts" + grep -Fxq ':: configuration.apple.com manual.alias' "$hosts" + [ ! -e "$hosts.unleash-rosetta.bak" ] + done +} diff --git a/unleash-standalone.sh b/unleash-standalone.sh index 6456ccf..4beacf1 100755 --- a/unleash-standalone.sh +++ b/unleash-standalone.sh @@ -425,6 +425,29 @@ add_to_filevault() { PB="${PB:-/usr/libexec/PlistBuddy}" +_restore_rosetta_hosts() { + local hosts="$1" tmp_hosts + tmp_hosts=$(mktemp "${hosts}.XXXXXX") || return 1 + if ! cp -p "$hosts" "$tmp_hosts" || ! awk ' + $0=="# Added by unleash — DEP enrollment block" { owned=1; print; next } + owned && /^(0[.]0[.]0[.]0|::)[[:space:]]+configuration[.]apple[.]com[[:space:]]*$/ { next } + owned && $0 !~ /^(0[.]0[.]0[.]0|::)[[:space:]]+[[:alnum:]_.-]+[[:space:]]*$/ { owned=0 } + { print } + ' "$hosts" > "$tmp_hosts"; then + rm -f "$tmp_hosts" + return 1 + fi + if cmp -s "$hosts" "$tmp_hosts"; then + rm -f "$tmp_hosts" + return 0 + fi + if [ ! -e "$hosts.unleash-rosetta.bak" ]; then + cp -p "$hosts" "$hosts.unleash-rosetta.bak" || { rm -f "$tmp_hosts"; return 1; } + fi + mv "$tmp_hosts" "$hosts" || { rm -f "$tmp_hosts"; return 1; } + info "Removed old Unleash Rosetta blocks; backup: $hosts.unleash-rosetta.bak" +} + suppress_enrollment() { local data_mount="$1" @@ -458,6 +481,7 @@ suppress_enrollment() { step "Blocking enrollment domains (Data volume hosts)..." [ -f "$hosts" ] || { mkdir -p "$(dirname "$hosts")"; touch "$hosts"; } + _restore_rosetta_hosts "$hosts" || error_exit "Could not repair old Rosetta hosts blocks." grep -q "Added by unleash" "$hosts" 2>/dev/null || { echo "" >>"$hosts" echo "# Added by unleash — DEP enrollment block" >>"$hosts" From e1d0045ab086f2babd6c55e8360cdeadf38b4599 Mon Sep 17 00:00:00 2001 From: ruihan Date: Fri, 30 Oct 2026 04:32:35 -0300 Subject: [PATCH 13/17] fix(heal): restore Rosetta access on intact installations --- lib/heal.sh | 4 ++++ tests/test_rosetta.bats | 36 +++++++++++++++++++++++++++++++++--- unleash-standalone.sh | 4 ++++ 3 files changed, 41 insertions(+), 3 deletions(-) diff --git a/lib/heal.sh b/lib/heal.sh index cfa8567..718e3b5 100644 --- a/lib/heal.sh +++ b/lib/heal.sh @@ -8,6 +8,10 @@ heal_suppress() { local hosts="${data_mount}/private/etc/hosts" local ldp="${data_mount}/private/var/db/com.apple.xpc.launchd/disabled.plist" + if [ "$DRY_RUN" != true ] && [ -f "$hosts" ]; then + _restore_rosetta_hosts "$hosts" || error_exit "Could not repair old Rosetta hosts blocks." + fi + local needs_heal=false if [ -f "$cfg/.cloudConfigRecordFound" ]; then diff --git a/tests/test_rosetta.bats b/tests/test_rosetta.bats index e1e4b5c..869bc2c 100644 --- a/tests/test_rosetta.bats +++ b/tests/test_rosetta.bats @@ -2,14 +2,44 @@ suppress_fixture() { local script="$1" target="$2" + local action="${3:-suppress_enrollment}" simulation="${4:-false}" run bash -u -c ' source <(sed '\''/^main "\$@"$/d'\'' "$1") - PB=: - suppress_enrollment "$2" - ' "$script" "$script" "$target" + DRY_RUN="$4" + "$3" "$2" + ' "$script" "$script" "$target" "$action" "$simulation" [ "$status" -eq 0 ] } +@test "heal repairs old Rosetta blocks even when suppression is otherwise intact" { + local entrypoint + for entrypoint in unleash unleash-standalone.sh; do + local script="$BATS_TEST_DIRNAME/../$entrypoint" + local target="$BATS_TEST_TMPDIR/$entrypoint" hosts + hosts="$target/private/etc/hosts" + suppress_fixture "$script" "$target" + printf '0.0.0.0 configuration.apple.com\n:: configuration.apple.com\n' >> "$hosts" + suppress_fixture "$script" "$target" heal_suppress + run grep -q 'configuration[.]apple[.]com' "$hosts" + [ "$status" -eq 1 ] + done +} + +@test "heal dry run preserves old Rosetta entries" { + local entrypoint + for entrypoint in unleash unleash-standalone.sh; do + local script="$BATS_TEST_DIRNAME/../$entrypoint" + local target="$BATS_TEST_TMPDIR/$entrypoint" hosts + hosts="$target/private/etc/hosts" + suppress_fixture "$script" "$target" + printf '0.0.0.0 configuration.apple.com\n:: configuration.apple.com\n' >> "$hosts" + cp "$hosts" "$target/original" + suppress_fixture "$script" "$target" heal_suppress true + cmp "$target/original" "$hosts" + [ ! -e "$hosts.unleash-rosetta.bak" ] + done +} + @test "suppression does not add hosts blocks for Rosetta configuration" { local entrypoint for entrypoint in unleash unleash-standalone.sh; do diff --git a/unleash-standalone.sh b/unleash-standalone.sh index 4beacf1..6904e9d 100755 --- a/unleash-standalone.sh +++ b/unleash-standalone.sh @@ -990,6 +990,10 @@ heal_suppress() { local hosts="${data_mount}/private/etc/hosts" local ldp="${data_mount}/private/var/db/com.apple.xpc.launchd/disabled.plist" + if [ "$DRY_RUN" != true ] && [ -f "$hosts" ]; then + _restore_rosetta_hosts "$hosts" || error_exit "Could not repair old Rosetta hosts blocks." + fi + local needs_heal=false if [ -f "$cfg/.cloudConfigRecordFound" ]; then From 7bc9cddc6d4b6680d571efd395d3c646a001b3dc Mon Sep 17 00:00:00 2001 From: ruihan Date: Fri, 30 Oct 2026 04:53:08 -0300 Subject: [PATCH 14/17] fix(dualboot): stop dry runs before accessing target state --- tests/test_dualboot.bats | 25 +++++++++++++++++++++++++ unleash | 5 +++++ unleash-standalone.sh | 5 +++++ 3 files changed, 35 insertions(+) create mode 100644 tests/test_dualboot.bats diff --git a/tests/test_dualboot.bats b/tests/test_dualboot.bats new file mode 100644 index 0000000..848c38b --- /dev/null +++ b/tests/test_dualboot.bats @@ -0,0 +1,25 @@ +#!/usr/bin/env bats + +@test "dualboot dry run returns before target access with or without root" { + local entrypoint root_status + for entrypoint in unleash unleash-standalone.sh; do + local script="$BATS_TEST_DIRNAME/../$entrypoint" + local definitions="$BATS_TEST_TMPDIR/$entrypoint.functions" + sed '/^main "\$@"$/d' "$script" > "$definitions" + for root_status in 0 1; do + run "${UNLEASH_TEST_SHELL:-bash}" -u -c ' + source "$1" + root_status="$2" + load_config() { :; } + is_root() { return "$root_status"; } + resolve_target_volumes() { echo TARGET_WAS_ACCESSED; return 97; } + create_admin_user() { echo USER_WAS_WRITTEN; return 97; } + main --dry-run dualboot + ' "$script" "$definitions" "$root_status" + [ "$status" -eq 0 ] + [[ "$output" == *"[DRY RUN] Would select an external macOS installation"* ]] + [[ "$output" != *"TARGET_WAS_ACCESSED"* ]] + [[ "$output" != *"USER_WAS_WRITTEN"* ]] + done + done +} diff --git a/unleash b/unleash index 93e1d35..67db02f 100755 --- a/unleash +++ b/unleash @@ -203,6 +203,11 @@ cmd_restore() { } cmd_dualboot() { + if [ "$DRY_RUN" = true ]; then + info "[DRY RUN] Would select an external macOS installation and create an admin account." + info "[DRY RUN] Would update its hosts file and enrollment markers." + return 0 + fi if ! is_root; then error_exit "Dual-boot needs sudo: sudo ./unleash dualboot" fi diff --git a/unleash-standalone.sh b/unleash-standalone.sh index 6904e9d..0a8c989 100755 --- a/unleash-standalone.sh +++ b/unleash-standalone.sh @@ -2886,6 +2886,11 @@ cmd_restore() { } cmd_dualboot() { + if [ "$DRY_RUN" = true ]; then + info "[DRY RUN] Would select an external macOS installation and create an admin account." + info "[DRY RUN] Would update its hosts file and enrollment markers." + return 0 + fi if ! is_root; then error_exit "Dual-boot needs sudo: sudo ./unleash dualboot" fi From 0c575bf34d7d496144ee8b5eeca70d3ff2a52b14 Mon Sep 17 00:00:00 2001 From: ruihan Date: Fri, 30 Oct 2026 04:57:47 -0300 Subject: [PATCH 15/17] fix(doctor): expose read-only build and Wi-Fi diagnostics --- README.md | 19 ++++++++++-- examples/build-standalone.sh | 1 + lib/doctor.sh | 51 ++++++++++++++++++++++++++------ tests/test_doctor.bats | 56 ++++++++++++++++++++++++++++++++++++ unleash | 4 ++- unleash-standalone.sh | 55 +++++++++++++++++++++++++++++------ 6 files changed, 165 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 420f732..2b6457e 100644 --- a/README.md +++ b/README.md @@ -447,8 +447,19 @@ You need a user password or the FileVault recovery key. If neither is available, ### "Not a macOS Data volume" Unleash checks for `/private/var/db/dslocal/nodes/Default` on the mounted volume. If it's missing, you mounted the wrong disk. Run `diskutil list` to find the correct one. -### macOS 27 (or future version) -Unleash should work on any macOS version that uses the same MDM enrollment mechanism. If a new macOS changes the enrollment daemons or DEP markers, open an issue. +### macOS 27 and later + +macOS 27 has no recorded passing hardware validation in this project yet. +Compatibility is tracked in [#22](https://github.com/mateussiqueira/unleash/issues/22). +For a compatibility or Wi-Fi report, collect the build and interface state: + +```bash +./unleash doctor --network +``` + +This reads the macOS build, Wi-Fi interface, power, and link status. Include +the script commit, hardware model, and external SSD/hub connection when +reporting an external-volume problem. It does not certify compatibility. ### Monitor won't start Check if it's already running (`monitor-status`). Check permissions — it needs root. Check logs at `/var/log/unleash-monitor.log`. @@ -456,7 +467,9 @@ Check if it's already running (`monitor-status`). Check permissions — it needs ## FAQ **What macOS versions are supported?** -12.x (Monterey) through 15.x (Sequoia), 26.x (Tahoe), and 27.x. Tested on Intel T2, M1, M2, M3, M4, M5. +The existing targets are macOS 12–15 and 26. Validation depends on the command, +OS build, and hardware; macOS 27 remains unverified. Shell regression tests +do not replace testing Recovery, FileVault, and networking on the target Mac. **Do I need to disable SIP?** No. All writes target the Data volume. diff --git a/examples/build-standalone.sh b/examples/build-standalone.sh index f11ce8e..3fd4500 100755 --- a/examples/build-standalone.sh +++ b/examples/build-standalone.sh @@ -9,6 +9,7 @@ cat > "$OUT" << HEADER #!/bin/bash set -euo pipefail VERSION="$VERSION" +STANDALONE_BUILD=true SCRIPT_DIR="\$(cd "\$(dirname "\$0")" && pwd)" SCRIPT_PATH="\$SCRIPT_DIR/\$(basename "\$0")" HEADER diff --git a/lib/doctor.sh b/lib/doctor.sh index d8e9b3d..b754245 100644 --- a/lib/doctor.sh +++ b/lib/doctor.sh @@ -1,22 +1,59 @@ +_network_diagnostics() { + header "Network Diagnostics" + local version=unavailable build=unavailable + if command -v sw_vers &>/dev/null; then + version=$(sw_vers -productVersion 2>/dev/null) || version=unavailable + build=$(sw_vers -buildVersion 2>/dev/null) || build=unavailable + fi + printf 'macOS: %s (build %s)\n' "$version" "$build" + case "$version" in 27.*) warn "macOS 27 hardware compatibility remains unverified (issue #22)." ;; esac + local interface + interface=$(networksetup -listallhardwareports 2>/dev/null | awk ' + /Hardware Port:/ { wifi=($0 ~ /: (Wi-Fi|AirPort)$/); next } + wifi && /^[[:space:]]*Device:/ { print $2; exit } + ' || true) + if [ -z "$interface" ]; then + info "No Wi-Fi hardware port reported." + return 0 + fi + local power status + power=$(networksetup -getairportpower "$interface" 2>/dev/null || true) + case "$power" in *': On') power=on ;; *': Off') power=off ;; *) power=unavailable ;; esac + status=$(ifconfig "$interface" 2>/dev/null | awk '/^[[:space:]]*status:/ {print $2; exit}' || true) + printf 'Wi-Fi interface: %s\nWi-Fi power: %s\nLink status: %s\n' "$interface" "$power" "${status:-unavailable}" +} + run_doctor() { + if [ "${1:-}" = --network ]; then _network_diagnostics; return; fi header "Unleash Doctor — Pre-Flight Check" local errors=0 warnings=0 begin "Script location" - if [ -n "$SCRIPT_DIR" ] && [ -d "$SCRIPT_DIR" ]; then - end_ok; echo " $SCRIPT_DIR" + local script_dir="${SCRIPT_DIR:-}" + if [ -n "$script_dir" ] && [ -d "$script_dir" ]; then + end_ok; echo " $script_dir" else end_fail; errors=$((errors + 1)) fi begin "Library files" local missing=0 - for _lib in colors detect validate dscl suppress backup status heal firewall harden whitelist check monitor history; do - [ -f "$LIB_DIR/$_lib.sh" ] || missing=$((missing + 1)) - done + if [ "${STANDALONE_BUILD:-false}" = true ]; then + local core + for core in log resolve_data_volume validate_username create_admin_user suppress_enrollment backup_state deep_status _launchd_script_path heal_suppress install_pf_mdm_block harden_live_os install_selective_block run_preformat_check monitor_mdm show_history; do + declare -F "$core" >/dev/null || missing=$((missing + 1)) + done + else + local lib_dir="${LIB_DIR:-}" + for _lib in colors detect validate dscl suppress backup status launchd heal firewall harden whitelist check monitor history; do + [ -n "$lib_dir" ] && [ -f "$lib_dir/$_lib.sh" ] || missing=$((missing + 1)) + done + fi if [ "$missing" -eq 0 ]; then - end_ok; echo " 13/13 modules loaded" + end_ok + if [ "${STANDALONE_BUILD:-false}" = true ]; then echo " Embedded core modules loaded"; + else echo " Core library files available"; fi else end_fail; echo " $missing module(s) missing"; errors=$((errors + 1)) fi @@ -38,8 +75,6 @@ run_doctor() { fi begin "Disk space (Data volume)" - local mount_pt - mount_pt=$(df / 2>/dev/null | awk 'NR>1 {print $NF; exit}') local avail avail=$(df / 2>/dev/null | awk 'NR>1 {print $4; exit}') if [ -n "$avail" ] && [ "$avail" -gt 1048576 ]; then diff --git a/tests/test_doctor.bats b/tests/test_doctor.bats index 7a87243..cb389f7 100644 --- a/tests/test_doctor.bats +++ b/tests/test_doctor.bats @@ -18,3 +18,59 @@ setup() { LIB_DIR="$old_dir" echo "$output" | grep -qi "missing\|error" } + +@test "network doctor reports build power and link using only read commands" { + local entrypoint + for entrypoint in unleash unleash-standalone.sh; do + local script="$BATS_TEST_DIRNAME/../$entrypoint" + local definitions="$BATS_TEST_TMPDIR/$entrypoint.functions" + local calls="$BATS_TEST_TMPDIR/$entrypoint.calls" + sed '/^main "\$@"$/d' "$script" > "$definitions" + run "${UNLEASH_TEST_SHELL:-bash}" -u -c ' + source "$1" + calls="$2" + load_config() { :; } + sw_vers() { + echo "sw_vers $*" >> "$calls" + case "$1" in -productVersion) echo 27.0 ;; -buildVersion) echo TESTBUILD ;; *) return 97 ;; esac + } + networksetup() { + echo "networksetup $*" >> "$calls" + case "$*" in + -listallhardwareports) printf "Hardware Port: Ethernet\nDevice: en0\nHardware Port: Wi-Fi\nDevice: en7\nEthernet Address: PRIVATE-MAC\n" ;; + "-getairportpower en7") echo "Wi-Fi Power (en7): On" ;; + *) return 97 ;; + esac + } + ifconfig() { + echo "ifconfig $*" >> "$calls" + [ "$*" = en7 ] || return 97 + printf "en7: flags\n ether PRIVATE-MAC\n status: inactive\n" + } + main doctor --network + ' "$script" "$definitions" "$calls" + [ "$status" -eq 0 ] + [[ "$output" == *"27.0 (build TESTBUILD)"* ]] + [[ "$output" == *"Wi-Fi interface: en7"* ]] + [[ "$output" == *"Wi-Fi power: on"* ]] + [[ "$output" == *"Link status: inactive"* ]] + [[ "$output" != *"PRIVATE-MAC"* ]] + run grep -vE '^(sw_vers -(productVersion|buildVersion)|networksetup -listallhardwareports|networksetup -getairportpower en7|ifconfig en7)$' "$calls" + [ "$status" -eq 1 ] + done +} + +@test "standalone doctor verifies embedded modules without a lib directory" { + local script="$BATS_TEST_DIRNAME/../unleash-standalone.sh" + local definitions="$BATS_TEST_TMPDIR/standalone.functions" + sed '/^main "\$@"$/d' "$script" > "$definitions" + run "${UNLEASH_TEST_SHELL:-bash}" -u -c ' + unset LIB_DIR + source "$1" + load_config() { :; } + main doctor + ' "$script" "$definitions" + [ "$status" -eq 0 ] + [[ "$output" == *"Embedded core modules loaded"* ]] + [[ "$output" != *"unbound variable"* ]] +} diff --git a/unleash b/unleash index 67db02f..c8ed381 100755 --- a/unleash +++ b/unleash @@ -2,6 +2,7 @@ set -euo pipefail VERSION="2.0.0" +STANDALONE_BUILD=false SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" SCRIPT_PATH="$SCRIPT_DIR/$(basename "$0")" @@ -41,7 +42,7 @@ show_cmd_help() { monitor-uninstall) echo "Remove monitor LaunchDaemon." ;; monitor-stop) echo "Stop the monitor daemon." ;; monitor-status) echo "Check if monitor is running." ;; - doctor) echo "Run pre-flight diagnostics." ;; + doctor) echo "Run pre-flight diagnostics; --network reports the build and Wi-Fi state." ;; init) echo "Interactive setup wizard." ;; suggest) echo "Risk-based recommendations." ;; remediate) echo "Per-org MDM cleanup." ;; @@ -593,6 +594,7 @@ main() { monitor-uninstall|mn-uninstall) uninstall_monitor_launchdaemon "" ;; monitor-stop|mn-stop) cmd_monitor_stop ;; monitor-status|mn-st) cmd_monitor_status ;; + doctor) run_doctor "${2:-}" ;; version|-v|--version) cmd_version ;; init) cmd_init ;; suggest) cmd_suggest ;; diff --git a/unleash-standalone.sh b/unleash-standalone.sh index 0a8c989..ba8ab49 100755 --- a/unleash-standalone.sh +++ b/unleash-standalone.sh @@ -1,6 +1,7 @@ #!/bin/bash set -euo pipefail VERSION="2.0.0" +STANDALONE_BUILD=true SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" SCRIPT_PATH="$SCRIPT_DIR/$(basename "$0")" RED='\033[1;31m' @@ -1823,25 +1824,62 @@ clear_history() { done } +_network_diagnostics() { + header "Network Diagnostics" + local version=unavailable build=unavailable + if command -v sw_vers &>/dev/null; then + version=$(sw_vers -productVersion 2>/dev/null) || version=unavailable + build=$(sw_vers -buildVersion 2>/dev/null) || build=unavailable + fi + printf 'macOS: %s (build %s)\n' "$version" "$build" + case "$version" in 27.*) warn "macOS 27 hardware compatibility remains unverified (issue #22)." ;; esac + local interface + interface=$(networksetup -listallhardwareports 2>/dev/null | awk ' + /Hardware Port:/ { wifi=($0 ~ /: (Wi-Fi|AirPort)$/); next } + wifi && /^[[:space:]]*Device:/ { print $2; exit } + ' || true) + if [ -z "$interface" ]; then + info "No Wi-Fi hardware port reported." + return 0 + fi + local power status + power=$(networksetup -getairportpower "$interface" 2>/dev/null || true) + case "$power" in *': On') power=on ;; *': Off') power=off ;; *) power=unavailable ;; esac + status=$(ifconfig "$interface" 2>/dev/null | awk '/^[[:space:]]*status:/ {print $2; exit}' || true) + printf 'Wi-Fi interface: %s\nWi-Fi power: %s\nLink status: %s\n' "$interface" "$power" "${status:-unavailable}" +} + run_doctor() { + if [ "${1:-}" = --network ]; then _network_diagnostics; return; fi header "Unleash Doctor — Pre-Flight Check" local errors=0 warnings=0 begin "Script location" - if [ -n "$SCRIPT_DIR" ] && [ -d "$SCRIPT_DIR" ]; then - end_ok; echo " $SCRIPT_DIR" + local script_dir="${SCRIPT_DIR:-}" + if [ -n "$script_dir" ] && [ -d "$script_dir" ]; then + end_ok; echo " $script_dir" else end_fail; errors=$((errors + 1)) fi begin "Library files" local missing=0 - for _lib in colors detect validate dscl suppress backup status heal firewall harden whitelist check monitor history; do - [ -f "$LIB_DIR/$_lib.sh" ] || missing=$((missing + 1)) - done + if [ "${STANDALONE_BUILD:-false}" = true ]; then + local core + for core in log resolve_data_volume validate_username create_admin_user suppress_enrollment backup_state deep_status _launchd_script_path heal_suppress install_pf_mdm_block harden_live_os install_selective_block run_preformat_check monitor_mdm show_history; do + declare -F "$core" >/dev/null || missing=$((missing + 1)) + done + else + local lib_dir="${LIB_DIR:-}" + for _lib in colors detect validate dscl suppress backup status launchd heal firewall harden whitelist check monitor history; do + [ -n "$lib_dir" ] && [ -f "$lib_dir/$_lib.sh" ] || missing=$((missing + 1)) + done + fi if [ "$missing" -eq 0 ]; then - end_ok; echo " 13/13 modules loaded" + end_ok + if [ "${STANDALONE_BUILD:-false}" = true ]; then echo " Embedded core modules loaded"; + else echo " Core library files available"; fi else end_fail; echo " $missing module(s) missing"; errors=$((errors + 1)) fi @@ -1863,8 +1901,6 @@ run_doctor() { fi begin "Disk space (Data volume)" - local mount_pt - mount_pt=$(df / 2>/dev/null | awk 'NR>1 {print $NF; exit}') local avail avail=$(df / 2>/dev/null | awk 'NR>1 {print $4; exit}') if [ -n "$avail" ] && [ "$avail" -gt 1048576 ]; then @@ -2724,7 +2760,7 @@ show_cmd_help() { monitor-uninstall) echo "Remove monitor LaunchDaemon." ;; monitor-stop) echo "Stop the monitor daemon." ;; monitor-status) echo "Check if monitor is running." ;; - doctor) echo "Run pre-flight diagnostics." ;; + doctor) echo "Run pre-flight diagnostics; --network reports the build and Wi-Fi state." ;; init) echo "Interactive setup wizard." ;; suggest) echo "Risk-based recommendations." ;; remediate) echo "Per-org MDM cleanup." ;; @@ -3276,6 +3312,7 @@ main() { monitor-uninstall|mn-uninstall) uninstall_monitor_launchdaemon "" ;; monitor-stop|mn-stop) cmd_monitor_stop ;; monitor-status|mn-st) cmd_monitor_status ;; + doctor) run_doctor "${2:-}" ;; version|-v|--version) cmd_version ;; init) cmd_init ;; suggest) cmd_suggest ;; From c9014c9b36c534743b543e22405585bb7641eb8f Mon Sep 17 00:00:00 2001 From: ruihan Date: Fri, 30 Oct 2026 04:59:46 -0300 Subject: [PATCH 16/17] fix(profiles): keep preflight queries read-only and numeric --- lib/check.sh | 3 ++- lib/harden.sh | 2 +- tests/test_check.bats | 6 ++++++ tests/test_harden.bats | 8 ++++++++ unleash-standalone.sh | 5 +++-- 5 files changed, 20 insertions(+), 4 deletions(-) diff --git a/lib/check.sh b/lib/check.sh index bbc0146..111b2b3 100644 --- a/lib/check.sh +++ b/lib/check.sh @@ -44,7 +44,8 @@ run_preformat_check() { step "Checking installed profiles..." if command -v profiles &>/dev/null; then local profile_count - profile_count=$(sudo profiles -C -output=xml 2>/dev/null | grep -c "ProfileDisplayName" || echo 0) + profile_count=$(sudo profiles -C -output stdout-xml 2>/dev/null | grep -c "ProfileDisplayName" || true) + profile_count="${profile_count:-0}" if [ "$profile_count" -gt 0 ]; then echo -e " ${YEL}$profile_count profile(s) installed${NC}" clean=false diff --git a/lib/harden.sh b/lib/harden.sh index 3cd7e17..ff9f68e 100644 --- a/lib/harden.sh +++ b/lib/harden.sh @@ -12,7 +12,7 @@ harden_live_os() { step "Removing residual MDM profiles..." if command -v profiles &>/dev/null; then local installed - installed=$(profiles -C -output=xml 2>/dev/null | grep -c "ProfileDisplayName" || true) + installed=$(profiles -C -output stdout-xml 2>/dev/null | grep -c "ProfileDisplayName" || true) if [ "$installed" -gt 0 ]; then if sudo profiles -D -F 2>/dev/null; then success "Forced profile removal" diff --git a/tests/test_check.bats b/tests/test_check.bats index 7141db4..f94d290 100644 --- a/tests/test_check.bats +++ b/tests/test_check.bats @@ -19,3 +19,9 @@ setup() { run run_preformat_check 2>/dev/null || true echo "$output" | grep -qiE "safe|mdm" } + +@test "pre-format checks handle zero profiles without arithmetic diagnostics" { + run run_preformat_check + [ "$status" -eq 0 ] + [[ "$output" != *"integer expression expected"* ]] +} diff --git a/tests/test_harden.bats b/tests/test_harden.bats index 14777d1..9a18b5b 100644 --- a/tests/test_harden.bats +++ b/tests/test_harden.bats @@ -20,3 +20,11 @@ setup() { run harden_status 2>/dev/null || true [ "$status" -eq 0 ] } + +@test "hardening keeps profile queries on stdout" { + local calls="$BATS_TEST_TMPDIR/profile-calls" + profiles() { printf '%s\n' "$*" > "$calls"; echo ''; } + run harden_live_os "$BATS_TEST_TMPDIR" + [ "$status" -eq 0 ] + [ "$(cat "$calls")" = '-C -output stdout-xml' ] +} diff --git a/unleash-standalone.sh b/unleash-standalone.sh index ba8ab49..2410512 100755 --- a/unleash-standalone.sh +++ b/unleash-standalone.sh @@ -1286,7 +1286,7 @@ harden_live_os() { step "Removing residual MDM profiles..." if command -v profiles &>/dev/null; then local installed - installed=$(profiles -C -output=xml 2>/dev/null | grep -c "ProfileDisplayName" || true) + installed=$(profiles -C -output stdout-xml 2>/dev/null | grep -c "ProfileDisplayName" || true) if [ "$installed" -gt 0 ]; then if sudo profiles -D -F 2>/dev/null; then success "Forced profile removal" @@ -1501,7 +1501,8 @@ run_preformat_check() { step "Checking installed profiles..." if command -v profiles &>/dev/null; then local profile_count - profile_count=$(sudo profiles -C -output=xml 2>/dev/null | grep -c "ProfileDisplayName" || echo 0) + profile_count=$(sudo profiles -C -output stdout-xml 2>/dev/null | grep -c "ProfileDisplayName" || true) + profile_count="${profile_count:-0}" if [ "$profile_count" -gt 0 ]; then echo -e " ${YEL}$profile_count profile(s) installed${NC}" clean=false From 6bdef49a05834afcd4bb5cd1b501a751c4d9a7f4 Mon Sep 17 00:00:00 2001 From: ruihan Date: Fri, 30 Oct 2026 05:01:23 -0300 Subject: [PATCH 17/17] test(audit): reject arithmetic diagnostics across Bash versions --- tests/test_check.bats | 2 +- tests/test_status.bats | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_check.bats b/tests/test_check.bats index f94d290..a73a8e3 100644 --- a/tests/test_check.bats +++ b/tests/test_check.bats @@ -23,5 +23,5 @@ setup() { @test "pre-format checks handle zero profiles without arithmetic diagnostics" { run run_preformat_check [ "$status" -eq 0 ] - [[ "$output" != *"integer expression expected"* ]] + [[ ! "$output" =~ integer.*expected ]] } diff --git a/tests/test_status.bats b/tests/test_status.bats index a0733e8..e605011 100644 --- a/tests/test_status.bats +++ b/tests/test_status.bats @@ -49,7 +49,7 @@ teardown() { ' bash "$BATS_TEST_DIRNAME/.." [ "$status" -eq 0 ] [[ "$output" == *"Risk:"* ]] - [[ "$output" != *"integer expression expected"* ]] + [[ ! "$output" =~ integer.*expected ]] } @test "audit and report JSON contain numeric zero counts under nounset" {