Skip to content

Instantly share code, notes, and snippets.

@mgregoro
Created June 22, 2017 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgregoro/f0590e720ea01538de9089d6ccbe1463 to your computer and use it in GitHub Desktop.
Save mgregoro/f0590e720ea01538de9089d6ccbe1463 to your computer and use it in GitHub Desktop.
Proof of concept TOTP implementation in perl... 20 second overlap.. reads "secret" from ARGV
#!/usr/bin/env perl
# (c) 2017 Michael Gregorowicz
# requires libsodium (with dev files), Crypt::Sodium, and MIME::Base32 to work
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
use Crypt::Sodium;
use MIME::Base32;
my $secret = join(' ', @ARGV);
my $skew_tolerance = 10;
my $interval = 60;
while (1) {
my $time_fragment = int(time / $interval);
my $remaining = ($interval - time % $interval);
my $announce_token = token_for($time_fragment . $secret);
my %candidates;
if ($skew_tolerance) {
$candidates{token_for($time_fragment . $secret)} = 1;
$candidates{token_for(int((time - $skew_tolerance) / $interval) . $secret)} = 1;
$candidates{token_for(int((time + $skew_tolerance) / $interval) . $secret)} = 1;
} else {
$candidates{token_for($time_fragment . $secret)} = 1;
}
my @candidates = sort {$a cmp $b} keys %candidates;
print "$remaining, ANNOUNCE $announce_token; ACCEPT [" . join(', ', @candidates) . "]\n";
sleep 1;
}
sub token_for {
my $str = MIME::Base32::encode(crypto_hash(shift));
my $token;
if (length($str) > 8) {
# the token is the first 4 and last 4 characters.
$token = substr($str, 0, 4) . substr($str, length($str) - 4, 4);
} else {
# the token is the string left zero padded.
$token = "0" x (8 - length($str)) . $str;
}
return $token;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment