/* * user-test.c - ask a user for their password, and compare it to * the password, as taken from the "/etc/passwd" file. */ #include /* crypt(), etc. */ #include /* getpass(), getpwnam(). */ #include /* strcmp(), etc. */ #include #include #define _XOPEN_SOURCE int main() { /* buffers for reading in the user name and the password. */ char user[21]; char* password; /* storing the encrypted password, and the salt. */ char* encrypted_password; char salt[2]; /* user's "/etc/passwd" entry. */ struct passwd* user_info; /* prompt the user for a user name. */ printf("User name: "); fflush(stdout); /* flush the prompt to make sure the user sees it. */ fgets(user, 20, stdin); /* fgets() stores also the new-line that the user typed in. so we */ /* need to locate the new-line character, and truncate it. */ if (strchr(user, '\n')) (*(strchr(user, '\n'))) = '\0'; /* prompt the user for their password. the getpass() function */ /* prints the given prompt, turns off echo (so the password */ /* typed won't be seen on screen), and returns the string that */ /* the user types. */ password = getpass("Password: "); /* find the user's encrypted password, as stored in "/etc/passwd". */ user_info = getpwnam(user); if (!user_info) { printf("login incorrect.\n"); return 1; } /* take the salt as stored in the password field of the user. */ strncpy(salt, user_info->pw_passwd, 2); /* encrypt the given password using the found "salt". */ encrypted_password = crypt(password, salt); /* compare the results of crypt, with the user's stored password field. */ if (strcmp(user_info->pw_passwd, encrypted_password) != 0) { printf("login incorrect.\n"); return 1; } /* authentication succeeded... */ printf("login successful.\n"); return 0; }