Posted: Tue 04 Dec 2012, 16:27 Post subject:
Check user & password in scripts
Checking a match of username and password in a shell program can be tricky. From various sources I have put together below source for a small utility that seems to do the job:
Code:
/* compile with:
* diet gcc chkpswd.c -Os -s -o check_password -lcrypt
*/
#include <stdlib.h>
#include <stdio.h>
#include <pwd.h>
#include <shadow.h>
#include <string.h>
#include <crypt.h>
#include <unistd.h>
#include <libgen.h>
/* example: ./check_password username password && echo "success" || echo "failure"
* returns 0 if username and password in /etc/shadow match - 1 if not.
*/
int check_pass(const char *plainpw, const char *cryptpw) {
return strcmp(crypt(plainpw,cryptpw), cryptpw) == 0;
}
int main(int argc, char **argv) {
if (argc != 3) {
printf("usage:\n\t%s [username] [password]\n", basename(argv[0]));
return 1;
}
if ( ! getuid() == 0) {
printf("You need to be root\n");
return 1;
}
if ( ! getpwnam(argv[1]) ) {
printf("No such user %s\n", argv[1]);
return 1;
}
if ( check_pass(argv[2], (getspnam(argv[1]))->sp_pwdp) ) {
//printf("Seems OK\n");
return 0;
} else {
//printf("NOT OK\n");
return 1;
}
}
amigo: Not sure - think 'getent' only lookup the values and cant see how it would validate a given plain text password for a given user...
I use the 'check_password' in script like below:
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum You cannot attach files in this forum You can download files in this forum