PERL   45

ga token

Guest on 10th July 2022 08:15:11 PM

  1. #!/usr/bin/perl -T -w
  2. use strict;
  3. use warnings;
  4. use Digest::HMAC_SHA1 qw/ hmac_sha1_hex /;
  5.  
  6. ## Set up usernames to secrets. Minimum length, 16 chars.
  7. my %users = (
  8.         "username"        => "ABCDEFGHIJKLMNOP",
  9. );
  10.  
  11. ## Catch Ctrl+C and Ctrl+Z...
  12. $SIG{'INT'} = sub { fail(); };
  13. $SIG{'TSTP'} = sub { fail(); };
  14.  
  15. sub decodeBase32 {
  16.         my ($val) = @_;
  17.         # turn into binary characters
  18.         $val =~ tr|A-Z2-7|\0-\37|;
  19.         # unpack into binary
  20.         $val = unpack('B*', $val);
  21.         # cut off the 000 prefix
  22.         $val =~ s/000(.....)/$1/g;
  23.         # trim off some characters if not 8 character aligned
  24.         my $len = length($val);
  25.         $val = substr($val, 0, $len & ~7) if $len & 7;
  26.         # pack back up
  27.         $val = pack('B*', $val);
  28.         return $val;
  29. }
  30. sub totp_token {
  31.         my $secret = shift;
  32.         my $key = unpack("H*", decodeBase32($secret));
  33.         my $lpad_time = sprintf("%016x", int(time()/30));
  34.         my $hmac = hmac_sha1_hex_string($lpad_time, $key);
  35.         my $offset = sprintf("%d", hex(substr($hmac, -1)));
  36.         my $part1 = 0 + sprintf("%d", hex(substr($hmac, $offset*2, 8)));
  37.         my $part2 = 0 + sprintf("%d", hex("7fffffff"));
  38.         my $token = substr("".($part1 & $part2), -6);
  39.         return $token;
  40. }
  41. sub hmac_sha1_hex_string {
  42.         my ($data, $key) = map pack('H*', $_), @_;
  43.         hmac_sha1_hex($data, $key);
  44. }
  45. sub fail {
  46.         kill( -1, 0 );
  47.         exit 1;
  48. }
  49.  
  50. my $username = $ENV{"LOGNAME"};
  51. if ( !defined $users{$username} ) {
  52.         print "No token configured. Bye.\n";
  53.         fail();
  54. }
  55.  
  56. print "Enter Code: ";
  57. my $input_code = <STDIN>;
  58. chomp($input_code);
  59.  
  60. my $calculated_code = totp_token($users{$username});
  61. if ( $calculated_code ne $input_code ) {
  62.         fail();
  63. }
  64.  
  65. ## Auth passed.
  66. exit 0;

Raw Paste


Login or Register to edit or fork this paste. It's free.