问题
I have a program written in C running on a embedded Linux, sometimes it want to check the password of a system user.
- If I can get the crypt salt of /etc/passwd, I can use crypt() to check the correction of user password.
- Is there any script of shell can help me check the password? Such as check_passwd username password, then it return a value for correct or incorrect? Thanks!
回答1:
As suggested above, the correct way to handle this is to use pluggable authentication modules. You have to add libpam to whatever embedded linux you're using, but this is generally easy enough (buildroot provides a linux-pam package, for example).
回答2:
See Given a linux username and a password how can I test if it is a valid account? for how to go about checking if a password given by a user is valid for that user.
回答3:
I had been solving the same task recently. Here is an example of C function (link with -lcrypt). Note that you need to have read permissions for files /etc/passwd and /etc/shadow.
#include <sys/types.h>
#include <pwd.h>
#include <shadow.h>
#include <crypt.h>
#include <string.h>
#include <stdio.h>
/// @return 0 - password is correct, otherwise no
int CheckPassword( const char* user, const char* password )
{
struct passwd* passwdEntry = getpwnam( user );
if ( !passwdEntry )
{
printf( "User '%s' doesn't exist\n", user );
return 1;
}
if ( 0 != strcmp( passwdEntry->pw_passwd, "x" ) )
{
return strcmp( passwdEntry->pw_passwd, crypt( password, passwdEntry->pw_passwd ) );
}
else
{
// password is in shadow file
struct spwd* shadowEntry = getspnam( user );
if ( !shadowEntry )
{
printf( "Failed to read shadow entry for user '%s'\n", user );
return 1;
}
return strcmp( shadowEntry->sp_pwdp, crypt( password, shadowEntry->sp_pwdp ) );
}
}
来源:https://stackoverflow.com/questions/17499163/how-to-check-password-in-linux-by-using-c-or-shell