C function (fgets) mitigation

三世轮回 提交于 2019-12-11 16:42:38

问题


I can't understand why taking the input using fgets always gives me "Wrong password" for my program.

However, when I use gets(), like gets(array); it works.

Expected outputs: when the password is wrong, prints "Wrong Passwor" and for correct one, let me see my "access is granted":

#include <stdio.h>
#include <string.h>

int main(void)
{
    int n=15;
    char array[n];
    int pass = 0;

    printf("\n Enter the password : \n");
         fgets(array, n, stdin);

    if(strncmp(array, "password",n))
    {
        printf ("\n Wrong Password \n");
    }
    else
    {
        printf ("\n Correct Password \n");
        pass = 1;
    }
    if(pass)
    {
       /* Now Give root or admin rights to user*/
        printf ("\n Root privileges given to the user \n");
    }
    return 0;
}

回答1:


The point here is, fgets() reads and stores the trailing newline, check the man page for fgets().

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. [...]

You need to remove that trailing newline before the comparison.

You can sanitize the input, using

 array[strcspn(array, "\n")] = 0;

to remove the trailing newline from the input.



来源:https://stackoverflow.com/questions/53262648/c-function-fgets-mitigation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!