#!/usr/bin/perl -w
#
# __copy1__
# __copy2__
#
# usage: validateuser [pam_service]
#
# reads username and password from stdin and validate auth
# using PAM, exits ok (0) if authentication succeded, 1 
# otherwise
#
# Note: you need to be root to validate local users if listed in
# /etc/shadow, due PAM limitations, any other source, like # LDAP,
# works like a charme
#
# run this program using 'sudo' if you need to validate local
# users
#
use strict;
use warnings;

use Authen::PAM;

my $username;
my $password;
my $service	= "other";

# parms check
usage()				if (@ARGV > 1);
$service = shift( @ARGV )	if (@ARGV == 1);

# get input from terminal
#
print( "user: " );
$username = <>;
chomp( $username );

`stty -echo 2>/dev/null`;
print( "password: " );
$password = <>;
chomp( $password );
print( "\n" );
`stty echo 2>/dev/null`;

# calls PAM
#
my( $pamh, $res );


ref ($pamh = new Authen::PAM( $service, $username, \&_my_conv_func)) || exit( 1 );

$res = $pamh->pam_authenticate;

if ($res != PAM_SUCCESS()) {
	print( $pamh->pam_strerror($res) . "\n" );
	exit( 1 );
}
print( "ok\n" );
exit( 0 );


sub _my_conv_func {
	my @res;
	while ( @_ ) {
		my $code = shift;
		my $msg = shift;
		my $ans = "";

		$ans = $username if ($code == PAM_PROMPT_ECHO_ON() );
		$ans = $password if ($code == PAM_PROMPT_ECHO_OFF() );

		push @res, (PAM_SUCCESS(),$ans);
	}
	push @res, PAM_SUCCESS();
	return @res;
}

sub usage {
	die "
usage: validateuser [pam_service]

pam_service defaults to 'other' (plain auth)

";
}

__END__

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version. For
more details read LICENSE in the root of this distribution.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

As per the GPL, removal of this notice is prohibited.
