使用无符号的int作为数组索引可能导致缓冲区溢出?
我有这个代码,必须在其中找到安全漏洞。
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 = -1
,v = 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
摘要一些评论和一些添加的内容
首先,该代码是错误的。
scanf
的参数需要是指示:是的,从技术上讲,这是正确的,这也是真的,这可能会导致界限访问数组。但是,即使您更改为未签名,也没有什么可以阻止攻击者简单地键入任何数字,包括任何数字
(unsigned)-1
都将在特定系统上。解决此安全问题的正确方法是检查输入的数字是否在范围内[0,49]。如果您使用未签名的数字,则可以跳过检查是否低于零,出于明显的原因。但是您仍然需要进行范围检查。
Summary of some comments and some additions
Firstly, the code is wrong. The arguments to
scanf
needs to be pointers: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.