Simple buffer overflow in C Programming Language | cpuinfo
Posts Simple buffer overflow in C Programming Language
Post
Cancel

Simple buffer overflow in C Programming Language

Overview

This tutorial provides a quick overview of how a buffer overflow occurs in C programs when unsafe functions are used.

Jargon

Buffer
Continuous bytes of data / information stored in memory to temporary use

Pre-requisite installations

None

Exercises

Files for exercise

buffovf.c

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>

int main(int argc, char const *argv[])
{
  unsigned char username[16];
  
  printf("Username:\n");

  scanf("%s", username);

  return 0;
}

Exercise #1: Provide an input big enough to crash the program

Compile buffovf.c using following command. This will generate the binary file with name buffovf.

1
2
gcc -o buffovf buffovf.c --no-stack-protector \
  -mpreferred-stack-boundary=2 -m32 -z execstack
Case 1
Execute the binary file as shown and pass a username with less than 16 bytes. As you see the binary excepts the username and exits sucessfully.
Case 2
Execute the binary file as shown and pass a username with more than 16 bytes. As you see the binary now crashes and throws a segmentation fault.

Below snapshot provides insight on the outcome of both cases.

filecmdoutput

A segmentation fault will occcur when a program attempts to:

  1. access a memory location that it is not allowed to access, or
  2. access a memory location in a way that is not allowed, for example,
    • attempting to write to a read-only location
    • overwrite part of the operating system

Exercise #2: Automate to find the size of input big enough for the program to crash

Another easy mechanism to send input data to a binary file is as follows:

1
2
3
4
5
6
7
python -c "print ('a' * 10)" | ./buffovf

python -c "print ('a' * 16)" | ./buffovf
python -c "print ('a' * 18)" | ./buffovf
python -c "print ('a' * 20)" | ./buffovf
python -c "print ('a' * 22)" | ./buffovf
python -c "print ('a' * 24)" | ./buffovf

filecmdoutput

Note
The buffer username is allocated 16 bytes in the C code. If you observe in the snapshot above, only after 24 bytes of data is sent, the segmentation fault occurs. Analyze the reason on why 8 bytes are additionaly required for a segmentation fault to occur.

Challenges

Challenge FilesDescription
Challenge 1For the given binary manually find out what is the input size that causes the binary to crash
Challenge 2For the challenge 1 write a Python script to automate the finding of input size that causes a segmentation fault

Quiz

Take a quiz to provide your answers to above challenges

This post is licensed under CC BY 4.0 by the author.