bufbomb 内存炸弹

// assemble.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "stdlib.h"
#include "ctype.h"
#include "malloc.h"
#include <iostream>
#include <fstream>
using namespace std;

/* Like gets, except that characters are typed as pairs of hex digits. 
Nondigit characters are ignored. Stops when encounters newline */ 
char*getxs(char*dest) 
{ 
    int c; 
    int even =1; /* Have read even number of digits */ 
    int otherd =0; /* Other hex digit of pair */ 
    char*sp = dest; 

    std::fstream fs("test.txt",std::fstream::in);
    cout<<fs.fail()<<endl;
    char str[100];
    char buf[2048];
    int i = 0;
    int j = 0;
    memset(str,0,100);
    memset(buf,0,2048);
    while(!fs.eof()){
        fs.getline(str,100);
        memcpy(buf+i,str+12,11);
        buf[i+11] = 0x20;
        i += 12;
    }


    while ((c = buf[j++]) != EOF && c !='\n' && c != 0) { 
        if (isxdigit(c)) { 
            int val; 
            if ('0'<= c && c <='9') 
                val = c -'0'; 
            else if ('A'<= c && c <='F') 
                val = c -'A'+10; 
            else 
                val = c -'a'+10; 
            if (even) { 
                otherd = val; 
                even =0; 
            }
            else { 
                *sp++= otherd *16+ val; 
                even =1; 
            } 
        } 
    } 
    *sp++='\0'; 
    return dest; 
} 

/* $begin getbuf-c */ 
int getbuf() 
{
    char *buf = (char*) alloca(16); 
    getxs(buf); 
    return 1; 
} 

void test() 
{ 
    int val;
    printf("Please enter hex string:\n");
    val = getbuf();
    printf("Result is %d", val);
} 
/* $end getbuf-c */ 

int _tmain(int argc, _TCHAR* argv[])
{
    test();
    system("pause");
    return 0;
}

这个题目主要是对栈帧结构的分析,通常情况下,vc生成的代码会进行栈溢出检查,比如定义char buf[16], 这16字节的栈空间是不能超出的,超出了就会报错,因此采用了 alloca的方式在栈中分配一块内存,这样编译器貌似不会加入栈安全检查的代码,

本来想加入可执行代码来着,但是因为cs , 和ss不一致,因此在栈中写入一些机器码不会被执行,跳转地址是可以修改的,同时因为将要输出的结果也是从栈中获取(如果是从eax中获取就没办法了),因此可以将那以部分内存通过stack overflow覆写,从而达到控制输出结果的目的,这种方式比较简单,没有涉及到执行自己的代码,只是修改了返回地址,改写了目标栈帧, 网上一些例子是执行了机器码的,这实际上是以cs ss两个选择子的値一样为前提的

posted @ 2016-04-29 10:00  SKY_VIEW  阅读(392)  评论(0)    收藏  举报