#include <stdio.h>
#include <string.h>
#define SRC_BUFF_SIZE 32
#define DST_BUFF_SIZE 8
int tempfn1(char *p)
{
printf("p %p\n", p);
return 0;
}
int tempfn(char *ip, int size)
{
char pttt[DST_BUFF_SIZE];
printf("ip %p\n", ip);
tempfn1(ip);
// ERROR - copying more data to a local buffer of 4 bytes
//memcpy(pttt, ip, size); // This will lead to stack corruption as
// the size exceeds the size of destination
// IDEALLY the copy should be done with min of size of destination buffer
// or source size rather than source size...
// anyways dest can hold only the size so it is better to crop the buffer
// than to crash due to overflow.
// proper call is as follows
#define MIN(a,b) (((a) < (b)) ? (a) : (b))
memcpy(pttt, ip, MIN(size, DST_BUFF_SIZE));
printf("ip %p\n", ip);
tempfn1(ip);
return 0;
}
int main()
{
char ip[SRC_BUFF_SIZE] = {0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2,
0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2,
0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2,
0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2 };
tempfn(ip, SRC_BUFF_SIZE);
return 0;
}
This a sample program to avoid stack corruption. Is there any other function to check length of destination as well as the source inorder to avoid stack corruption?
The concept which you are pointing to doesn’t apply only to stack corruption. It is applied in general to avoid memory overflow. A memory overflow can lead to corruption of stack when used with stack variable, or heap when used with heap variable. Basically it leads to undefined behavior.
The best way to avoid this is to:
The following two links about Secure Coding Guidelines and Practices might be of some help:
http://www.atsec.com/downloads/pdf/secure-coding-guidelines.pdf
https://www.securecoding.cert.org/confluence/display/seccode/Top+10+Secure+Coding+Practices