Search code examples
c++linuxsecurityinteger-overflow

Can the C++ sizeof() function be used to prevent integer overflows?


I'm building mathematics functions that I plan to use for cryptography.

Your algorithm is useless if the code is vulnerable to exploitation. Buffers are fairly easy to protect against overflows; but what about integers?

I won't share my Galois functions but here is one of my normal addition functions:

/**/
private:
    bool ERROR;
    signed int ret;

    void error(std::string msg){
            ERROR = true;
            std::cout<<"\n[-] "<<msg<<std::endl;
    }
/**/
public:
signed int add(signed int a, signed int b){
                if(sizeof(a) > sizeof(signed int) || sizeof(b) > sizeof(signed int) || sizeof(a+b) > sizeof(signed int)){
                        error("Integer overflow!");
                        ERROR = true;
                        ret = 0;
                        return ret;
                }else{
                        ERROR = false;
                        ret = a + b;
                        return ret;
                }
                error("context failure");
                ret = 0;
                ERROR = true;
                return ret;
        }

Is the if conditional enough to prevent malicious input? If not, how would I fix this vulnerability?


Solution

  • So I've found my answer.

    I've decided to use the following if logic to prevent an integer overflow:

    if((a >= 2000000000 || a <= -2000000000) ||
      (b >= 2000000000 || b <= -2000000000) || 
      ((a+b) >= 2000000000 || (a+b) <= -2000000000)){
    

    After running some tests i was able to confirm that the integer loops back around into the negative numbers.

    Since I'm working with finite fields, I can expect that normal input from the program won't get near 2 million while also ensuring that overflows are handled.

    If outside of the bounds, exit.

    ~edit: Fixed logic error