#!/usr/bin/perl
use strict;
use warnings;
use LWP::UserAgent;
use LWP::Protocol::https;
use Digest::SHA qw( hmac_sha256_hex );
use MIME::Base64 qw( encode_base64 );

my $yubico_id = '16';
my %yubikeys = (
	# username          #yubikey ID
	'yubikey'	=> "vvaabbccddee",
);

$| = 1;

## Generate the auth-token for use after the OTP has worked.
sub generate_token($) {
	my $time = shift;
	my $to_auth = $time . '-' . $ENV{'common_name'} . '-' . $ENV{'ifconfig_pool_remote_ip'};
	my $secret = $ENV{'trusted_ip'} . '-' . $ENV{'daemon_start_time'} . '-' . $ENV{'daemon_pid'};
	my $digest = encode_base64(hmac_sha256_hex($to_auth, $secret), "");
	return $digest;
}

if ( $ENV{'script_type'} eq "user-pass-verify" ) {
	my $auth_file = $ARGV[0];

	## Read the auth file.
	open my $fh, '<', $auth_file;
	chomp(my @lines = <$fh>);
	close $fh;

	my $username = $lines[0];
	my $password = $lines[1];

	## Ensure we have a valid entry for the expected username.
	if ( ! defined( $yubikeys{$username} ) ) {
		print "No yubikey enabled for $username\n";
		exit 1;
	}

	## If we have the start of a yubikey, validate the OTP against yubico.
	if ( $password =~ m/^${yubikeys{$username}}/ ) {
		## Check the yubikey entry is valid.
		print "Attempting Yubikey authentication for user: $username\n";
		my $ua = LWP::UserAgent->new;
		$ua->timeout(10);
		my $res = $ua->get( "https://api.yubico.com/wsapi/verify?id=$yubico_id&otp=$password" );
	
		## Only go further if the request was successful.
		if ( ! $res->is_success ) {
			print "Error querying the YubiCo Servers: " . $res->status_line . " - " . $res->decoded_content . "\n";
			exit 1;
		}

		## Pull out the status returned from YubiCo.
		my $result = "";
		if ( $res->decoded_content =~ m/status=(\w+)/ ) {
			$result = $1;
		}

		## Allow access on ONLY an OK response.
		if ( $result eq "OK" ) {
			print "Yubikey authentication successful for user: $username\n";
			exit 0;
		} else {
			print "Yubikey authentication for user $username failed with result: $result\n";
			exit 1;
		}
	}

	## We may have a token, not an OTP... Check.
	if ( $password =~ m/^\d{10}:/ ) {
		print "Performing token authentication for $username\n";
		my ($time, $token) = split(/:/, $password);
		my $digest = generate_token($time);
		if ( $digest eq $token ) {
			print "Token authentication successful for user: $username\n";
			exit 0;
		} else {
			print "Token authentication failed for user: $username\n";
			exit 1;
		}
	}

	## Fall back to an authentication failed error.
	print "Authentication failed for user $username\n";
	exit 1;
} 

## Handle generation of the auth-token to be pushed to the client.
elsif ( $ENV{'script_type'} eq "client-connect" ) {
	my $time = time;
	my $digest = generate_token($time);
	my $token = 'push "auth-token ' . $time . ':' . $digest . '"';
	print "Pushing Auth-Token: $token\n";

	open my $fh, '>', $ARGV[0];
	print $fh $token . "\n";
	close $fh;
	exit 0;
}

else {
	print "We should never get here unless we have the wrong config!\n";
	exit 1;
}

exit 1;
