开发者

buffer overflow correction please

开发者 https://www.devze.com 2023-01-30 22:50 出处:网络
i want to avoid buffer overflow vulnerability in the following program, int main (int argc, char *argv[ ]) {

i want to avoid buffer overflow vulnerability in the following program,

int main (int argc, char *argv[ ]) {    
  int valid=FALSE;     
  char str1[8];     
  char str2[8];      
  next_tag(str1);     
  gets(str2);    
  if (strncmp(str1,str2,8)==0)      
    valid=TRUE;     
  printf("buffer: str1(%s),str2(%s),valid(%d) \n", str1, str2, valid); 
} 

is this the right correction to it in order to fix vulnerability?

int main (in开发者_StackOverflowt argc, char *argv[ ]) {     
  int valid=FALSE;     
  char str1[8];     
  char str2[8];      
  next_tag(str1);     
  fgets(str2);       /* HERE IS THE CHANGE! */
  if (strncmp(str1,str2,8)==0)        
    valid=TRUE;     
  printf("buffer: str1(%s),str2(%s),valid(%d) \n", str1, str2, valid); 
} 


  fgets(str2, 8, STDIN);    

fgets takes three arguments:

str

  • Pointer to an array of chars where the string read is stored.

num

  • Maximum number of characters to be read (including the final null-character). Usually, the length of the array passed as str is used.

stream

  • Pointer to a FILE object that identifies the stream where characters are read from. To read from the standard input, stdin can be used for this parameter.

see here.


The first thing I should point out is why your first implementation has a buffer overflow.

// Allocate a char array that can hold 'max' 8 characters.
char str2[8];

// Ask user for input and stuff it into str2. If the user
// gives us more than 8 characters, we will end up overwriting
// str2 beyond its allocated buffer. 
gets(str2);  

So what we need is a way to tell 'gets', to get no more than 8 characters. fgets helps us solve this. It takes for a parameter, the maximum number of characters to read. Look at Vladimir's post for more details about fgets.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号