Working with Passwords
One traditional route to user and password information was through the getpw* family of functions. However, those functions are not ideal for working with systems that support multiple directories (flat files, NetInfo, LDAP, etc.). Also, in the interest of thwarting dictionary attacks against password files
, many operating systems have stopped returning encrypted passwords
through those APIs. Many Unix and Linux systems simply return an "x" when you invoke a function like getpwnam(). However, those systems can return an encrypted password through functions like getspnam(), which consult shadow password entries and can generally be invoked by the root user only. Example 10-1 shows the typical usage of such an API, where the user enters her plaintext password, and the program encrypts it and then compares it against the encrypted password stored in the system.
/* * getpw* no longer returns a crypted password. * * Compile with gcc checkpass.c -o checkpass * Run with: ./checkpass */ #include <pwd.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { const char *user = NULL; struct passwd *pwd; /* Set the user name if it was supplied on the command * line. Bail out if we don't end up with a user name. */ if (argc == 2) user = argv[1]; if(!user) { fprintf(stderr, "Usage: checkpass <username>\n"); exit(1); } /* Fetch the password entry. */ if (pwd = getpwnam(user)) { char *password ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access