I was going through the security issues in C. I could not understand the below code of how it corrupts the stack,
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int chk_perm(){
printf("\n Check Perm \n");
return 2;
}
int main(int argc,char* argv[]){
int fg;
char filename[16];
if(argc != 2){
fprintf(stderr,"Usage : %s filename\n",argv[0]);
exit(1);
}
fg = chk_perm();
strcpy(filename,argv[1]);
if(fg == 0xdeadbeef){
//execute as root or deposit million dollars in bank account
}
else{
//execute as a normal user , deduct $10 from an account
}
return 0;
}
The argv[1] passed may change the value of fg. Its said, that corruption will happen, if argv[1] passed is an entire binary that can cause undesired results can be passed as an argument along with return address.
I could not understand , how the strcpy corrupts the stack check_perm such that the value of the fg gets changed.
My assumption about the program,
When program starts executing, It creates a stack for the main function and put its arguments,return address,local variables onto the stack.So int fg will occupy 4 bytes (08567500 loc)of the stack and filename[16] will occupy next 16 bytes(08567504). Even if the filename is overflowing more than 16 bytes it may corrupt if any local variable was present after it.
So how does the fg gets corrupted due to strcpy(filename,argv[1]);