Search code examples
c++visual-studio-2022buffer-overflow

Can't force a buffer overflow into another variable


This is for a homework assignment. I've been given a c++ file that is supposed to demonstrate a buffer overflow error and I need to correct the error. Unfortunately, I can't reproduce the error to begin with. Two local variables are declared right next to each other, presumably with the idea that when the character array is given a value that is too large the overflow will go into the next variable and that will now display incorrectly.

Here is the code that I was given (with some comments removed):

#include <iomanip>
#include <iostream>

int main()
{
  std::cout << "Buffer Overflow Example" << std::endl;

  const std::string account_number = "CharlieBrown42";
  char user_input[20];
  std::cout << "Enter a value: ";
  std::cin >> user_input;

  std::cout << "You entered: " << user_input << std::endl;
  std::cout << "Account Number = " << account_number << std::endl;
}

However, when I type more than 20 characters into the prompt it still returns the full string that I've entered and then returns the correct value for the account_number. My understanding is that the extra characters that I enter should bleed into the account_number.

Under the project properties I've already tried turning off Basic Runtime Checks (under C/C++->Code Generation) and I've turned off Randomized Base Address (under Linker->Advanced). Is there some other setting that I need to change to be able to produce a more predictable buffer overflow?


Solution

  • One way to achieve this would be to place the buffer inside a struct and place a "magic number" after it:

    struct ProtectedBuffer
    {
        char buffer[20];
        unsigned magicNumber = 1234;
    
        bool overflow() {magicNumber != 1234;}
    };
    

    This way, any overflow of the buffer will bleed into the fixed magic number which can be detected.