usustarr
usustarr

Reputation: 418

how to redirect a file to gets() in C

I am using gets() to read a password. Is there a risk of someone redirecting a file when my program is waiting for the password and causing a buffer overflow, eventually doing something bad?

I was told this can be done, but I was not able to redirect a file as the input to my program. Can someone show me how to redirect a file as the password?

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

int checkPassword(void) 
{
    char password[16];
    bzero(password, 16);
    printf("Enter password: ");
    gets(password);
    if (strcmp(password, "correctPassword")==0)
        return 1;

    return 0;
}

int main(void)
{
    if (checkPassword()) {
        printf("Correct password\n");
    } 
    else {
        printf("Access denied!\n");
    }
}

Upvotes: 0

Views: 106

Answers (2)

user2969932
user2969932

Reputation: 86

A buffer overflow can be caused by exploiting the gets function. Use the fgets function instead:

fgets(password, sizeof(password), stdin);

The viability of such an attack depends on the system you are using, if there are any stack protection mechanisms enabled, and - of course - how sophisticated the attack is.

Upvotes: 1

Deduplicator
Deduplicator

Reputation: 45654

Handle redirection is mostly a shell question. Most would do that with eg: myprogram < myinputfile.

Also, in program, you can reopen any stream you want, to a completly unrelated file.

Next, never use gets(): It is insecure, and cannot be used securely without having complete control over input.

Guess I should try a 16 char password on your system sometime.

Upvotes: 1

Related Questions