Buffer Overflows

A buffer overflow occurs when a program tries to write too much data in a fixed length block of memory (a buffer). Buffer overflows can be used by attackers to crash a web-server or execute malicious code.

A buffer is a block of contiguous memory used to hold data. High-level languages will check the length of a buffer before writing to it, but low-level languages like C, C++ and Assembly require the application itself to do this type of checking.

Take a look at this very simple C program that does not check the length of the input. Try entering a username that is longer than 8 characters and watch what happens.

Extra data that overflows a buffer will will be written into the nearby memory space, and will often crash the application. Under some circumstances, an attacker will be able to sneak their own code into the overflowed data, and have this “shellcode” executed within the vulnerable application.

One common approach is to fill as much of the program’s memory space as possible with no-op (“no operation”) instructions then place the injected code at the end. If the progam’s execution context lands on any of the no-op codes, it will skip to the next no-op, then the next, and so on, until it finally executes the injected code.

Most languages used to write web-code - like Python, Ruby, Node, Java and .NET - used “managed memory”, and are immune to buffer overflow attacks.

However web-servers, language runtimes, and operating systems are frequently written in low-level languages, and can exhibit the vulnerability. The fact that 80% of the web is running on one of the four web-servers means anytime a vulnerability is discovered, it can be widely exploited!

Let’s learn how to protect against buffer overflows!


try {
   String[] array = { "a", "b", "c" };
   array[25] = "z";
catch (ArrayIndexOutOfBoundsException e) {
   // Attempts to overflow the buffer will raise an error in Java.
void askForUsername()
  // Buffer can only hold 8 characters!
  char buffer[8];

  printf("Enter supply your username:\n");
  scanf("%s", buffer);
  printf("You entered: %s\n", buffer);

int main()
  while(1) askForUsername();

  return 0;
Running: "oops.c"
Enter supply your username: