CWE 190 - Integer Overflow or Wraparound

Disclaimer
  • The code provided is for **educational purposes** only and should not be used in a **production environment** without proper review and testing.

  • The provided code should be regarded as **best practice**. There are also several ways to remediate the Vulnerabilities.

  • The code provided **may contain vulnerabilities** that could be exploited by attackers, and is intended to be used as a learning tool to help improve security awareness and best practices.

  • The mitigations provided are intended to address **specific vulnerabilities** in the code, but may not be effective against all potential attack vectors or scenarios.

  • The code provided is not **guaranteed to be secure or free** from all vulnerabilities, and should be reviewed and tested thoroughly before being used in a production environment.

  • The code provided is **not a substitute for professional security** advice or guidance, and users should consult with a qualified security professional before implementing any security measures.

  • The authors and contributors of the code provided **cannot be held responsible** for any damages or losses resulting from the use of this code.

  • The code provided is provided "as is" without any warranties, express or implied, including but not limited to the implied warranties of merchantability and fitness for a particular purpose.

  • We do not have any sponsors or financial interests in any specific products or services, and the information provided is based solely on our own knowledge and experience.

  • The vulnerable and mitigated code samples provided on our platform are generated with the help of AI and sourced from the internet. We have made every effort to ensure that the code is accurate and up-to-date, but we cannot guarantee its correctness or completeness. If you notice that any of the code samples belong to you and you wish for it to be removed, please contact us and we will take appropriate action. We also apologize for any inconvenience caused and are committed to giving appropriate credit to the respective authors.

About CWE 190

Integer Overflow or Wraparound

This vulnerability occurs when an integer variable exceeds its maximum value, causing it to wrap around and start again from the minimum value, potentially leading to unexpected or malicious behavior.

Impact

  • Buffer Overflow

  • Memory Corruption

  • Data corruption or Manipulation.

  • Denial of Service (DoS)

Example with Code Explanation

C

Let us consider an example case and understand the CWE-190 with context of Vulnerable code and Mitigated code.

Vulnerable Code

#include <stdio.h>
#include <stdlib.h>

int main() {
  int arr[10];
  int index = 0;
  int input = 0;

  // read integers from user input and store them in the array
  while (scanf("%d", &input) == 1) {
    arr[index] = input;
    index++;
  }

  // process the array
  int sum = 0;
  for (int i = 0; i <= index; i++) {
    sum += arr[i];
  }

  printf("The sum of the numbers is: %d\n", sum);

  return 0;
}

The above program reads integers from user input and stores them in an array. Then, it attempts to compute the sum of all the integers in the array by looping through the array and adding each element to a sum variable.

The loop condition (i <= index) allows the loop to continue executing beyond the end of the array, causing an integer overflow vulnerability. If an attacker provided a large enough input, the index variable could become greater than the size of the array, causing the loop to access memory outside of the bounds of the array.

  • Some of the ways the vulnerable code can be mitigated is:

    • Use a data type with a larger range, such as unsigned long long instead of unsigned int.

    • Check for integer overflow before performing any arithmetic operation on an integer.

    • Use libraries or built-in functions that handle arithmetic operations safely, such as strtol() or strtoull().

    • Test the code with large input values and boundary cases to ensure that integer overflow does not occur.

    • Avoid user input if it is not needed.

Mitigated Code

#include <stdio.h>
#include <stdlib.h>

#define SIZE 10

int sum_array(const int arr[], size_t len);

int main(void) {
  int arr[SIZE] = {0};
  size_t i;

  for (i = 0; i < SIZE; i++) {
    arr[i] = i;
  }

  int sum = sum_array(arr, SIZE);
  printf("The sum of the array is: %d\n", sum);

  return 0;
}

int sum_array(const int arr[], size_t len) {
  size_t i;
  int sum = 0;

  for (i = 0; i < len; i++) {
    if (arr[i] > INT_MAX - sum) { // check for potential overflow
      printf("Integer overflow detected!\n");
      exit(EXIT_FAILURE);
    }
    sum += arr[i];
  }

  return sum;
}
  • The Mitigated Code does the following:

    • Perform explicit range checking to detect potential integer overflow, by checking if the current element added to the running sum is greater than INT_MAX.

    • If a potential overflow is detected, terminate the program with an error message using exit().

    • USer input is eliminated.

C++

Vulnerable Code

#include <iostream>

void allocate_memory(size_t size) {
  char* buffer = new char[size];
  std::cout << "Allocated " << size << " bytes" << std::endl;
  delete[] buffer;
}

int main() {
  size_t size = 4000000000; // 4 GB
  allocate_memory(size);
  return 0;
}

In this code, the allocate_memory function dynamically allocates memory using the new operator with the char data type, and then deallocates it using the delete[] operator.

However, the size parameter is set to an integer value that is larger than the maximum size that can be allocated on some systems, resulting in an integer overflow or wraparound vulnerability. This can cause the program to allocate less memory than expected, leading to unexpected behavior or crashes.

  • Some of the ways the Vulnerable code can be mitigated is:

    • Input validation and sanitization: Validate input data and sanitize it to ensure that only valid data is processed by the application. This includes checking that input data is within acceptable bounds, and rejecting data that could result in integer overflow or wraparound.

    • Use of safe integer operations: Use safe integer operations, such as those provided by the programming language, that automatically detect and prevent integer overflow or wraparound.

    • Range checking and error handling: Perform range checking on integer values and implement error handling mechanisms to prevent integer overflow or wraparound.

    • Type checking and conversion: Use appropriate data types and ensure that conversions are done correctly to avoid integer overflow or wraparound.

Mitigated Code

#include <iostream>
#include <cstdint>
#include <stdexcept>
#include <memory>
#include <vector>

void allocate_memory(size_t size) {
  // limit the maximum size to 1 GB
  const size_t MAX_SIZE = 1073741824;
  if (size > MAX_SIZE) {
    throw std::invalid_argument("Size is too large");
  }
  // use a smart pointer and a vector to manage memory
  std::unique_ptr<std::vector<char>> buffer = std::make_unique<std::vector<char>>(size);
  std::cout << "Allocated " << size << " bytes" << std::endl;
}

int main() {
  size_t size = 4000000000; // 4 GB
  try {
    allocate_memory(size);
  } catch (const std::invalid_argument& e) {
    std::cerr << "Error: " << e.what() << std::endl;
    return 1;
  }
  return 0;
}
  • The Mitigated code does the following:

    • Limits the maximum size of memory that can be allocated to 1 GB, which helps prevent integer overflow and wraparound.

    • It uses a smart pointer and a vector to manage memory, which helps prevent memory leaks and buffer overflows.

    • It throws an exception if the size is too large, which helps prevent unexpected program behavior and crashes.

    • It uses C++ standard library classes and functions that are designed to be safer and more secure than raw pointers and arrays.

JAVA

Vulnerable Code

import java.util.Scanner;

public class IntegerOverflow {

  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter two positive integers:");
    int x = scanner.nextInt();
    int y = scanner.nextInt();
    scanner.close();
    // assume x and y are positive
    int z = x * y; // potential integer overflow
    System.out.println("The product of x and y is: " + z);
  }
}

This code takes two user inputs and multiplies them without checking their values. If the product of x and y exceeds the maximum value of an int (2^31 - 1), then an integer overflow will occur and the result will be incorrect. A malicious user could exploit this vulnerability to cause unexpected behavior or bypass security checks

  • Some of the ways the Vulnerable code can be mitigated is:

    • Use appropriate data types and arithmetic operations that can handle large values without wrapping or overflowing.

    • Validate the user input and ensure that it does not exceed the expected range or size. For example, use input sanitization, input validation, or input filtering techniques to reject or modify inputs that are too large or too small.

    • Check for potential overflow or wraparound before performing a calculation that could produce one.

    • Use libraries or frameworks that provide built-in protection against integer overflow or wraparound. For example, use BigInteger or BigDecimal classes in Java, or SafeInt class in C++.

Mitigated Code

import java.util.Scanner;
import java.math.BigInteger;

public class IntegerOverflow {

  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter two positive integers:");
    BigInteger x = scanner.nextBigInteger();
    BigInteger y = scanner.nextBigInteger();
    scanner.close();
    // validate the input and ensure that it is positive
    if (x.signum() < 0 || y.signum() < 0) {
      System.out.println("Invalid input: negative numbers are not allowed");
      return;
    }
    // use BigInteger class to perform the multiplication
    BigInteger z = x.multiply(y); // no integer overflow or wraparound
    System.out.println("The product of x and y is: " + z);
  }
}
  • The Mitigated code does the following:

    • The code uses the BigInteger class which provides automatic handling of integer overflow and wraparound issues.

    • The code also validates the input and ensures that the input is positive to prevent any negative values that can cause integer overflow or wraparound issues.

References

Integer overflow: How does it occur and how can it be prevented? | WeLiveSecurity

Integer Overflow Attack and Prevention | SecureCoding.com

Integer Overflow Prevention in C

Last updated

Was this helpful?