简体   繁体   English

安全漏洞:这段代码有什么错误?

[英]Security Vulnerability : What is the error in this piece of code?

I was reading this book on my own , just for fun , and came across the following question : 我只是为了娱乐而独自阅读这本书 ,遇到了以下问题:

This code has a security vulnerability ; 此代码存在安全漏洞; Can you find and fix it? 您可以找到并修复它吗? :

  bool isValidAddition(unsigned short x, unsigned short y) 
 {
     if(x + y < x)
         return false;
     else 
         return true;
 }

Can someone help me , recognize the vulnerability ? 有人可以帮助我,识别此漏洞吗?

We know that the following points are true as per the C Standard : 我们知道,根据C Standard ,以下几点是正确的:

  • sizeof(short) <= sizeof(int) <= sizeof(long) sizeof(short)<= sizeof(int)<= sizeof(long)
  • sizeof(short) >= 2 bytes , sizeof(int) >= 2 bytes, sizeof(long) >= 4 bytes sizeof(short)> = 2个字节,sizeof(int)> = 2个字节,sizeof(long)> = 4个字节
  • There is an implicit integer promotion of operand data types used in arithmetic expressions which is done by the compiler 算术表达式中使用了操作数数据类型的隐式整数提升,这是由编译器完成的

So in the code snippet above do the following : 因此,在上面的代码段中,请执行以下操作:

Change 更改

if(x + y < x) 

to

if((unsigned short)(x + y) < x) 

This will worrk if int is 4 (or >2) bytes 如果int是4(或> 2)个字节,这将很麻烦

Hope this helps :) 希望这可以帮助 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM