// stack_smash_test.c
// demonstrate SSP behaviour
// Georg Kapeller, Michael Gissing
// trivial code - no copyrigth

#include <stdio.h>

void smash_int_endlessly();
void segmentation_fault();
void smash_stack_affecting_other_vars();
void smash_stack_affecting_local_vars();


int main()
{
  
  //Tested on pluto with gcc 4.1.2, compiling: gcc -o stack_smash_test stack_smash_test.c
  //-fstack-protector-all does make an important difference for testcase-results
  
  //Also tested on local ubuntu with gcc 4.1.3, the error scenarios where different, also
  //leading to different problems (behaviour was not random (as on pluto), but only
  //unexpected for the novice programmer). -fstack-protector-all did not make a difference
  //but didn't protect so well either (some of the testcases where undetected)


  int a = 255, b = 255, c = 255;
  
  // *** smashes the stack by overwriting position counter
  //     causing an endless loop -- (sometimes) dedected
  //smash_int_endlessly();

  // *** writes beyond the stack-segement -- dedected
  //segmentation_fault();

  // *** writes on the stack randomly affecting other vars -- dedected
  //     just run the programm a couple of times...
  //smash_stack_affecting_other_vars();

  // *** corrupts the stack by writing some integers into the stack-areas 
  //     which correspond to other (local) variables
  //smash_stack_affecting_local_vars();

  printf("%d %d %d should be 255 255 255\n", a, b, c);
  return 0;
}

void smash_int_endlessly()
{
  int vector[10];
  int position = 0;

  for(position = 0; position <= 10; position++) //10, off by 1!
  {
    printf("[INT] Position: %d\n", position);
    vector[position] = 0;
  }
}

void segmentation_fault()
{
  char string[10];
  int position = 0;

  string[16] = 10;
}

void smash_stack_affecting_other_vars()
{
  char string[10];
  int position = 0;

  string[14] = 10;
}

void smash_stack_affecting_local_vars()
{
  char string[10];
  int position = 0;

  for(position = 0; position < 11; position++) //4
  {
    printf("[CHR] Position: %d\n", position);
    string[position] = 15;                   //*5
  }

  printf("position: %d, when it should be 11\n", position);
}


