chiark / gitweb /
automatic agpl compliance: wip fixes
[cgi-auth-flexible.git] / cgi-auth-flexible.pm
1 # -*- perl -*-
2
3 # This is part of CGI::Auth::Flexible, a perl CGI authentication module.
4 # Copyright (C) 2012 Ian Jackson.
5 # Copyright (C) 2012 Citrix.
6
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU Affero General Public License for more details.
16
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20 use strict;
21 use warnings FATAL => 'all';
22
23 package CGI::Auth::Flexible;
24 require Exporter;
25
26 BEGIN {
27     use Exporter   ();
28     our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
29
30     $VERSION     = 1.00;
31     @ISA         = qw(Exporter);
32     @EXPORT      = qw();
33     %EXPORT_TAGS = ( );     # eg: TAG => [ qw!name1 name2! ],
34
35     @EXPORT_OK   = qw();
36 }
37 our @EXPORT_OK;
38
39 use DBI;
40 use CGI qw/escapeHTML/;
41 use Locale::gettext;
42 use URI;
43 use IO::File;
44 use Fcntl qw(:flock);
45 use POSIX;
46 use Digest;
47 use Digest::HMAC;
48 use Digest::SHA;
49 use Data::Dumper;
50 use File::Copy;
51
52 #---------- public utilities ----------
53
54 sub flatten_params ($) {
55     my ($p) = @_;
56     my @p;
57     foreach my $k (keys %$p) {
58         next if $k eq '';
59         foreach my $v (@{ $p->{$k} }) {
60             push @p, $k, $v;
61         }
62     }
63     return @p;
64 }
65
66 #---------- default callbacks ----------
67
68 sub has_a_param ($$) {
69     my ($r,$cn) = @_;
70     foreach my $pn (@{ $r->{S}{$cn} }) {
71         return 1 if $r->_ch('get_param',$pn);
72     }
73     return 0;
74 }
75
76 sub get_params ($) {
77     my ($r) = @_;
78     my %p;
79     my $c = $r->{Cgi};
80     foreach my $name ($c->param()) {
81         $p{$name} = [ $c->param($name) ];
82     }
83     return \%p;
84 }
85
86 sub get_cookie_domain ($$$) {
87     my ($c,$r) = @_;
88     my $uri = new URI $r->_ch('get_url');
89     return $uri->host();
90 }
91
92 sub login_ok_password ($$) {
93     my ($c, $r) = @_;
94     my $username_params = $r->{S}{username_param_names};
95     my $username = $r->_ch('get_param',$username_params->[0]);
96     my $password = $r->_rp('password_param_name');
97     my $error = $r->_ch('username_password_error', $username, $password);
98     return defined($error) ? (undef,$error) : ($username,undef);
99 }
100
101 sub do_redirect_cgi ($$$$) {
102     my ($c, $r, $new_url, $cookie) = @_;
103     $r->_print($c->header($r->_cgi_header_args($cookie,
104                                                -status => '303 See other',
105                                                -location => $new_url)),
106                $r->_ch('gen_start_html',$r->_gt('Redirection')),
107                '<a href="'.escapeHTML($new_url).'">',
108                $r->_gt("If you aren't redirected, click to continue."),
109                "</a>",
110                $r->_ch('gen_end_html'));
111 }
112
113 sub gen_some_form ($$) {
114     my ($r, $params, $bodyfn) = @_;
115     # Calls $bodyfn->($c,$r) which returns @formbits
116     my $c = $r->{Cgi};
117     my @form;
118     my $pathinfo = '';
119     $pathinfo .= $params->{''}[0] if $params->{''};
120     push @form, ('<form method="POST" action="'.
121                  escapeHTML($r->_ch('get_url').$pathinfo).'">');
122     push @form, $bodyfn->($c,$r);
123     foreach my $n (keys %$params) {
124         next if $n eq '';
125         foreach my $val (@{ $params->{$n} }) {
126             push @form, ('<input type="hidden"'.
127                          ' name="'.escapeHTML($n).'"'.
128                          ' value="'.escapeHTML($val).'">');
129         }
130     }
131     push @form, ('</form>');
132     return join "\n", @form;
133 }
134
135 sub gen_plain_login_form ($$) {
136     my ($c,$r, $params) = @_;
137     return $r->gen_some_form($params, sub {
138         my @form;
139         push @form, ('<table>');
140         my $sz = 'size="'.$r->{S}{form_entry_size}.'"';
141         foreach my $up (@{ $r->{S}{username_param_names}}) {
142             push @form, ('<tr><td>',$r->_gt(ucfirst $up),'</td>',
143                          '<td><input type="text" '.$sz.
144                          ' name='.$up.'></td></tr>');
145         }
146         push @form, ('<tr><td>'.$r->_gt('Password').'</td>',
147                      '<td><input type="password" '.$sz.
148                      ' name="'.$r->{S}{password_param_name}.'"></td></tr>');
149         push @form, ('<tr><td colspan="2">',
150                      '<input type="submit"'.
151                      ' name="'.$r->{S}{dummy_param_name_prefix}.'login"'.
152                      ' value="'.$r->_gt('Login').'"></td></tr>',
153                      '</table>');
154         return @form;
155     });
156 }
157
158 sub gen_postmainpage_form ($$$) {
159     my ($c,$r, $params) = @_;
160     return $r->gen_some_form($params, sub {
161         my @form;
162         push @form, ('<input type="submit"',
163                      ' name="'.$r->{S}{dummy_param_name_prefix}.'submit"'.
164                      ' value="'.$r->_gt('Continue').'">');
165         return @form;
166     });
167 }
168
169 sub gen_plain_login_link ($$) {
170     my ($c,$r, $params) = @_;
171     my $url = $r->url_with_query_params($params);
172     return ('<a href="'.escapeHTML($url).'">'.
173             $r->_gt('Log in again to continue.').
174             '</a>');
175 }
176
177 sub gen_srcdump_link_html ($$$$) {
178     my ($c,$r,$anchor,$specval) = @_;
179     my %params = ($r->{S}{srcdump_param_name} => [ $specval ]);
180     return '<a href="'.escapeHTML($r->url_with_query_params(\%params)).'">'.
181         $anchor."</a>";
182 }
183 sub gen_plain_licence_link_html ($$) {
184     my ($c,$r) = @_;
185     gen_srcdump_link_html($c,$r, 'GNU Affero GPL', 'licence');
186 }
187 sub gen_plain_source_link_html ($$) {
188     my ($c,$r) = @_;
189     gen_srcdump_link_html($c,$r, 'Source available', 'source');
190 }
191
192 sub gen_plain_footer_html ($$) {
193     my ($c,$r) = @_;
194     return ('<hr><address>',
195             ("Powered by Free / Libre / Open Source Software".
196              " according to the ".$r->_ch('gen_licence_link_html')."."),
197             $r->_ch('gen_source_link_html').".",
198             '</address>');
199 }
200
201 #---------- licence and source code ----------
202
203 sub srcdump_dump ($$$) {
204     my ($c,$r, $thing) = @_;
205     die if $thing =~ m/\W/ || $thing !~ m/\w/;
206     my $path = $r->_get_path('srcdump');
207     my $ctf = new IO::File "$path/$thing.ctype", 'r'
208         or die "$path/$thing.ctype $!";
209     my $ct = <$ctf>;
210     chomp $ct or die "$path/$thing ?";
211     $ctf->close or die "$path/$thing $!";
212     my $df = new IO::File "$path/$thing.data", 'r'
213         or die "$path/$thing.data $!";
214     $r->_ch('dump', $ct, $df);
215 }
216
217 sub dump_plain ($$$$) {
218     my ($c, $r, $ct, $df) = @_;
219     $r->_print($c->header('-type' => $ct));
220     my $buffer;
221     for (;;) {
222         my $got = read $df, $buffer, 65536;
223         die $! unless defined $got;
224         return if !$got;
225         $r->_print($buffer);
226     }
227 }
228
229 sub srcdump_process_dir ($$$$$$) {
230     my ($c, $v, $dumpdir, $incdir, $tarballcounter,
231         $needlicence, $dirsdone) = @_;
232     return () if $v->_ch('srcdump_system_dir', $incdir);
233     my $upwards = $incdir;
234     for (;;) {
235         $upwards =~ s#/+##;
236         last unless $upwards =~ m#[^/]#;
237         foreach my $try (@{ $v->{S}{srcdump_vcs_dirs} }) {
238             if (!stat "$upwards/$try") {
239                 $!==&ENOENT or die "check $upwards/$try $!";
240                 next;
241             }
242             $try =~ m/\w+/ or die;
243             return if $dirsdone->{$upwards}++;
244             return $v->_ch(('srcdump_byvcs_'.lc $try),
245                            $dumpdir, $upwards, $tarballcounter);
246         }
247         $upwards =~ s#/*[^/]+##;
248     }
249     return $v->_ch('srcdump_novcs', $dumpdir, $incdir, $tarballcounter);
250 }
251
252 sub srcdump_novcs ($$$$$) {
253     my ($c, $v, $dumpdir, $dir, $tarballcounter) = @_;
254     my $script = 'find -type f -perm +004';
255     foreach my $excl (@{ $v->{S}{srcdump_excludes} }) {
256         $script .= " \\! -name '$excl'";
257     }
258     $script .= " -print0";
259     return srcdump_dir_cpio($c,$v,$dumpdir,$dir,$tarballcounter,$script);
260 }
261
262 sub srcdump_byvcs_git ($$$$$) {
263     my ($c, $v, $dumpdir, $dir, $tarballcounter) = @_;
264     return srcdump_dir_cpio($c,$v,$dumpdir,$dir,$tarballcounter,"
265                  git-ls-files -z;
266                  git-ls-files -z --others --exclude-from=.gitignore;
267                  find .git -print0
268                             ");
269 }
270
271 sub srcdump_dir_cpio ($$$$$) {
272     my ($c,$v,$dumpdir,$dir,$tarballcounter,$script) = @_;
273     my $outfile = "$dumpdir/$$tarballcounter.tar";
274     my $pid = fork();
275     defined $pid or die $!;
276     if (!$pid) {
277         open STDOUT, ">", $outfile or die "$outfile $!";
278         chdir $dir or die "chdir $dir: $!";
279         exec '/bin/bash','-ec','',"
280             set -o pipefail
281             (
282              $script
283             ) | (
284              cpio -Hustar -o --quiet -0 -R 1000:1000 || \
285              cpio -Hustar -o --quiet -0
286             )
287             ";
288         die $!;
289     }
290     $!=0; (waitpid $pid, 0) == $pid or die "$!";
291     die "$dir ($script) $outfile $?" if $?;
292     $$tarballcounter++;
293     return $outfile;
294 }
295
296 sub srcdump_dirscan_prepare ($$) {
297     my ($c, $v) = @_;
298     my $dumpdir = $v->_get_path('srcdump');
299     mkdir $dumpdir or $!==&EEXIST or die "mkdir $dumpdir $!";
300     my $lockf = new IO::File "$dumpdir/generate.lock", 'w+'
301         or die "$dumpdir/generate.lock $!";
302     flock $lockf, LOCK_EX or die "$dumpdir/generate.lock $!";
303     my $needlicence = "$dumpdir/licence.tmp";
304     unlink $needlicence or $!==&ENOENT or die "rm $needlicence $!";
305     if (defined $v->{S}{srcdump_licence_path}) {
306         copy($v->{S}{srcdump_licence_path}, $needlicence)
307             or die "$v->{S}{srcdump_licence_path} $!";
308         $needlicence = undef;
309     }
310     my $srctarballcounter = 'aaa';
311     my %dirsdone;
312     my @srcfiles = ("$dumpdir/licence.data");
313     foreach my $incdir ($v->_ch('srcdump_includedirs')) {
314         if (defined $needlicence) {
315             foreach my $try (@{ $v->{S}{srcdump_licence_files} }) {
316                 last if copy("$incdir/$try", $needlicence);
317                 $!==&ENOENT or die "copy $incdir/$try $!";
318             }
319         }
320         push @srcfiles, $v->_ch('srcdump_process_dir', $dumpdir, $incdir,
321                                 \$srctarballcounter, \$needlicence, \%dirsdone);
322         $dirsdone{$incdir}++;
323     }
324     die "licence file not found" unless defined $needlicence;
325     srcdump_install($c,$v, $dumpdir, 'licence', 'text/plain');
326     close $lockf or die $!;
327 }
328
329 sub srcdump_install ($$$$$) {
330     my ($c,$v, $dumpdir, $which, $ctype) = @_;
331     rename "$dumpdir/$which.tmp", "$dumpdir/$which.data"
332         or die "$dumpdir/$which.data $!";
333     my $ctf = new IO::File "$dumpdir/$which.tmp", 'w'
334         or die "$dumpdir/$which.tmp $!";
335     print $ctf $ctype, "\n" or die $!;
336     close $ctf or die $!;
337     rename "$dumpdir/$which.tmp", "$dumpdir/$which.ctype"
338         or die "$dumpdir/$which.ctype $!";
339 }
340
341 #---------- verifier object methods ----------
342
343 sub new_verifier {
344     my $class = shift;
345     my $verifier = {
346         S => {
347             dir => undef,
348             assocdb_dbh => undef, # must have AutoCommit=0, RaiseError=1
349             assocdb_path => 'caf-assocs.db',
350             keys_path => 'caf-keys',
351             srcdump_path => 'caf-srcdump',
352             assocdb_dsn => undef,
353             assocdb_user => '',
354             assocdb_password => '',
355             assocdb_table => 'caf_assocs',
356             random_source => '/dev/urandom',
357             secretbits => 128, # bits
358             hash_algorithm => "SHA-256",
359             login_timeout => 86400, # seconds
360             login_form_timeout => 3600, # seconds
361             key_rollover => 86400, # seconds
362             assoc_param_name => 'caf_assochash',
363             dummy_param_name_prefix => 'caf__',
364             cookie_name => "caf_assocsecret",
365             password_param_name => 'password',
366             srcdump_param_name => 'caf_srcdump',
367             username_param_names => [qw(username)],
368             form_entry_size => 60,
369             logout_param_names => [qw(caf_logout)],
370             loggedout_param_names => [qw(caf_loggedout)],
371             promise_check_mutate => 0,
372             get_param => sub { $_[0]->param($_[2]) },
373             get_params => sub { $_[1]->get_params() },
374             get_path_info => sub { $_[0]->path_info() },
375             get_cookie => sub { $_[0]->cookie($_[1]->{S}{cookie_name}) },
376             get_method => sub { $_[0]->request_method() },
377             check_https => sub { !!$_[0]->https() },
378             get_url => sub { $_[0]->url(); },
379             is_login => sub { defined $_[1]->_rp('password_param_name') },
380             login_ok => \&login_ok_password,
381             username_password_error => sub { die },
382             is_logout => sub { $_[1]->has_a_param('logout_param_names') },
383             is_loggedout => sub { $_[1]->has_a_param('loggedout_param_names') },
384             is_page => sub { return 1 },
385             handle_divert => sub { return 0 },
386             do_redirect => \&do_redirect_cgi, # this hook is allowed to throw
387             cookie_path => "/",
388             get_cookie_domain => \&get_cookie_domain,
389             encrypted_only => 1,
390             gen_start_html => sub { $_[0]->start_html($_[2]); },
391             gen_footer_html => \&gen_plain_footer_html,
392             gen_licence_link_html => \&gen_plain_licence_link_html,
393             gen_source_link_html => \&gen_plain_source_link_html,
394             gen_end_html => sub { $_[0]->end_html(); },
395             gen_login_form => \&gen_plain_login_form,
396             gen_login_link => \&gen_plain_login_link,
397             gen_postmainpage_form => \&gen_postmainpage_form,
398             srcdump_dump => \&srcdump_dump,
399             srcdump_prepare => \&srcdump_dirscan_prepare,
400             srcdump_licence_path => undef,
401             srcdump_licence_files => [qw(AGPLv3 CGI/Auth/Flexible/AGPLv3)],
402             srcdump_includedirs => sub { return @INC; },
403             srcdump_system_dir => sub { $_[2] =~ m#^/etc/|^/usr/(?!local/)#; },
404             srcdump_process_dir => \&srcdump_process_dir,
405             srcdump_vcs_dirs => [qw(.git .hg .svn CVS)],
406             srcdump_byvcs_git => \&srcdump_byvcs_git,
407             srcdump_byvcs_hg => \&srcdump_byvcs_hg,
408             srcdump_byvcs_svn => \&srcdump_byvcs_svn,
409             srcdump_byvcs_cvs => \&srcdump_byvcs_cvs,
410             srcdump_novcs => \&srcdump_novcs,
411             srcdump_excludes => [qw(*~ *.bak *.tmp), '#*#'],
412             dump => \&dump_plain,
413             gettext => sub { gettext($_[2]); },
414             print => sub { print $_[2] or die $!; },
415             debug => sub { }, # like print; msgs contain trailing \n
416         },
417         Dbh => undef,
418     };
419     my ($k,$v);
420     while (($k,$v,@_) = @_) {
421         die "unknown setting $k" unless exists $verifier->{S}{$k};
422         $verifier->{S}{$k} = $v;
423     }
424     bless $verifier, $class;
425     $verifier->_dbopen();
426     $verifier->_ch('srcdump_prepare');
427     return $verifier;
428 }
429
430 sub _db_setup_do ($$) {
431     my ($v, $sql) = @_;
432     my $dbh = $v->{Dbh};
433     eval {
434         $v->_db_transaction(sub {
435             local ($dbh->{PrintError}) = 0;
436             $dbh->do($sql);
437         });
438     };
439 }
440
441 sub _dbopen ($) {
442     my ($v) = @_;
443     my $dbh = $v->{Dbh};
444     return $dbh if $dbh; 
445
446     $dbh = $v->{S}{assocdb_dbh};
447     if ($dbh) {
448         die if $dbh->{AutoCommit};
449         die unless $dbh->{RaiseError};
450     } else {
451         $v->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=".$v->_get_path('assocdb');
452         my $dsn = $v->{S}{assocdb_dsn};
453
454         my $u = umask 077;
455         $dbh = DBI->connect($dsn, $v->{S}{assocdb_user},
456                             $v->{S}{assocdb_password}, {
457                                 AutoCommit => 0,
458                                 RaiseError => 1,
459                                 ShowErrorStatement => 1,
460                             });
461         umask $u;
462         die "$dsn $! ?" unless $dbh;
463     }
464     $v->{Dbh} = $dbh;
465
466     $v->_db_setup_do("CREATE TABLE $v->{S}{assocdb_table} (".
467                      " assochash VARCHAR PRIMARY KEY,".
468                      " username VARCHAR NOT NULL,".
469                      " last INTEGER NOT NULL".
470                      ")");
471     $v->_db_setup_do("CREATE INDEX $v->{S}{assocdb_table}_timeout_index".
472                      " ON $v->{S}{assocdb_table}".
473                      " (last)");
474     return $dbh;
475 }
476
477 sub disconnect ($) {
478     my ($v) = @_;
479     my $dbh = $v->{Dbh};
480     return unless $dbh;
481     $dbh->disconnect();
482 }
483
484 sub _db_transaction ($$) {
485     my ($v, $fn) = @_;
486     my $retries = 10;
487     my $rv;
488     my $dbh = $v->{Dbh};
489 #print STDERR "DT entry\n";
490     for (;;) {
491 #print STDERR "DT loop\n";
492         if (!eval {
493             $rv = $fn->();
494 #print STDERR "DT fn ok\n";
495             1;
496         }) {
497 #print STDERR "DT fn error\n";
498             { local ($@); $dbh->rollback(); }
499 #print STDERR "DT fn throwing\n";
500             die $@;
501         }
502 #print STDERR "DT fn eval ok\n";
503         if (eval {
504             $dbh->commit();
505 #print STDERR "DT commit ok\n";
506             1;
507         }) {
508 #print STDERR "DT commit eval ok ",Dumper($rv);
509             return $rv;
510         }
511 #print STDERR "DT commit throw?\n";
512         die $@ if !--$retries;
513 #print STDERR "DT loop again\n";
514     }
515 }
516
517 #---------- request object methods ----------
518
519 sub new_request {
520     my ($classbase, $cgi, @extra) = @_;
521     if (!ref $classbase) {
522         $classbase = $classbase->new_verifier(@extra);
523     } else {
524         die if @extra;
525     }
526     my $r = {
527         V => $classbase,
528         S => $classbase->{S},
529         Dbh => $classbase->{Dbh},
530         Cgi => $cgi,
531     };
532     bless $r, ref $classbase;
533 }
534
535 sub _ch ($$@) { # calls an application hook
536     my ($r,$methname, @args) = @_;
537     my $methfunc = $r->{S}{$methname};
538     die "$methname ?" unless $methfunc;
539     return $methfunc->($r->{Cgi}, $r, @args);
540 }
541
542 sub _rp ($$@) {
543     my ($r,$pnvb) = @_;
544     my $pn = $r->{S}{$pnvb};
545     my $p = scalar $r->_ch('get_param',$pn)
546 }
547
548 sub _debug ($@) {
549     my ($r,@args) = @_;
550     $r->_ch('debug',@args);
551 }
552
553 sub _get_path ($$) {
554     my ($r,$keybase) = @_;
555     my $leaf = $r->{S}{"${keybase}_path"};
556     return $r->_absify_path($leaf);
557 }
558
559 sub _absify_path ($$) {
560     my ($v,$leaf) = @_;
561     return $leaf if $leaf =~ m,^/,;
562     my $dir = $v->{S}{dir};
563     die "relying on cwd by default ?!  set dir" unless defined $dir;
564     return "$dir/$leaf";
565 }
566
567 sub _gt ($$) { my ($r, $t) = @_; return $r->_ch('gettext',$t); }
568 sub _print ($$) { my ($r, @t) = @_; return $r->_ch('print', join '', @t); }
569
570 sub construct_cookie ($$$) {
571     my ($r, $cooks) = @_;
572     return undef unless $cooks;
573     my $c = $r->{Cgi};
574 my @ca = (-name => $r->{S}{cookie_name},
575                              -value => $cooks,
576                              -path => $r->{S}{cookie_path},
577                              -domain => $r->_ch('get_cookie_domain'),
578                              -expires => '+'.$r->{S}{login_timeout}.'s',
579                              -secure => $r->{S}{encrypted_only});
580     my $cookie = $c->cookie(@ca);
581 #print STDERR "CC $r $c $cooks $cookie (@ca).\n";
582     return $cookie;
583 }
584
585 # pages/param-sets are
586 #   n normal non-mutating page
587 #   r retrieval of information for JS, non-mutating
588 #   m mutating page
589 #   u update of information by JS, mutating
590 #   i login
591 #   o logout
592 #   O "you have just logged out" page load
593
594 # in cook and par,
595 #    -         no value supplied (represented in code as $cookt='')
596 #    n, nN     value not in our db
597 #    t, tN     temporary value (in our db, no logged in user yet)
598 #    y, yN     value corresponds to logged-in user
599 # and, aggregated conditions:
600 #    a, aN     anything including -
601 #    x, xN     t or y
602 # if N differs the case applies only when the two values differ
603 # (eg,   a1 y2   does not apply when the logged-in value is supplied twice)
604
605 # "stale session" means request originates from a page from a login
606 # session which has been revoked (eg by logout); "cleared session"
607 # means request originates from a browser which has a different (or
608 # no) cookie.
609
610     # Case analysis, cookie mode, app promises re mutate:
611     # cook parm meth form
612     #                      
613     #  any -   POST  nrmuoi   bug or attack, fail
614     #  any -   GET    rmuoi   bug or attack, fail
615     #  any any GET     muoi   bug or attack, fail
616     #  any t   any   nrmu     bug or attack, fail
617     #
618     #  -   -   GET         O  "just logged out" page
619     #  (any other)         O  bug or attack, fail
620     #
621     #  a1  a2  POST      o    logout
622     #                           if a1 is valid, revoke it
623     #                           if a2 is valid, revoke it
624     #                           delete cookie
625     #                           redirect to "just logged out" page
626     #                             (which contains link to login form)
627     #
628     #  -   t   POST       i   complain about cookies being disabled
629     #                           (with link to login form)
630     #
631     #  t1  t1  POST       i   login (or switch user)
632     #                           if bad
633     #                             show new login form
634     #                           if good
635     #                             upgrade t1 to y1 in our db (setting username)
636     #                             redirect to GET of remaining params
637     #
638     #  y1  a2  POST       i   complain about stale login form
639     #                           revoke y1
640     #                           show new login form
641     #                           
642     #  (other) POST       i   complain about stale login form
643     #                           show new login form
644     #
645     #  t1  a2  ANY   nrmu     treat as  - a2 ANY
646     #
647     #  y   -   GET   n        cross-site link
648     #                           show data
649     #
650     #  y   y   GET   nr       fine, show page or send data
651     #  y   y   POST  nrmu     mutation is OK, do operation
652     #
653     #  y1  y2  GET   nr       request from stale page
654     #                           do not revoke y2 as not RESTful
655     #                           treat as   y1 n GET
656     #
657     #  y1  y2  POST  nrmu     request from stale page
658     #                           revoke y2
659     #                           treat as   y1 n POST
660     #
661     #  y   n   GET   n        intra-site link from stale page,
662     #                           treat as cross-site link, show data
663     #
664     #  y   n   POST  n m      intra-site form submission from stale page
665     #                           show "session interrupted"
666     #                           with link to main data page
667     #
668     #  y   n   GET    r       intra-site request from stale page
669     #                           fail
670     #
671     #  y   n   POST   r u     intra-site request from stale page
672     #                           fail
673     #
674     #  -/n y2  GET   nr       intra-site link from cleared session
675     #                           do not revoke y2 as not RESTful
676     #                           treat as   -/n n GET
677     #
678     #  -/n y2  POST  nrmu     request from cleared session
679     #                           revoke y2
680     #                           treat as   -/n n POST
681     #
682     #  -/n -/n GET   n        cross-site link but user not logged in
683     #                           show login form with redirect to orig params
684     #                           generate fresh cookie
685     #
686     #  -/n n   GET    rmu     user not logged in
687     #                           fail
688     #
689     #  -/n n   POST  n m      user not logged in
690     #                           show login form
691     #
692     #  -/n n   POST   r u     user not logged in
693     #                           fail
694
695 sub _check_divert_core ($) {
696     my ($r) = @_;
697
698     my $srcdump = $r->_rp('srcdump_param_name');
699     if ($srcdump) {
700         die if $srcdump =~ m/\W/;
701         return ({ Kind => 'SRCDUMP-'.uc $srcdump,
702                   Message => undef,
703                   CookieSecret => undef,
704                   Params => { } });
705     }
706
707     my $cooks = $r->_ch('get_cookie');
708
709     if ($r->{S}{encrypted_only} && !$r->_ch('check_https')) {
710         return ({ Kind => 'REDIRECT-HTTPS',
711                   Message => $r->_gt("Redirecting to secure server..."),
712                   CookieSecret => undef,
713                   Params => { } });
714     }
715
716     my $meth = $r->_ch('get_method');
717     my $parmh = $r->_rp('assoc_param_name');
718     my $cookh = defined $cooks ? $r->hash($cooks) : undef;
719
720     my ($cookt,$cooku) = $r->_identify($cookh, $cooks);
721     my $parms = (defined $cooks && defined $parmh && $parmh eq $cookh)
722         ? $cooks : undef;
723     my ($parmt) = $r->_identify($parmh, $parms);
724
725     $r->_debug("_c_d_c cookt=$cookt parmt=$parmt\n");
726
727     if ($r->_ch('is_logout')) {
728         $r->_must_be_post();
729         die unless $parmt;
730         $r->_db_revoke($cookh);
731         $r->_db_revoke($parmh);
732         return ({ Kind => 'REDIRECT-LOGGEDOUT',
733                   Message => $r->_gt("Logging out..."),
734                   CookieSecret => '',
735                   Params => { } });
736     }
737     if ($r->_ch('is_loggedout')) {
738         die unless $meth eq 'GET';
739         die if $cookt eq 'y';
740         die if $parmt;
741         return ({ Kind => 'SMALLPAGE-LOGGEDOUT',
742                   Message => $r->_gt("You have been logged out."),
743                   CookieSecret => '',
744                   Params => { } });
745     }
746     if ($r->_ch('is_login')) {
747         $r->_must_be_post();
748         die unless $parmt;
749         if (!$cookt && $parmt eq 'n') {
750             return ({ Kind => 'SMALLPAGE-NOCOOKIE',
751                       Message => $r->_gt("You do not seem to have cookies".
752                                          " enabled.  You must enable cookies".
753                                          " as we use them for login."),
754                       CookieSecret => $r->_fresh_secret(),
755                       Params => $r->chain_params() })
756         }
757         if (!$cookt || $cookt eq 'n' || $cookh ne $parmh) {
758             $r->_db_revoke($cookh);
759             return ({ Kind => 'LOGIN-STALE',
760                       Message => $r->_gt("Stale session;".
761                                          " you need to log in again."),
762                       CookieSecret => $r->_fresh_secret(),
763                       Params => { } })
764         }
765         die unless $parmt eq 't' || $parmt eq 'y';
766         my ($username, $login_errormessage) = $r->_ch('login_ok');
767         unless (defined $username && length $username) {
768             $login_errormessage = $r->_gt("Incorrect username/password.")
769                 if !$login_errormessage;
770             return ({ Kind => 'LOGIN-BAD',
771                       Message => $login_errormessage,
772                       CookieSecret => $cooks,
773                       Params => $r->chain_params() })
774         }
775         $r->_db_record_login_ok($parmh,$username);
776         return ({ Kind => 'REDIRECT-LOGGEDIN',
777                   Message => $r->_gt("Logging in..."),
778                   CookieSecret => $cooks,
779                   Params => $r->chain_params() });
780     }
781     if ($cookt eq 't') {
782         $cookt = '';
783     }
784     die if $parmt eq 't';
785
786     if ($cookt eq 'y' && $parmt eq 'y' && $cookh ne $parmh) {
787         $r->_db_revoke($parmh) if $meth eq 'POST';
788         $parmt = 'n';
789     }
790
791     if ($cookt ne 'y') {
792         die unless !$cookt || $cookt eq 'n';
793         die unless !$parmt || $parmt eq 'n' || $parmt eq 'y';
794         my $news = $r->_fresh_secret();
795         if ($meth eq 'GET') {
796             return ({ Kind => 'LOGIN-INCOMINGLINK',
797                       Message => $r->_gt("You need to log in."),
798                       CookieSecret => $news,
799                       Params => $r->chain_params() });
800         } else {
801             $r->_db_revoke($parmh);
802             return ({ Kind => 'LOGIN-FRESH',
803                       Message => $r->_gt("You need to log in."),
804                       CookieSecret => $news,
805                       Params => { } });
806         }
807     }
808
809     if (!$r->{S}{promise_check_mutate}) {
810         if ($meth ne 'POST') {
811             return ({ Kind => 'MAINPAGEONLY',
812                       Message => $r->_gt('Entering via cross-site link.'),
813                       CookieSecret => $cooks,
814                       Params => { } });
815             # NB caller must then ignore params & path!
816             # if this is too hard they can spit out a small form
817             # with a "click to continue"
818         }
819     }
820
821     die unless $cookt eq 'y';
822     unless ($r->{S}{promise_check_mutate} && $meth eq 'GET') {
823         die unless $parmt eq 'y';
824         die unless $cookh eq $parmh;
825     }
826     $r->{AssocSecret} = $cooks;
827     $r->{UserOK} = $cooku;
828 #print STDERR "C-D-C OK\n";
829     return undef;
830 }
831
832 sub chain_params ($) {
833     my ($r) = @_;
834     my %p = %{ $r->_ch('get_params') };
835     foreach my $pncn (keys %{ $r->{S} }) {
836         my $names;
837         if ($pncn =~ m/_param_name$/) {
838             my $name = $r->{S}{$pncn};
839             die "$pncn ?" if ref $name;
840             $names = [ $name ];
841         } elsif ($pncn =~ m/_param_names$/) {
842             $names = $r->{S}{$pncn};
843         } else {
844             next;
845         }
846         foreach my $name (@$names) {
847             delete $p{$name};
848         }
849     }
850     my $dummy_prefix = $r->{S}{dummy_param_name_prefix};
851     foreach my $name (grep /^$dummy_prefix/, keys %p) {
852         delete $p{$name};
853     }
854     die if exists $p{''};
855     $p{''} = [ $r->_ch('get_path_info') ];
856     return \%p;
857 }
858
859 sub _identify ($$) {
860     my ($r,$h,$s) = @_;
861     # returns ($t,$username)
862     # where $t is one of "t" "y" "n", or "" (for -)
863     # either $s must be undef, or $h eq $r->hash($s)
864
865 #print STDERR "_identify\n";
866     return '' unless defined $h && length $h;
867 #print STDERR "_identify h=$h s=".(defined $s ? $s : '<undef>')."\n";
868
869     my $dbh = $r->{Dbh};
870
871     $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
872              " WHERE last < ?", {},
873              time - $r->{S}{login_timeout});
874
875     my $row = $dbh->selectrow_arrayref("SELECT username, last".
876                               " FROM $r->{S}{assocdb_table}".
877                               " WHERE assochash = ?", {}, $h);
878     if (defined $row) {
879 #print STDERR "_identify h=$h s=$s YES @$row\n";
880         my ($nusername, $nlast) = @$row;
881         return ('y', $nusername);
882     }
883
884     # Well, it's not in the database.  But maybe it's a hash of a
885     # temporary secret.
886
887     return 'n' unless defined $s;
888
889     my ($keyt, $signature, $message, $noncet, $nonce) =
890         $s =~ m/^(\d+)\.(\w+)\.((\d+)\.(\w+))$/ or die;
891
892     return 'n' if time > $noncet + $r->{S}{login_form_timeout};
893
894 #print STDERR "_identify noncet=$noncet ok\n";
895
896     my $keys = $r->_open_keys();
897     while (my ($rkeyt, $rkey, $line) = $r->_read_key($keys)) {
898 #print STDERR "_identify  search rkeyt=$rkeyt rkey=$rkey\n";
899         last if $rkeyt < $keyt; # too far down in the file
900         my $trysignature = $r->_hmac($rkey, $message);
901 #print STDERR "_identify  search rkeyt=$rkeyt rkey=$rkey try=$trysignature\n";
902         return 't' if $trysignature eq $signature;
903     }
904     # oh well
905 #print STDERR "_identify NO\n";
906
907     $keys->error and die $!;
908     return 'n';
909 }
910
911 sub _db_revoke ($$) {
912     # revokes $h if it's valid; no-op if it's not
913     my ($r,$h) = @_;
914
915     my $dbh = $r->{Dbh};
916
917     $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
918              " WHERE assochash = ?", {}, $h);
919 }
920
921 sub _db_record_login_ok ($$$) {
922     my ($r,$h,$user) = @_;
923     $r->_db_revoke($h);
924     my $dbh = $r->{Dbh};
925     $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
926              " (assochash, username, last) VALUES (?,?,?)", {},
927              $h, $user, time);
928 }
929
930 sub check_divert ($) {
931     my ($r) = @_;
932     if (exists $r->{Divert}) {
933         return $r->{Divert};
934     }
935     my $dbh = $r->{Dbh};
936     $r->{Divert} = $r->_db_transaction(sub { $r->_check_divert_core(); });
937     $dbh->commit();
938     $r->_debug(Data::Dumper->Dump([$r->{Divert}],[qw(divert)]));
939     return $r->{Divert};
940 }
941
942 sub get_divert ($) {
943     my ($r) = @_;
944     die "unchecked" unless exists $r->{Divert};
945     return $r->{Divert};
946 }
947
948 sub get_username ($) {
949     my ($r) = @_;
950     my $divert = $r->get_divert();
951     return undef if $divert;
952     return $r->{UserOK};
953 }
954
955 sub url_with_query_params ($$) {
956     my ($r, $params) = @_;
957 #print STDERR "PARAMS ",Dumper($params);
958     my $uri = URI->new($r->_ch('get_url'));
959     $uri->path($uri->path() . $params->{''}[0]) if $params->{''};
960     $uri->query_form(flatten_params($params));
961     return $uri->as_string();
962 }
963
964 sub _cgi_header_args ($$@) {
965     my ($r, $cookie, @ha) = @_;
966     unshift @ha, qw(-type text/html);
967     push @ha, (-cookie => $cookie) if defined $cookie;
968 #print STDERR "_cgi_header_args ",join('|',@ha),".\n";
969     return @ha;
970 }
971
972 sub check_ok ($) {
973     my ($r) = @_;
974
975     my ($divert) = $r->check_divert();
976     return 1 if !$divert;
977
978     my $handled = $r->_ch('handle_divert',$divert);
979     return 0 if $handled;
980
981     my $kind = $divert->{Kind};
982     my $cookiesecret = $divert->{CookieSecret};
983     my $params = $divert->{Params};
984     my $cookie = $r->construct_cookie($cookiesecret);
985
986     if ($kind =~ m/^SRCDUMP-(\w+)$/) {
987         $r->_ch('srcdump_dump', (lc $1));
988         return 0;
989     }
990
991     if ($kind =~ m/^REDIRECT-/) {
992         # for redirects, we honour stored NextParams and SetCookie,
993         # as we would for non-divert
994         if ($kind eq 'REDIRECT-LOGGEDOUT') {
995             $params->{$r->{S}{loggedout_param_names}[0]} = [ 1 ];
996         } elsif ($kind eq 'REDIRECT-LOGOUT') {
997             $params->{$r->{S}{logout_param_names}[0]} = [ 1 ];
998         } elsif ($kind =~ m/REDIRECT-(?:LOGGEDIN|HTTPS)/) {
999         } else {
1000             die;
1001         }
1002         my $new_url = $r->url_with_query_params($params);
1003         if ($kind eq 'REDIRECT-HTTPS') {
1004             my $uri = URI->new($new_url);
1005             die unless $uri->scheme eq 'http';
1006             $uri->scheme('https');
1007             $new_url = $uri->as_string();
1008         }
1009         $r->_ch('do_redirect',$new_url, $cookie);
1010         return 0;
1011     }
1012
1013     if (defined $cookiesecret) {
1014         $params->{$r->{S}{assoc_param_name}} = [ $r->hash($cookiesecret) ];
1015     }
1016
1017     my ($title, @body);
1018     if ($kind =~ m/^LOGIN-/) {
1019         $title = $r->_gt('Login');
1020         push @body, $divert->{Message};
1021         push @body, $r->_ch('gen_login_form', $params);
1022     } elsif ($kind =~ m/^SMALLPAGE-/) {
1023         $title = $r->_gt('Not logged in');
1024         push @body, $divert->{Message};
1025         push @body, $r->_ch('gen_login_link', $params);
1026     } elsif ($kind =~ m/^MAINPAGEONLY$/) {
1027         $title = $r->_gt('Entering secure site.');
1028         push @body, $divert->{Message};
1029         push @body, $r->_ch('gen_postmainpage_form', $params);
1030     } else {
1031         die $kind;
1032     }
1033
1034     $r->_print($r->{Cgi}->header($r->_cgi_header_args($cookie)),
1035                $r->_ch('gen_start_html',$title),
1036                (join "\n", (@body,
1037                             $r->_ch('gen_footer_html'),
1038                             $r->_ch('gen_end_html'))));
1039     return 0;
1040 }
1041
1042 sub _random ($$) {
1043     my ($r, $bytes) = @_;
1044     my $v = $r->{V};
1045     my $rsf = $v->{RandomHandle};
1046     my $rsp = $r->{S}{random_source};
1047     if (!$rsf) {
1048         $v->{RandomHandle} = $rsf = new IO::File $rsp, '<' or die "$rsp $!";
1049 #print STDERR "RH $rsf\n";
1050     }
1051     my $bin;
1052     $!=0;
1053     read($rsf,$bin,$bytes) == $bytes or die "$rsp $!";
1054     my $out = unpack "H*", $bin;
1055 #print STDERR "_random out $out\n";
1056     return $out;
1057 }
1058
1059 sub _random_key ($) {
1060     my ($r) = @_;
1061 #print STDERR "_random_key\n";
1062     my $bytes = ($r->{S}{secretbits} + 7) >> 3;
1063     return $r->_random($bytes);
1064 }
1065
1066 sub _read_key ($$) {
1067     my ($r, $keys) = @_;
1068     # returns $gen_time_t, $key_value_in_hex, $complete_line
1069     while (<$keys>) {
1070         my ($gen, $k) = m/^(\d+) (\S+)$/ or die "$_ ?";
1071         my $age = time - $gen;
1072         next if $age > $r->{S}{key_rollover} &&
1073             $age > $r->{S}{login_form_timeout}*2;
1074         return ($gen, $k, $_);
1075     }
1076     return ();
1077 }
1078
1079 sub _open_keys ($) {
1080     my ($r) = @_;
1081     my $spath = $r->_get_path('keys');
1082     for (;;) {
1083 #print STDERR "_open_keys\n";
1084         my $keys = new IO::File $spath, 'r+';
1085         if ($keys) {
1086 #print STDERR "_open_keys open\n";
1087             stat $keys or die $!; # NB must not disturb stat _
1088             my $size = (stat _)[7];
1089             my $age = time - (stat _)[9];
1090 #print STDERR "_open_keys open size=$size age=$age\n";
1091             return $keys
1092                 if $size && $age <= $r->{S}{key_rollover} / 2;
1093 #print STDERR "_open_keys open bad\n";
1094         }
1095         # file doesn't exist, or is empty or too old
1096         if (!$keys) {
1097 #print STDERR "_open_keys closed\n";
1098             die "$spath $!" unless $!==&ENOENT;
1099             # doesn't exist, so create it just so we can lock it
1100             $keys = new IO::File $spath, 'a+';
1101             die "$keys $!" unless $keys;
1102             stat $keys or die $!; # NB must not disturb stat _
1103             my $size = (stat _)[7];
1104 #print STDERR "_open_keys created size=$size\n";
1105             next if $size; # oh someone else has done it, reopen and read it
1106         }
1107         # file now exists is empty or too old, we must try to replace it
1108         my $our_inum = (stat _)[1]; # last use of that stat _
1109         flock $keys, LOCK_EX or die "$spath $!";
1110         stat $spath or die "$spath $!";
1111         my $path_inum = (stat _)[1];
1112 #print STDERR "_open_keys locked our=$our_inum path=$path_inum\n";
1113         next if $our_inum != $path_inum; # someone else has done it
1114         # We now hold the lock!
1115 #print STDERR "_open_keys creating\n";
1116         my $newkeys = new IO::Handle;
1117         sysopen $newkeys, "$spath.new", O_CREAT|O_TRUNC|O_WRONLY, 0600
1118             or die "$spath.new $!";
1119         # we add the new key to the front which means it's always sorted
1120         print $newkeys time, ' ', $r->_random_key(), "\n" or die $!;
1121         while (my ($gen,$key,$line) = $r->_read_key($keys)) {
1122 #print STDERR "_open_keys copy1\n";
1123             print $newkeys, $line or die $!;
1124         }
1125         $keys->error and die $!;
1126         close $newkeys or die "$spath.new $!";
1127         rename "$spath.new", "$spath" or die "$spath: $!";
1128 #print STDERR "_open_keys installed\n";
1129         # that rename effective unlocks, since it makes the name refer
1130         #  to the new file which we haven't locked
1131         # we go round again opening the file at the beginning
1132         #  so that our caller gets a fresh handle onto the existing key file
1133     }
1134 }
1135
1136 sub _fresh_secret ($) {
1137     my ($r) = @_;
1138 #print STDERR "_fresh_secret\n";
1139
1140     my $keys = $r->_open_keys();
1141     my ($keyt, $key) = $r->_read_key($keys);
1142     die unless defined $keyt;
1143
1144     my $nonce = $r->_random_key();
1145     my $noncet = time;
1146     my $message = "$noncet.$nonce";
1147
1148     my $signature = $r->_hmac($key, $message);
1149     my $secret = "$keyt.$signature.$message";
1150 #print STDERR "FRESH $secret\n";
1151     return $secret;
1152 }
1153
1154 sub _hmac ($$$) {
1155     my ($r, $keyhex, $message) = @_;
1156     my $keybin = pack "H*", $keyhex;
1157     my $alg = $r->{S}{hash_algorithm};
1158 #print STDERR "hmac $alg\n";
1159     my $base = new Digest $alg;
1160 #print STDERR "hmac $alg $base\n";
1161     my $digest = new Digest::HMAC $keybin, $base;
1162 #print STDERR "hmac $alg $base $digest\n";
1163     $digest->add($message);
1164     return $digest->hexdigest();
1165 }
1166
1167 sub hash ($$) {
1168     my ($r, $message) = @_;
1169     my $alg = $r->{S}{hash_algorithm};
1170 #print STDERR "hash $alg\n";
1171     my $digest = new Digest $alg;
1172     $digest->add($message);
1173     return $digest->hexdigest();
1174 }
1175
1176 sub _assert_checked ($) {
1177     my ($r) = @_;
1178     die "unchecked" unless exists $r->{Divert};
1179 }
1180
1181 sub _is_post ($) {
1182     my ($r) = @_;
1183     my $meth = $r->_ch('get_method');
1184     return $meth eq 'POST';
1185 }
1186
1187 sub _must_be_post ($) {
1188     my ($r) = @_;
1189     my $meth = $r->_ch('get_method');
1190     die "mutating non-POST" if $meth ne 'POST';
1191 }
1192
1193 sub check_mutate ($) {
1194     my ($r) = @_;
1195     $r->_assert_checked();
1196     die if $r->{Divert};
1197     $r->_must_be_post();
1198 }
1199
1200 sub mutate_ok ($) {
1201     my ($r) = @_;
1202     $r->_assert_checked();
1203     die if $r->{Divert};
1204     return $r->_is_post();
1205 }
1206
1207 #---------- output ----------
1208
1209 sub secret_cookie_val ($) {
1210     my ($r) = @_;
1211     $r->_assert_checked();
1212     return defined $r->{AssocSecret} ? $r->{AssocSecret} : '';
1213 }
1214
1215 sub secret_hidden_val ($) {
1216     my ($r) = @_;
1217     $r->_assert_checked();
1218     return defined $r->{AssocSecret} ? $r->hash($r->{AssocSecret}) : '';
1219 }
1220
1221 sub secret_hidden_html ($) {
1222     my ($r) = @_;
1223     return $r->{Cgi}->hidden(-name => $r->{S}{assoc_param_name},
1224                              -default => $r->secret_hidden_val());
1225 }
1226
1227 sub secret_cookie ($) {
1228     my ($r) = @_;
1229     my $secret = $r->secret_cookie_val();
1230     return undef if !defined $secret;
1231 #print STDERR "SC\n";
1232     my $cookv = $r->construct_cookie($secret); 
1233 #print STDERR "SC=$cookv\n";
1234     return $cookv;
1235 }
1236
1237 1;
1238
1239 __END__
1240
1241 =head1 NAME
1242
1243 CGI::Auth::Flexible - web authentication optionally using cookies
1244
1245 =head1 SYNOPSYS
1246
1247  my $verifier = CGI::Auth::Flexible->new_verifier(setting => value,...);
1248  my $authreq = $verifier->new_request($cgi_request_object);
1249
1250  my $authreq = CGI::Auth::Flexible->new_request($cgi_request_object,
1251                                               setting => value,...);
1252
1253 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
1254
1255  $authreq->check_ok() or return;
1256
1257  blah blah blah
1258  $authreq->check_mutate();
1259  blah blah blah
1260
1261 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
1262
1263  my $divert_kind = $authreq->check_divert();
1264  if ($divert_kind) {
1265      if ($divert_kind eq 'LOGGEDOUT') {
1266          print "goodbye you are now logged out" and quit
1267      } elsif ($divert_kind eq 'NOCOOKIES') {
1268          print "you need cookies" and quit
1269      ... etc.
1270      }
1271  }
1272
1273  blah blah blah
1274  $authreq->check_mutate();
1275  blah blah blah