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 pass;
} localinfo;
localinfo.pass = 0;
printf("\n Enter the password:\n");
gets(localinfo.buff);
if(strcmp(localinfo.buff, "byte")){
printf ("\n Wrong Password \n");
}
else {
printf ("\n Correct Password\n");
localinfo.pass = 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
Congratulations! Root privileges given to the user
but if password is wrong user should not get admin rights. currently he is getting because of bufferoverflow how to fix this ?
i tried to fix this through the fgets and strncmp but no use.
CodePudding user response:
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.
CodePudding user response:
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;
}
