lib/Authen/ModAuthPubTkt.pm

filter: Statementstmt 92.7% 77 / 83 Branchbran 57.4% 31 / 54 Conditioncond 50.0% 10 / 20 MC/DCmcdc 0.0% 0 / 12 Subroutinesub 88.8% 8 / 9 Podpod 100% 3 / 3 totaltotal 71.2% 129 / 181 CC 36 SCAR 30.3
CC
36
Cov
75%
pubtkt_generate
29.7
pubtkt_verify
17.8
pubtkt_parse
6.0
CRAP 20.6
« script/mod_auth_pubtkt.pl ↑ Summary
1 package Authen::ModAuthPubTkt;
2 8 require Exporter;
3 8 our @ISA=qw(Exporter);
4 8 our @EXPORT = qw/pubtkt_generate
5 pubtkt_verify
6 pubtkt_parse/;
7  
8 8 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 8 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 8 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 8 ▶use MIME::Base64;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 8 ▶use File::Temp qw/tempfile/;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 8 ▶use IPC::Run3;
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15  
16 # ABSTRACT: A Module to generate Mod-Auth-PubTkt compatible Cookies
17  
18 =pod
19  
20 =head1 NAME
21  
22 Authen::ModAuthPubTkt - Generate Tickets (Signed HTTP Cookies) for mod_auth_pubtkt protected websites.
23  
24 =head1 VERSION
25  
26 version 0.1.1
27  
28 =cut
29 8 our $VERSION = '0.1.1';
30  
31 =pod
32  
33 =head1 SYNOPSIS
34  
35 On the command-line, generate the public + private keys:
36 (More details available at L<https://neon1.net/mod_auth_pubtkt/install.html>)
37  
38 $ openssl genrsa -out key.priv.pem 1024
39 $ openssl rsa -in key.priv.pem -out key.pub.pem -pubout
40  
41  
42 Then in your perl script (which is probably the your custom login website), use the following code to issue tickets:
43  
44 use Authen::ModAuthPubTkt;
45  
46 my $ticket = pubtkt_generate(
47 privatekey => "key.priv.pem",
48 keytype => "rsa",
49 clientip => undef, # or a valid IP address
50 userid => "102", # or any ID that makes sense to your application, e.g. email
51 validuntil => time() + 86400, # valid for one day
52 graceperiod=> 3600, # grace period of an hour
53 tokens => undef, # comma separated string of tokens.
54 userdata => undef # any application specific data to pass.
55 );
56  
57 ## $ticket string will look something like:
58 ## "uid=102;validuntil=1337899939;graceperiod=1337896339;tokens=;udata=;sig=h5qR" \
59 ## "yZZDl8PfW8wNxPYkcOMlAxtWuEyU5bNAwEFT9lztN3I7V13SaGOHl+U6wB+aMkvvLQiaAfD2xF/Hl" \
60 ## "+QmLDEvpywp98+5nRS+GeihXTvEMRaA4YVyxb4NnZujCZgX8IBhP6XBlw3s7180jxE9I8DoDV8bDV" \
61 ## "k/2em7yMEzLns="
62  
63  
64 To verify a ticket, use the following code:
65  
66 my $ok = pubtkt_verify (
67 publickey => "key.pub.pem",
68 keytype => "rsa",
69 ticket => $ticket
70 );
71 die "Ticket verification failed.\n" if not $ok;
72  
73 To extract items from a ticket, use the following code:
74  
75 my %items = pubtkt_parse($ticket);
76  
77 ## %items will be something like:
78 ## {
79 ## 'uid' => 102,
80 ## 'validuntil' => 1337899939,
81 ## 'graceperiod => 1337896339,
82 ## 'tokens' => "",
83 ## 'udata' => "",
84 ## 'sig' => 'h5qRyZZDl8PfW8wNxPYkcOMlAxtWuEyU5bNAwEFT9lztN3 (....)'
85 ## }
86  
87  
88 Also, a command-line utility (C<mod_auth_pubtkt.pl>) will be installed, and can be used to generate/verify keys:
89  
90 $ mod_auth_pubtkt.pl --generate --private-key key.priv.pem --rsa
91 $ mod_auth_pubtkt.pl --verify --public-key key.pub.pem --rsa
92 $ mod_autH_pubtkt.pl --help
93  
94  
95 =head1 DESCRIPTION
96  
97 This module generates and verify a mod_auth_pubtkt-compatible ticket string, which should be used
98 as a cookie with the rest of the B<mod_auth_pubtkt> ( L<https://neon1.net/mod_auth_pubtkt/> ) system.
99  
100 =head3 Common scenario:
101  
102 =over 2
103  
104 =item 1.
105 On the login server side, write perl code to authenticate users (using Apache's authenetication, LDAP, DB, etc.).
106  
107 =item 2.
108 Once the user is authenticated, call C<pubtkt_generate> to generate a ticket, and send it back to the user as a cookie.
109  
110 =item 3.
111 Redirect the user back to the server he/she came from.
112  
113 =back
114  
115  
116 =head1 Working Example
117  
118 A working (but minimal) perl login example is available at L<https://github.com/manuelkasper/mod_auth_pubtkt/blob/master/perl-login/minimal_cgi/login.pl>
119  
120 =cut
121  
122  
123 ## On unix, assume it's on the $PATH.
124 ## On Windows - you're on your own.
125 ## TODO: make this user-configurable.
126 8 my $openssl_bin = "openssl";
127  
128 =pod
129  
130 =head1 METHODS
131  
132 =head2 pubtkt_generate
133  
134 Generates a signed ticket.
135  
136 If successful, returns a signed ticket string (to be sent back to the user as a cookie).
137  
138 On any failure (bad key, failure to run C<openssl>, etc.) returns C<undef>.
139  
140 Accepts a hash of parameters:
141  
142 =over 4
143  
144 =item B<privatekey>
145  
146 String containing the private key filename (full path). The key can be either DSA or RSA key (see B<keytype>).
147  
148 =item B<keytype>
149  
150 either "rsa" or "dsa" - depending on how you created the private/public key files.
151  
152 =item B<userid>
153  
154 String containing the user ID. No specific format is enforced: can by a number, a string, an email address, etc. It will be encoded as "uid=XXXX" in the signed ticket.
155  
156 =item B<validuntil>
157  
158 Numeric value, containing the validity period, in seconds since epoch (use C<time()> function).
159  
160 =item B<graceperiod>
161  
162 Optional. Numeric value. If given, will be added to the signed ticket string.
163  
164 =item B<clientip>
165  
166 Optional. A string with an IP address. If given. will be added to the signed ticket string.
167  
168 =item B<token>
169  
170 Optional. Any textual string. If given. will be added to the signed ticket string.
171  
172 =item B<userdata>
173  
174 Optional. Any textual string. If given. will be added to the signed ticket string.
175  
176 =back
177  
178 =cut
179 sub pubtkt_generate
180 6 ▶{
Subroutine pubtkt_generate: called CC=21 SCAR=33.9
Pod documented
181 6 my %args = @_;
182 6 ▶ my $private_key_file = $args{privatekey} or croak "Missing \"privatekey\" parameter";
Branch: 1 branch
BranchTrueFalseTotal
my $private_key_file = $args{"privatekey"} or croak("Missing \"privatekey\" parameter") 6 0 6
183 6 ▶ croak "Invalid \"privatekey\" value ($private_key_file): file doesn't exist/not readable"
Branch: 1 branch
BranchTrueFalseTotal
unless -r $private_key_file 0 6 6
184 unless -r $private_key_file;
185  
186 6 ▶ my $keytype = $args{keytype} or croak "Missing \"keytype\" parameter";
Branch: 1 branch
BranchTrueFalseTotal
my $keytype = $args{"keytype"} or croak("Missing \"keytype\" parameter") 6 0 6
187 6 ▶ croak "Invalid \"keytype\" value ($keytype): expecting 'dsa' or 'rsa'\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $keytype eq "dsa" or $keytype eq "rsa" 0 6 6
Condition66%2/3
$keytype eq "dsa" or $keytype eq "rsa"
l!l&&r!l&&!r
240
MC/DC0%0/2
$keytype eq "dsa" or $keytype eq "rsa"
$keytype eq "dsa" $keytype eq "rsa"
Truth table66%2/3
A or B
A= $keytype eq "dsa"B= $keytype eq "rsa"
ABresult
1X1
011
000
188 unless $keytype eq "dsa" || $keytype eq "rsa";
189  
190 6 ▶ my $user_id = $args{userid} or croak "Missing \"userid\" parameter";
Branch: 1 branch
BranchTrueFalseTotal
my $user_id = $args{"userid"} or croak("Missing \"userid\" parameter") 6 0 6
191  
192 6 ▶ my $valid_until = $args{validuntil} or croak "Missing \"validuntil\" parameter";
Branch: 1 branch
BranchTrueFalseTotal
my $valid_until = $args{"validuntil"} or croak("Missing \"validuntil\" parameter") 6 0 6
193 6 ▶ croak "Invalid \"validuntil\" value ($valid_until), expecting a numeric value."
Branch: 1 branch
BranchTrueFalseTotal
unless $valid_until =~ /^\d+$/ 0 6 6
194 unless $valid_until =~ /^\d+$/;
195  
196 6 ▶ my $grace_period = $args{graceperiod} || "";
Condition50%1/2
$args{'graceperiod'} || ''
l!l
60
MC/DC0%0/1
$args{'graceperiod'} || ''
$args{'graceperiod'}
Truth table50%1/2
A
A= $args{'graceperiod'}
Aresult
11
00
197 6 ▶ croak "Invalid \"graceperiod\" value ($grace_period), expecting a numeric value."
Branch: 1 branch
BranchTrueFalseTotal
unless $grace_period eq "" or $grace_period =~ /^\d+$/ 0 6 6
Condition33%1/3
$grace_period eq "" or $grace_period =~ /^\d+$/
l!l&&r!l&&!r
060
MC/DC0%0/2
$grace_period eq "" or $grace_period =~ /^\d+$/
$grace_period eq "" $grace_period =~ /^\d+$/
Truth table33%1/3
A or B
A= $grace_period eq ""B= $grace_period =~ /^\d+$/
ABresult
1X1
011
000
198 unless $grace_period eq "" || $grace_period =~ /^\d+$/;
199  
200 6 ▶ my $client_ip = $args{clientip} || "";
Condition50%1/2
$args{'clientip'} || ''
l!l
60
MC/DC0%0/1
$args{'clientip'} || ''
$args{'clientip'}
Truth table50%1/2
A
A= $args{'clientip'}
Aresult
11
00
201 ##TODO: better IP address validation
202 6 ▶ croak "Invalid \"client_ip\" value ($client_ip), expecting a valid IP address."
Branch: 1 branch
BranchTrueFalseTotal
unless $client_ip eq "" or $client_ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/ 0 6 6
Condition33%1/3
$client_ip eq "" or $client_ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/
l!l&&r!l&&!r
060
MC/DC0%0/2
$client_ip eq "" or $client_ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/
$client_ip eq "" $client_ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/
Truth table33%1/3
A or B
A= $client_ip eq ""B= $client_ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/
ABresult
1X1
011
000
203 unless $client_ip eq "" || $client_ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
204  
205 6 ▶ my $tokens = $args{token} || "";
Condition50%1/2
$args{'token'} || ''
l!l
06
MC/DC0%0/1
$args{'token'} || ''
$args{'token'}
Truth table50%1/2
A
A= $args{'token'}
Aresult
11
00
206 6 ▶ my $user_data = $args{userdata} || "";
Condition50%1/2
$args{'userdata'} || ''
l!l
06
MC/DC0%0/1
$args{'userdata'} || ''
$args{'userdata'}
Truth table50%1/2
A
A= $args{'userdata'}
Aresult
11
00
207  
208 # Generate Ticket String
209 6 my $tkt = "uid=$user_id;" ;
210 6 ▶ $tkt .= "cip=$client_ip;" if $client_ip;
Branch: 1 branch
BranchTrueFalseTotal
if $client_ip 6 0 6
211 6 $tkt .= "validuntil=$valid_until;";
212 6 ▶ $tkt .= "graceperiod=" . ($valid_until - $grace_period) . ";" if $grace_period;
Branch: 1 branch
BranchTrueFalseTotal
if $grace_period 6 0 6
213 6 $tkt .= "tokens=$tokens;";
214 6 $tkt .= "udata=$user_data";
215  
216 6 ▶ my $algorithm_param = ( $keytype eq "dsa" ) ? "-dss1" : "-sha1";
Branch: 1 branch
BranchTrueFalseTotal
$keytype eq 'dsa' ? : 2 4 6
217  
218 6 my @cmd = ( $openssl_bin,
219 "dgst", $algorithm_param,
220 "-binary",
221 "-sign", $private_key_file ) ;
222  
223 6 my ($stdin, $stdout, $stderr);
224  
225 6 $stdin = $tkt;
226 6 run3 \@cmd, \$stdin, \$stdout, \$stderr;
227 6 my $exitcode = $?;
228  
229 6 ▶ if ($exitcode != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($exitcode != 0) 2 4 6
230 2 warn "pubtkt_generate failed: openssl returned exit code $exitcode, stderr = $stderr\n";
231 2 return;
232 }
233  
234 4 $tkt .= ";sig=" . encode_base64($stdout,""); #2nd param = no EOL.
235  
236 4 return $tkt;
237 }
238  
239 =head2 pubtkt_verify
240  
241 Verifies a signed ticket string.
242  
243 If successful (i.e. the ticket's signature is valid), returns TRUE (=1).
244  
245 On any failure (bad key, failure to run C<openssl>, etc.) returns C<undef>.
246  
247 B<NOTE>: B<This function checks ONLY THE SIGNATURE, based on the public key file. It is the caller's resposibility to check the expiration date.> That is: The function will return TRUE if the ticket is properly signed, but possibly expired.
248  
249 Accepts a hash of parameters:
250  
251 =over 4
252  
253 =item B<publickey>
254  
255 String containing the public key filename (full path). The key can be either DSA or RSA key (see B<keytype>).
256  
257 =item B<keytype>
258  
259 either "rsa" or "dsa" - depending on how you created the private/public key files.
260  
261 =item B<ticket>
262  
263 The string of the ticket (such as returned by C<pubtkt_generate>).
264  
265 =back
266  
267 =cut
268 sub pubtkt_verify
269 104 ▶{
Subroutine pubtkt_verify: called CC=15 SCAR=28.8
Pod documented
270 104 my %args = @_;
271 104 ▶ my $public_key_file = $args{publickey} or croak "Missing \"publickey\" parameter";
Branch: 1 branch
BranchTrueFalseTotal
my $public_key_file = $args{"publickey"} or croak("Missing \"publickey\" parameter") 104 0 104
272 104 ▶ croak "Invalid \"publickey\" value ($public_key_file): file doesn't exist/not readable"
Branch: 1 branch
BranchTrueFalseTotal
unless -r $public_key_file 0 104 104
273 unless -r $public_key_file;
274  
275 104 ▶ my $keytype = $args{keytype} or croak "Missing \"keytype\" parameter";
Branch: 1 branch
BranchTrueFalseTotal
my $keytype = $args{"keytype"} or croak("Missing \"keytype\" parameter") 104 0 104
276 104 ▶ croak "Invalid \"keytype\" value ($keytype): expecting 'dsa' or 'rsa'\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $keytype eq "dsa" or $keytype eq "rsa" 0 104 104
Condition66%2/3
$keytype eq "dsa" or $keytype eq "rsa"
l!l&&r!l&&!r
11030
MC/DC0%0/2
$keytype eq "dsa" or $keytype eq "rsa"
$keytype eq "dsa" $keytype eq "rsa"
Truth table66%2/3
A or B
A= $keytype eq "dsa"B= $keytype eq "rsa"
ABresult
1X1
011
000
277 unless $keytype eq "dsa" || $keytype eq "rsa";
278 104 ▶ my $algorithm_param = ( $keytype eq "dsa" ) ? "-dss1" : "-sha1";
Branch: 1 branch
BranchTrueFalseTotal
$keytype eq 'dsa' ? : 1 103 104
279  
280 104 ▶ my $ticket_str = $args{ticket} or croak "Missing \"ticket\" parameter";
Branch: 1 branch
BranchTrueFalseTotal
my $ticket_str = $args{"ticket"} or croak("Missing \"ticket\" parameter") 103 1 104
281  
282 # Extract base64'd signature text
283 103 my ($ticket_data, $sig_base64) = split /;sig=/, $ticket_str;
284 103 ▶ warn "Pubtkt.pm: missing \"sig=\" in ticket ($ticket_str)" unless $sig_base64;
Branch: 1 branch
BranchTrueFalseTotal
unless $sig_base64 0 103 103
285 103 ▶ return unless $sig_base64;
Branch: 1 branch
BranchTrueFalseTotal
unless $sig_base64 0 103 103
286  
287 # Decode base64 signature, and store in a temporary file
288 103 my $sig_bin = decode_base64($sig_base64);
289 103 ▶ warn "Pubtkt.pm: invalid base64 signature from ticket ($ticket_str)" unless length($sig_bin)>0;
Branch: 1 branch
BranchTrueFalseTotal
unless length $sig_bin > 0 0 103 103
290  
291 103 my ($fh, $temp_sig_file) = tempfile("pubtkt.XXXXXXXXX", UNLINK=>1, TMPDIR=>1);
292 103 ▶ print $fh $sig_bin or die "Failed to write signature data: $!";
Branch: 1 branch
BranchTrueFalseTotal
print $fh $sig_bin or die "Failed to write signature data: $!" 103 0 103
293 103 ▶ close $fh or die "Failed to write signature data: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or die "Failed to write signature data: $!" 103 0 103
294  
295 # verify signature using openssl
296 103 my @cmd = ( $openssl_bin,
297 "dgst", $algorithm_param,
298 "-verify", $public_key_file,
299 "-signature", $temp_sig_file);
300 103 my ($stdin, $stdout, $stderr);
301 103 $stdin = $ticket_data;
302 103 run3 \@cmd, \$stdin, \$stdout, \$stderr;
303 103 my $exitcode = $?;
304 103 ▶ return unless $exitcode == 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $exitcode == 0 102 1 103
305  
306 1 ▶ return 1 if ( $stdout eq "Verified OK\n" ) ;
Branch: 1 branch
BranchTrueFalseTotal
if $stdout eq "Verified OK\n" 1 0 1
307  
308 0 return ;
309 }
310  
311 =head2 pubtkt_parse($ticket)
312  
313 Utility function to parse a ticket string into a Perl hash.
314  
315 B<NOTE>: No validation is performed. The given ticket might be expired, or even forged.
316  
317 =cut
318 sub pubtkt_parse
319 0 ▶{
Subroutine pubtkt_parse: not called CC=2 SCAR=17.9
Pod documented
320 0 ▶ my $tkt = shift or croak "missing ticket string parameter";
Branch: 1 branch
BranchTrueFalseTotal
my $tkt = shift() or croak("missing ticket string parameter") 0 0 0
321 0 my @fields = split /;/, $tkt;
322 0 my %values = map { split (/=/, $_, 2) } @fields;
323 0 return %values;
324 }
325  
326 =head1 PREREQUISITES
327  
328 B<openssl> must be installed (and available on the $PATH).
329  
330 L<IPC::Run3> is required to run the openssl executables.
331  
332 =head1 BUGS
333  
334 Probably many.
335  
336 =head1 TODO
337  
338 Use Perl's L<Crypt::OpenSSL::RSA> and L<Crypt::OpenSSL::DSA> instead of the running C<openssl> executable.
339  
340 Don't assume C<openssl> binary is on the $PATH.
341  
342 Refactor into OO interface.
343  
344 =head1 LICENSE
345  
346 Copyright (C) 2012 A. Gordon ( gordon at cshl dot edu ).
347  
348 Apache License, same as the rest of B<mod_auth_pubtkt>
349  
350 =head1 AUTHORS
351  
352 A. Gordon, heavily based on the PHP code from B<mod_auth_pubtkt>.
353  
354 =head1 SEE ALSO
355  
356 ModAuthPubTkt main website: L<https://neon1.net/mod_auth_pubtkt/>
357  
358 ModAuthPubTkt github repository: L<https://github.com/manuelkasper/mod_auth_pubtkt>
359  
360 This module's github repository: L<https://github.com/agordon/Authen-ModAuthPubTkt>
361  
362 Examples in the C<./eg> directory:
363  
364 =over 4
365  
366 =item B<generate_rsa_keys.sh>
367  
368 Generates a pair of RSA key files.
369  
370 =item B<generate_dsa_keys.sh>
371  
372 Generates a pair of DSA key files.
373  
374 =item B<mod_auth_pubtkt.pl>
375  
376 A command-line utility to generate/verify tickets.
377  
378 =back
379  
380 =cut
381  
382 8 1;
« script/mod_auth_pubtkt.pl ↑ Summary