使用无符号的int作为数组索引可能导致缓冲区溢出?

发布于 2025-02-04 12:53:54 字数 685 浏览 6 评论 0原文

我有这个代码,必须在其中找到安全漏洞。

win() {
    printf("Congratulations!");
}
setter(unsigned int i, int v, int * a) {
    a[i] = v;
}

main() {
    int i, v;
    int a[50];
    puts("i");
    scanf("%d", i);
    puts("v");
    scanf("%d", v);
    setter(i, v, a)
}

在Internet上阅读,我发现,当从int转换为未签名的INT发生时,如果INT为负数,则将转换为一个非常高的未签名INT。因此,此代码中的漏洞可能是由于此转换造成的,该转换是在setter中在main函数中调用的。因此,攻击者可以给出以下输入:i = -1v = 40,他将访问内存的一部分,该内存不保留到缓冲区a等等,在setter函数中,攻击者将能够覆盖重要值。例如,攻击者可以用win函数的地址覆盖返回地址,以便在setter返回时执行win。我对吗?

I have this code in which I have to find security vulnerabilities.

win() {
    printf("Congratulations!");
}
setter(unsigned int i, int v, int * a) {
    a[i] = v;
}

main() {
    int i, v;
    int a[50];
    puts("i");
    scanf("%d", i);
    puts("v");
    scanf("%d", v);
    setter(i, v, a)
}

Reading on the Internet, I've found that when a conversion from an int to an unsigned int takes place, if the int is a negative number, it will be converted into a very high unsigned int. So, probably the vulnerabilty in this code is due to this conversion which takes place when setter is called in the main function. So, an attacker could give the following input: i=-1, v=40 and he will access to a part of the memory which isn't reserved to the buffer a and so, in the setter function, the attacker will be able to overwrite important values. For example, the attacker could overwrite the return address with the address of the win function in order to execute win when setter returns. Am I right?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

年华零落成诗 2025-02-11 12:53:54

摘要一些评论和一些添加的内容

首先,该代码是错误的。 scanf的参数需要是指示:

scanf("%d", &i); // Note the &

如果int是负数,则将转换为非常高的无符号int。

是的,从技术上讲,这是正确的,这也是真的,这可能会导致界限访问数组。但是,即使您更改为未签名,也没有什么可以阻止攻击者简单地键入任何数字,包括任何数字(unsigned)-1都将在特定系统上。

解决此安全问题的正确方法是检查输入的数字是否在范围内[0,49]。如果您使用未签名的数字,则可以跳过检查是否低于零,出于明显的原因。但是您仍然需要进行范围检查。

Summary of some comments and some additions

Firstly, the code is wrong. The arguments to scanf needs to be pointers:

scanf("%d", &i); // Note the &

if the int is a negative number, it will be converted into a very high unsigned int.

Yes, this is technically true, and it's also true that this may lead to accessing the array out of bounds. However, even if you change to unsigned, there is nothing preventing the attacker from simply typing any number, including whatever the number (unsigned) -1 will be on the particular system.

The correct way of solving this security issue is to check that the inputted number are in the range [0,49]. If you use an unsigned number, you may skip checking if it's below zero for obvious reasons. But you still need to do a range check.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文