Check user & password in scripts

For discussions about programming, programming questions/advice, and projects that don't really have anything to do with Puppy.
Post Reply
Message
Author
goingnuts
Posts: 932
Joined: Sun 07 Dec 2008, 13:33
Contact:

Check user & password in scripts

#1 Post by goingnuts »

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: Select all

/* 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;	
	}
}
Attachments
check_password.gz
static build of check_password
(16.73 KiB) Downloaded 425 times

jamesbond
Posts: 3433
Joined: Mon 26 Feb 2007, 05:02
Location: The Blue Marble

#2 Post by jamesbond »

Can't resist ... :twisted:

Code: Select all

#!/bin/dash
for p in $(cat one-million-words-dictionary); do 
    check_password root "$p" && echo "root password is $p" && break
done
Fatdog64 forum links: [url=http://murga-linux.com/puppy/viewtopic.php?t=117546]Latest version[/url] | [url=https://cutt.ly/ke8sn5H]Contributed packages[/url] | [url=https://cutt.ly/se8scrb]ISO builder[/url]

goingnuts
Posts: 932
Joined: Sun 07 Dec 2008, 13:33
Contact:

#3 Post by goingnuts »

Can't resist ... :twisted:
Me neither... :)

Code: Select all

#!/bin/dash
whoami | grep root && su spot
check_password root woofwoof

amigo
Posts: 2629
Joined: Mon 02 Apr 2007, 06:52

#4 Post by amigo »

Couldn't that be done using 'getent'?

goingnuts
Posts: 932
Joined: Sun 07 Dec 2008, 13:33
Contact:

#5 Post by goingnuts »

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:

Code: Select all

#!/bin/sh
echo -n "Enter username:"
read username
echo -n "Enter password:"
read password

check_password $username $password && \
echo "Access granted..." || echo "Access denied..."
as part of a rewrite of mu´s minixdm

Post Reply