简体   繁体   English

C 程序使用获取密码来防止缓冲区溢出

[英]C program prevent the buffer overflow using the gets for Password

i have the following c program.我有以下 c 程序。 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.如果我由于缓冲区溢出而输入 bytebyte,则将 pass 修改为 1。并且用户正在获得管理员权限。

if enter bytebyte as input output is如果输入 bytebyte 作为输入 output 是

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.我试图通过 fgets 和 strncmp 解决这个问题,但没有用。

Simply never use gets function, It is dangerous and obsolete.永远不要使用gets function,它既危险又过时。

Use fgets instead改用fgets

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

To be sure that the whole line was read check if the last character is '\n' .为确保已读取整行,请检查最后一个字符是否为'\n' If not assume that something is wrong and wrong password was entered.如果不是,则假设出现问题并且输入了错误的密码。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM