How a buffer overflow can change the content of a local variable? | cpuinfo
Posts How a buffer overflow can change the content of a local variable?
Post
Cancel

How a buffer overflow can change the content of a local variable?

Objectives

The purpose of this tutorial is to establish the fact that an external input being stored in a buffer can change the contents of another local variable in vicinity.

Jargon

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

Pre-requisite installations

None

Exercises

Files for exercise

buffovfvar.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char const *argv[])
{
  volatile int flag = 0;
  unsigned char username[16];

  if(argc > 1) {
    strcpy(username, argv[1]);
  } else {
    printf("Usage: buffovfvar username\n");
    exit(EXIT_FAILURE);
  }

  if (flag == 0) {
    printf("Flag is zero: %d\n", flag);
  } else {
    printf("Flag is non-zero: %d\n", flag);
  }
  return 0;
}
1
2
gcc -o buffovfvar buffovfvar.c --no-stack-protector\
 -mpreferred-stack-boundary=2 -m32 -z execstack

Exercise 1: Overflow the buffer such that the variables in vicinity are in our control

After compiling the program bufferovfvar.c, lets execute it with two set of inputs as follows:

InputValueDescription
Input 1aaaaaaaaaaaaaaaab16 bytes of a followed by 1 byte of character b
Input 2aaaaaaaaaaaaaaaabb16 bytes of a followed by 2 bytes of character bb

Below is the outcome when the we execute the binary with Input 1 and Input 2 filecmdoutput

When we give the first Input 1 the flag gets printed as value 98 decimal. The following snapshot validate the results. For quick reference of ascii chart type the following command:

1
man ascii

filecmdoutput

Look at the snapshot below to understand why the flag variable has the decimal value 25186 when we pass the second Input 2 to the binary.

filecmdoutput

Conclusion

Thus this proves that we are able to control the value of variables in vicinity of our buffer.

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