-3

i have the following c program. when i enter input as bytebyte it is giving the wrong input due to buffer overflow.

this is the program


#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 
  
int main(void) {
// Use a struct to force local variable memory ordering
struct {
char buff[5];
char perf;
} localinfo;
localinfo.perf = 0;

 
if(strcmp(localinfo.perf, "byte")){
printf ("\n Wrong Password \n");
}
else {
printf ("\n wrong Password\n");
localinfo.perf = 1; // Set a flag denoting correct password
}

//IF password matches
// GIVE root or admin rights to user
if(localinfo.pass){ 
  printf ("\n Congratulations! Root privileges given to the user!\n");
}

return 0;
}

The correct password is byte, if enter byte it works fine. if i enter bytebyte due to bufferoverflow the pass is modified as 1. and user is getting admin privileges.

if enter bytebyte as input output is

wrong password

  • 2
    I would start from the proper formating – 0___________ Feb 05 '22 at 00:53
  • 2
    Since `gets` knows nothing about the size of the buffer, it can write into memory other than the array. In this case `pass` should end up right next to the array, so it gets filled with one of the input chars which is different to 0. You may not write yo `pass` after assigning 0 to it directly, but `gets` does. If you enter enough data, you'll even end up with undefined behaviour... – fabian Feb 05 '22 at 01:01
  • 1
    [Why is the gets function so dangerous that it should not be used?](https://stackoverflow.com/q/1694036/995714) – phuclv Feb 05 '22 at 01:01

2 Answers2

2

Simply never use gets function, It is dangerous and obsolete.

Use fgets instead

fgets(localinfo.buff, sizeof(localinfo.buff), stdin);

To be sure that the whole line was read check if the last character is '\n'. If not assume that something is wrong and wrong password was entered.

0___________
  • 60,014
  • 4
  • 34
  • 74
1

Try this

#include <stdio.h>

#include <string.h>

int main(void) {
  struct {
    char buff[10];
    char pass;
  }
  localinfo;
  localinfo.pass = 0;

  printf("\n Enter the password:\n");
  scanf("%[^\n]s", localinfo.buff);

  if (strcmp(localinfo.buff, "byte")) {
    printf("\n Wrong Password \n");
  } else {
    printf("\n Correct Password\n");
    localinfo.pass = 1;
  }
  if (localinfo.pass) {
    printf("\n Congratulations! Root privileges given to the user!\n");
  }

  return 0;
}
Student369
  • 21
  • 3