summaryrefslogtreecommitdiff
path: root/lib/Auth/Yubikey_WebClient.pm
blob: 687b4e23bb4a9b8a74fc7f548dd71364b0d15e66 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
package Auth::Yubikey_WebClient;

use warnings;
use strict;
use MIME::Base64;
use Digest::HMAC_SHA1 qw(hmac_sha1 hmac_sha1_hex);
use LWP::UserAgent;
use URI::Escape;

=head1 NAME

Auth::Yubikey_WebClient - Authenticating the Yubikey against the Yubico Web API

=head1 VERSION

Version 4.02

=cut

our $VERSION = '4.02';

=head1 SYNOPSIS

Authenticate against the Yubico server via the Web API in Perl

Sample CGI script :-

	#!/usr/bin/perl

	use CGI;
	use strict;

	my $cgi = new CGI;
	my $otp = $cgi->param("otp");

	print $cgi->header();
	print "<html>\n";
	print "<form method=get>Yubikey : <input type=text name=otp size=40 type=password></form>\n";

	use Auth::Yubikey_WebClient;

	my $id = "<enter your id here>";
	my $api = "<enter your API key here>";
	my $nonce = "<enter your nonce here>";

	if($otp)
	{
        	my $result = Auth::Yubikey_WebClient::yubikey_webclient($otp,$id,$api,$nonce);
		# result can be either ERR or OK

        	print "Authentication result : <b>$result</b><br>";
	}

	print "</html>\n";


=head1 FUNCTIONS

=head2 new

Creates a new Yubikey Webclient connection

   use Auth::Yubikey_WebClient;

   my $yubi = Auth::Yubikey_WebClient->new({
        id => <enter your id here> ,
        api => '<enter your API key here>' ,
        nonce => '<enter your nonce if you have one>',
	verify_hostname => 0	# optional - defaults to 1.  Can be set to 0 if you do not want to check the validity of the SSL certificate when querying the Yubikey server
        });

You can overwrite the URL called if you want to call an alternate authentication server as well :-

   use Auth::Yubikey_WebClient;

   my $yubi = Auth::Yubikey_WebClient->new({
        id => <enter your id here> ,
        api => '<enter your API key here>' ,
        nonce => '<enter your nonce if you have one>',
	url => 'http://www.otherserver.com/webapi.php'
        });

=cut

sub new
{
	my ($class,$options_ref) = @_;
	my $self = {};

	bless $self, ref $class || $class;

	if(! defined $options_ref) {
		die "You did not pass any parameters to the Yubikey Web Client initialization";
	}
	my %options = %{$options_ref};

	# grab the variables from the initialization
	if(defined $options{id}) {
        	$self->{id} = $options{id};
	} else {
		die "Can not start without a Yubikey ID";
	}

	if(defined $options{api}) {
		$self->{api} = $options{api};

		if(length($self->{api}) % 4 != 0) {
			die "Your API key must be in 4 byte lengths";
		}
  	} else {
		die "Can not start without a Yubikey API key";
	}

	$self->{nonce} = defined $options{nonce} ? $options{nonce} : '';

	$self->{url} = defined $options{url} ? $options{url} : 'https://api2.yubico.com/wsapi/2.0/verify';

	$self->{verify_hostname} = defined $options{verify_hostname} ? $options{verify_hostname} : 1;

	return $self;
}

=head2 debug

Displays the debug info

   $yubi->debug();

Prints out some debug information.  Useful to be called after authentication to see what Yubico sent back.  You can also call the variables yourself, for example if you'd like to see what the token ID is, call $yubi->{publicid}.  The same goes for all the other variables printed in debug.

=cut

sub debug
{
	my ($self) = @_;

	print "id             = $self->{id}\n";
	print "api            = $self->{api}\n";
	print "url            = $self->{url}\n";
	print "nonce          = $self->{nonce}\n";
	print "params         = $self->{params}\n";
	print "status         = $self->{status}\n";
	print "otp            = $self->{otp}\n";
	print "publicid       = $self->{publicid}\n";
	print "t              = $self->{t}\n";
	print "sl             = $self->{sl}\n";
	print "timestamp      = $self->{timestamp}\n";
	print "sessioncounter = $self->{sessioncounter}\n";
	print "sessionuse     = $self->{sessionuse}\n";

#	print "response = $self->{response}\n";

}

=head2 yubikey_webclient

=cut

sub yubikey_webclient
{
	my ($otp,$id,$api,$nonce) = @_;

	my $yubi_tmp = new Auth::Yubikey_WebClient ( { id => $id, api => $api, nonce => $nonce } );

	return $yubi_tmp->otp($otp);
}

=head2 otp

Check a OTP for validity

	$result = $yubi->otp($otp);

Call the otp procedure with the input from the yubikey.  It will return the result.

This function will also setup a few internal variables that was returned from Yubico.

=cut

sub otp
{
        my ($self,$otp) = @_;

	chomp($otp);
	$self->{otp} = $otp;

	# lets do a basic sanity check on the otp, before we blast it off to yubico...
	if($self->{otp} !~ /[cbdefghijklnrtuv]/i || length($self->{otp}) < 32) 	{
		$self->{status} = "ERR_BAD_OTP";
		return $self->{status};
	}

	# Generate nonce unless passed
	$self->{nonce} = hmac_sha1_hex(time, rand()) unless $self->{nonce};

	# Start generating the parameters
	$self->{params} = "id=$self->{id}&nonce=$self->{nonce}&otp=" . uri_escape($self->{otp}) . "&timestamp=1";
	$self->{params} .= '&h=' . uri_escape(encode_base64(hmac_sha1($self->{params}, decode_base64($self->{api})), ''));

	# pass the request to yubico
	my $ua = LWP::UserAgent->new(ssl_opts => { verify_hostname => $self->{verify_hostname} });
	$ua->env_proxy();	# 4.02
	my $req = HTTP::Request->new(GET => $self->{url} . "?$self->{params}");
	my $res = $ua->request($req);
	if($res->is_success) {
		$self->{response} = $res->content;
	} else {
		print $res->status_line . "\n";
	}
	chomp($self->{response});

	if($self->{response} !~ /status=ok/i) {
		# If the status is not ok, let's not even go through the rest...
		$self->{response} =~ m/status=(.+)/;
		$self->{status} = "ERR_$1";
		$self->{status} =~ s/\s//g;
		return $self->{status};
	}

	#extract each of the lines, and store in a hash...

	my %result;
	foreach (split(/\n/,$self->{response})) {
		chomp;
                if($_ =~ /=/)
                {
                        ($a,$b) = split(/=/,$_,2);
                        $b =~ s/\s//g;
                        $result{$a} = $b;
			$self->{$a} = $b;
                }
        }

        # save the h parameter, that's what we'll be comparing to

        my $signatur=$result{h};
        delete $result{h};
        my $datastring='';

	my $key;
        foreach $key (sort keys %result) {
                $result{$key} =~ s/\s//g;
                $datastring .= "$key=$result{$key}&";
        }
        $datastring = substr($datastring,0,length($datastring)-1);

	# Check that nonce and OTP are the ones we asked for
	$self->{status} = "ERR_MSG_AUTH";

	return "ERR_MSG_AUTH" unless ($self->{nonce} eq $result{nonce} and $self->{otp} eq $result{otp});

  	my $hmac = encode_base64(hmac_sha1($datastring,decode_base64($self->{api})));
	chomp($hmac);
  	if($hmac eq $signatur) {
		$self->{publicid} = substr(lc($self->{otp}),0,12);
		$self->{status} = "OK";
                return "OK";
   } else {
		$self->{status} = "ERR_HMAC";
		return "ERR_HMAC";
	}
}

=head1 USAGE

Before you can use this module, you need to register for an API key at Yubico.  This is as simple as logging onto <https://upgrade.yubico.com/getapikey/> and entering your Yubikey's OTP and your email address.  Once you have the API and ID, you need to provide those details to the module to work.

=head1 AUTHOR

Phil Massyn, C<< <massyn at gmail.com> >>

=head1 BUGS

Please report any bugs or feature requests to C<bug-auth-yubikey_webclient at rt.cpan.org>, or through
the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Auth-Yubikey_WebClient>.  I will be notified, and then you'll
automatically be notified of progress on your bug as I make changes.




=head1 SUPPORT

You can find documentation for this module with the perldoc command.

    perldoc Auth::Yubikey_WebClient


You can also look for information at:

=over 4

=item * RT: CPAN's request tracker

L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Auth-Yubikey_WebClient>

=item * AnnoCPAN: Annotated CPAN documentation

L<http://annocpan.org/dist/Auth-Yubikey_WebClient>

=item * CPAN Ratings

L<http://cpanratings.perl.org/d/Auth-Yubikey_WebClient>

=item * Search CPAN

L<http://search.cpan.org/dist/Auth-Yubikey_WebClient>

=back

=head1 Version history

0.04 - Fixed bug L<http://rt.cpan.org/Public/Bug/Display.html?id=51121>
1.00 - Added validation of the request to Yubico (Thanks to Kirill Miazine)
2.00 - Added nounce coding (Thanks to Ludvig af Klinteberg)
2.01 - Response turning into an array due to \r bug (Thanks to Peter Norin)
3.00 - Major update
4.01 - 13.10.2016 - Requested by Peter Norin - update to use LWP::UserAgent, and the option to overwrite a valid SSL certificate (verify_hostname).  The API default server is changed to ssl.
4.02 - 2019.04.04 - Request by Alexandre Linte - Support for proxy servers

=head1 ACKNOWLEDGEMENTS

=head1 COPYRIGHT & LICENSE

Copyright 2016 Phil Massyn, all rights reserved.

This program is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.


=cut

; # End of Auth::Yubikey_WebClient