chiark / gitweb /
4dd6daf2ddaca6fdc0c433cf26a7960b86593f0a
[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_thing ($$$) {
204     my ($c,$r, $thing, $outfn) = @_;
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     $ct->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 scrdump_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     my $lockf = new IO::File "$dumpdir/generate.lock", 'w+'
300         or die "$dumpdir/generate.lock $!";
301     flock $lockf, LOCK_EX or die "$dumpdir/generate.lock $!";
302     my $needlicence = "$dumpdir/licence.tmp";
303     unlink $needlicence || $!==&ENOENT or die "rm $needlicence $!";
304     if (defined $v->{S}{srcdump_licence_path}) {
305         copy($v->{S}{srcdump_licence_path}, $needlicence)
306             or die "$v->{S}{srcdump_licence_path} $!";
307         $needlicence = undef;
308     }
309     my $srctarballcounter = 'aaa';
310     my %dirsdone;
311     my @srcfiles = ("$dumpdir/licence.data");
312     foreach my $incdir ($v->_ch('getsource_includedirs')) {
313         if (defined $needlicence) {
314             foreach my $try (@{ $v->{S}{srcdump_licence_files} }) {
315                 last if copy("$incdir/$try", $needlicence);
316                 $!==&ENOENT or die "copy $incdir/$try $!";
317             }
318         }
319         push @srcfiles, $v->_ch('srcdump_process_dir', $dumpdir, $incdir,
320                                 \$srctarballcounter, \$needlicence, \%dirsdone);
321         $dirsdone{$incdir}++;
322     }
323     die "licence file not found" unless defined $needlicence;
324     srcdump_install($c,$v, $dumpdir, 'licence', 'text/plain');
325     close $lockf or die $!;
326 }
327
328 sub srcdump_install ($$$$$) {
329     my ($c,$v, $dumpdir, $which, $ctype) = @_;
330     rename "$dumpdir/$which.tmp", "$dumpdir/$which.data"
331         or die "$dumpdir/$which.data $!";
332     my $ctf = new IO::File "$dumpdir/$which.tmp", 'w'
333         or die "$dumpdir/$which.tmp $!";
334     print $ctf $ctype, "\n" or die $!;
335     close $ctf or die $!;
336     rename "$dumpdir/$which.tmp", "$dumpdir/$which.ctype"
337         or die "$dumpdir/$which.ctype $!";
338 }
339
340 #---------- verifier object methods ----------
341
342 sub new_verifier {
343     my $class = shift;
344     my $verifier = {
345         S => {
346             dir => undef,
347             assocdb_dbh => undef, # must have AutoCommit=0, RaiseError=1
348             assocdb_path => 'caf-assocs.db',
349             keys_path => 'caf-keys',
350             srcdump_path => 'caf-srcdump',
351             assocdb_dsn => undef,
352             assocdb_user => '',
353             assocdb_password => '',
354             assocdb_table => 'caf_assocs',
355             random_source => '/dev/urandom',
356             secretbits => 128, # bits
357             hash_algorithm => "SHA-256",
358             login_timeout => 86400, # seconds
359             login_form_timeout => 3600, # seconds
360             key_rollover => 86400, # seconds
361             assoc_param_name => 'caf_assochash',
362             dummy_param_name_prefix => 'caf__',
363             cookie_name => "caf_assocsecret",
364             password_param_name => 'password',
365             srcdump_param_name => 'caf_srcdump',
366             username_param_names => [qw(username)],
367             form_entry_size => 60,
368             logout_param_names => [qw(caf_logout)],
369             loggedout_param_names => [qw(caf_loggedout)],
370             promise_check_mutate => 0,
371             get_param => sub { $_[0]->param($_[2]) },
372             get_params => sub { $_[1]->get_params() },
373             get_path_info => sub { $_[0]->path_info() },
374             get_cookie => sub { $_[0]->cookie($_[1]->{S}{cookie_name}) },
375             get_method => sub { $_[0]->request_method() },
376             check_https => sub { !!$_[0]->https() },
377             get_url => sub { $_[0]->url(); },
378             is_login => sub { defined $_[1]->_rp('password_param_name') },
379             login_ok => \&login_ok_password,
380             username_password_error => sub { die },
381             is_logout => sub { $_[1]->has_a_param('logout_param_names') },
382             is_loggedout => sub { $_[1]->has_a_param('loggedout_param_names') },
383             is_page => sub { return 1 },
384             handle_divert => sub { return 0 },
385             do_redirect => \&do_redirect_cgi, # this hook is allowed to throw
386             cookie_path => "/",
387             get_cookie_domain => \&get_cookie_domain,
388             encrypted_only => 1,
389             gen_start_html => sub { $_[0]->start_html($_[2]); },
390             gen_footer_html => \&gen_plain_footer_html,
391             gen_licence_link_html => \&gen_plain_licence_link_html,
392             gen_source_link_html => \&gen_plain_source_link_html,
393             gen_end_html => sub { $_[0]->end_html(); },
394             gen_login_form => \&gen_plain_login_form,
395             gen_login_link => \&gen_plain_login_link,
396             gen_postmainpage_form => \&gen_postmainpage_form,
397             srcdump_dump_thing => \&srcdump_dump_thing,
398             srcdump_prepare => \&srcdump_dirscan_prepare,
399             srcdump_licence_path => undef,
400             srcdump_licence_files => [qw(AGPLv3 CGI/Auth/Flexible/AGPLv3)],
401             srcdump_system_dir => sub { $_[2] =~ m#^/etc/|^/usr/(?!local/)#; },
402             srcdump_vcs_dirs => [qw(.git .hg .svn CVS)],
403             srcdump_byvcs_git => \&srcdump_byvcs_git,
404             srcdump_byvcs_hg => \&srcdump_byvcs_hg,
405             srcdump_byvcs_svn => \&srcdump_byvcs_svn,
406             srcdump_byvcs_cvs => \&srcdump_byvcs_cvs,
407             srcdump_novcs => \&srcdump_novcs,
408             srcdump_excludes => [qw(*~ *.bak *.tmp), '#*#'],
409             gettext => sub { gettext($_[2]); },
410             print => sub { print $_[2] or die $!; },
411             debug => sub { }, # like print; msgs contain trailing \n
412         },
413         Dbh => undef,
414     };
415     my ($k,$v);
416     while (($k,$v,@_) = @_) {
417         die "unknown setting $k" unless exists $verifier->{S}{$k};
418         $verifier->{S}{$k} = $v;
419     }
420     bless $verifier, $class;
421     $verifier->_dbopen();
422     return $verifier;
423 }
424
425 sub _db_setup_do ($$) {
426     my ($v, $sql) = @_;
427     my $dbh = $v->{Dbh};
428     eval {
429         $v->_db_transaction(sub {
430             local ($dbh->{PrintError}) = 0;
431             $dbh->do($sql);
432         });
433     };
434 }
435
436 sub _dbopen ($) {
437     my ($v) = @_;
438     my $dbh = $v->{Dbh};
439     return $dbh if $dbh; 
440
441     $dbh = $v->{S}{assocdb_dbh};
442     if ($dbh) {
443         die if $dbh->{AutoCommit};
444         die unless $dbh->{RaiseError};
445     } else {
446         $v->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=".$v->_get_path('assocdb');
447         my $dsn = $v->{S}{assocdb_dsn};
448
449         my $u = umask 077;
450         $dbh = DBI->connect($dsn, $v->{S}{assocdb_user},
451                             $v->{S}{assocdb_password}, {
452                                 AutoCommit => 0,
453                                 RaiseError => 1,
454                                 ShowErrorStatement => 1,
455                             });
456         umask $u;
457         die "$dsn $! ?" unless $dbh;
458     }
459     $v->{Dbh} = $dbh;
460
461     $v->_db_setup_do("CREATE TABLE $v->{S}{assocdb_table} (".
462                      " assochash VARCHAR PRIMARY KEY,".
463                      " username VARCHAR NOT NULL,".
464                      " last INTEGER NOT NULL".
465                      ")");
466     $v->_db_setup_do("CREATE INDEX $v->{S}{assocdb_table}_timeout_index".
467                      " ON $v->{S}{assocdb_table}".
468                      " (last)");
469     return $dbh;
470 }
471
472 sub disconnect ($) {
473     my ($v) = @_;
474     my $dbh = $v->{Dbh};
475     return unless $dbh;
476     $dbh->disconnect();
477 }
478
479 sub _db_transaction ($$) {
480     my ($v, $fn) = @_;
481     my $retries = 10;
482     my $rv;
483     my $dbh = $v->{Dbh};
484 #print STDERR "DT entry\n";
485     for (;;) {
486 #print STDERR "DT loop\n";
487         if (!eval {
488             $rv = $fn->();
489 #print STDERR "DT fn ok\n";
490             1;
491         }) {
492 #print STDERR "DT fn error\n";
493             { local ($@); $dbh->rollback(); }
494 #print STDERR "DT fn throwing\n";
495             die $@;
496         }
497 #print STDERR "DT fn eval ok\n";
498         if (eval {
499             $dbh->commit();
500 #print STDERR "DT commit ok\n";
501             1;
502         }) {
503 #print STDERR "DT commit eval ok ",Dumper($rv);
504             return $rv;
505         }
506 #print STDERR "DT commit throw?\n";
507         die $@ if !--$retries;
508 #print STDERR "DT loop again\n";
509     }
510 }
511
512 #---------- request object methods ----------
513
514 sub new_request {
515     my ($classbase, $cgi, @extra) = @_;
516     if (!ref $classbase) {
517         $classbase = $classbase->new_verifier(@extra);
518     } else {
519         die if @extra;
520     }
521     my $r = {
522         V => $classbase,
523         S => $classbase->{S},
524         Dbh => $classbase->{Dbh},
525         Cgi => $cgi,
526     };
527     bless $r, ref $classbase;
528 }
529
530 sub _ch ($$@) { # calls an application hook
531     my ($r,$methname, @args) = @_;
532     my $methfunc = $r->{S}{$methname};
533     die "$methname ?" unless $methfunc;
534     return $methfunc->($r->{Cgi}, $r, @args);
535 }
536
537 sub _rp ($$@) {
538     my ($r,$pnvb) = @_;
539     my $pn = $r->{S}{$pnvb};
540     my $p = scalar $r->_ch('get_param',$pn)
541 }
542
543 sub _debug ($@) {
544     my ($r,@args) = @_;
545     $r->_ch('debug',@args);
546 }
547
548 sub _get_path ($$) {
549     my ($r,$keybase) = @_;
550     my $leaf = $r->{S}{"${keybase}_path"};
551     return $r->_absify_path($leaf);
552 }
553
554 sub _absify_path ($$) {
555     my ($v,$leaf) = @_;
556     return $leaf if $leaf =~ m,^/,;
557     my $dir = $v->{S}{dir};
558     die "relying on cwd by default ?!  set dir" unless defined $dir;
559     return "$dir/$leaf";
560 }
561
562 sub _gt ($$) { my ($r, $t) = @_; return $r->_ch('gettext',$t); }
563 sub _print ($$) { my ($r, @t) = @_; return $r->_ch('print', join '', @t); }
564
565 sub construct_cookie ($$$) {
566     my ($r, $cooks) = @_;
567     return undef unless $cooks;
568     my $c = $r->{Cgi};
569 my @ca = (-name => $r->{S}{cookie_name},
570                              -value => $cooks,
571                              -path => $r->{S}{cookie_path},
572                              -domain => $r->_ch('get_cookie_domain'),
573                              -expires => '+'.$r->{S}{login_timeout}.'s',
574                              -secure => $r->{S}{encrypted_only});
575     my $cookie = $c->cookie(@ca);
576 #print STDERR "CC $r $c $cooks $cookie (@ca).\n";
577     return $cookie;
578 }
579
580 # pages/param-sets are
581 #   n normal non-mutating page
582 #   r retrieval of information for JS, non-mutating
583 #   m mutating page
584 #   u update of information by JS, mutating
585 #   i login
586 #   o logout
587 #   O "you have just logged out" page load
588
589 # in cook and par,
590 #    -         no value supplied (represented in code as $cookt='')
591 #    n, nN     value not in our db
592 #    t, tN     temporary value (in our db, no logged in user yet)
593 #    y, yN     value corresponds to logged-in user
594 # and, aggregated conditions:
595 #    a, aN     anything including -
596 #    x, xN     t or y
597 # if N differs the case applies only when the two values differ
598 # (eg,   a1 y2   does not apply when the logged-in value is supplied twice)
599
600 # "stale session" means request originates from a page from a login
601 # session which has been revoked (eg by logout); "cleared session"
602 # means request originates from a browser which has a different (or
603 # no) cookie.
604
605     # Case analysis, cookie mode, app promises re mutate:
606     # cook parm meth form
607     #                      
608     #  any -   POST  nrmuoi   bug or attack, fail
609     #  any -   GET    rmuoi   bug or attack, fail
610     #  any any GET     muoi   bug or attack, fail
611     #  any t   any   nrmu     bug or attack, fail
612     #
613     #  -   -   GET         O  "just logged out" page
614     #  (any other)         O  bug or attack, fail
615     #
616     #  a1  a2  POST      o    logout
617     #                           if a1 is valid, revoke it
618     #                           if a2 is valid, revoke it
619     #                           delete cookie
620     #                           redirect to "just logged out" page
621     #                             (which contains link to login form)
622     #
623     #  -   t   POST       i   complain about cookies being disabled
624     #                           (with link to login form)
625     #
626     #  t1  t1  POST       i   login (or switch user)
627     #                           if bad
628     #                             show new login form
629     #                           if good
630     #                             upgrade t1 to y1 in our db (setting username)
631     #                             redirect to GET of remaining params
632     #
633     #  y1  a2  POST       i   complain about stale login form
634     #                           revoke y1
635     #                           show new login form
636     #                           
637     #  (other) POST       i   complain about stale login form
638     #                           show new login form
639     #
640     #  t1  a2  ANY   nrmu     treat as  - a2 ANY
641     #
642     #  y   -   GET   n        cross-site link
643     #                           show data
644     #
645     #  y   y   GET   nr       fine, show page or send data
646     #  y   y   POST  nrmu     mutation is OK, do operation
647     #
648     #  y1  y2  GET   nr       request from stale page
649     #                           do not revoke y2 as not RESTful
650     #                           treat as   y1 n GET
651     #
652     #  y1  y2  POST  nrmu     request from stale page
653     #                           revoke y2
654     #                           treat as   y1 n POST
655     #
656     #  y   n   GET   n        intra-site link from stale page,
657     #                           treat as cross-site link, show data
658     #
659     #  y   n   POST  n m      intra-site form submission from stale page
660     #                           show "session interrupted"
661     #                           with link to main data page
662     #
663     #  y   n   GET    r       intra-site request from stale page
664     #                           fail
665     #
666     #  y   n   POST   r u     intra-site request from stale page
667     #                           fail
668     #
669     #  -/n y2  GET   nr       intra-site link from cleared session
670     #                           do not revoke y2 as not RESTful
671     #                           treat as   -/n n GET
672     #
673     #  -/n y2  POST  nrmu     request from cleared session
674     #                           revoke y2
675     #                           treat as   -/n n POST
676     #
677     #  -/n -/n GET   n        cross-site link but user not logged in
678     #                           show login form with redirect to orig params
679     #                           generate fresh cookie
680     #
681     #  -/n n   GET    rmu     user not logged in
682     #                           fail
683     #
684     #  -/n n   POST  n m      user not logged in
685     #                           show login form
686     #
687     #  -/n n   POST   r u     user not logged in
688     #                           fail
689
690 sub _check_divert_core ($) {
691     my ($r) = @_;
692
693     my $srcdump = $r->_rp('srcdump_param_name');
694     if ($srcdump) {
695         die if $srcdump =~ m/\W/;
696         return ({ Kind => 'SRCDUMP-'.uc $srcdump,
697                   Message => undef,
698                   CookieSecret => undef,
699                   Params => { } });
700     }
701
702     my $cooks = $r->_ch('get_cookie');
703
704     if ($r->{S}{encrypted_only} && !$r->_ch('check_https')) {
705         return ({ Kind => 'REDIRECT-HTTPS',
706                   Message => $r->_gt("Redirecting to secure server..."),
707                   CookieSecret => undef,
708                   Params => { } });
709     }
710
711     my $meth = $r->_ch('get_method');
712     my $parmh = $r->_rp('assoc_param_name');
713     my $cookh = defined $cooks ? $r->hash($cooks) : undef;
714
715     my ($cookt,$cooku) = $r->_identify($cookh, $cooks);
716     my $parms = (defined $cooks && defined $parmh && $parmh eq $cookh)
717         ? $cooks : undef;
718     my ($parmt) = $r->_identify($parmh, $parms);
719
720     $r->_debug("_c_d_c cookt=$cookt parmt=$parmt\n");
721
722     if ($r->_ch('is_logout')) {
723         $r->_must_be_post();
724         die unless $parmt;
725         $r->_db_revoke($cookh);
726         $r->_db_revoke($parmh);
727         return ({ Kind => 'REDIRECT-LOGGEDOUT',
728                   Message => $r->_gt("Logging out..."),
729                   CookieSecret => '',
730                   Params => { } });
731     }
732     if ($r->_ch('is_loggedout')) {
733         die unless $meth eq 'GET';
734         die if $cookt eq 'y';
735         die if $parmt;
736         return ({ Kind => 'SMALLPAGE-LOGGEDOUT',
737                   Message => $r->_gt("You have been logged out."),
738                   CookieSecret => '',
739                   Params => { } });
740     }
741     if ($r->_ch('is_login')) {
742         $r->_must_be_post();
743         die unless $parmt;
744         if (!$cookt && $parmt eq 'n') {
745             return ({ Kind => 'SMALLPAGE-NOCOOKIE',
746                       Message => $r->_gt("You do not seem to have cookies".
747                                          " enabled.  You must enable cookies".
748                                          " as we use them for login."),
749                       CookieSecret => $r->_fresh_secret(),
750                       Params => $r->chain_params() })
751         }
752         if (!$cookt || $cookt eq 'n' || $cookh ne $parmh) {
753             $r->_db_revoke($cookh);
754             return ({ Kind => 'LOGIN-STALE',
755                       Message => $r->_gt("Stale session;".
756                                          " you need to log in again."),
757                       CookieSecret => $r->_fresh_secret(),
758                       Params => { } })
759         }
760         die unless $parmt eq 't' || $parmt eq 'y';
761         my ($username, $login_errormessage) = $r->_ch('login_ok');
762         unless (defined $username && length $username) {
763             $login_errormessage = $r->_gt("Incorrect username/password.")
764                 if !$login_errormessage;
765             return ({ Kind => 'LOGIN-BAD',
766                       Message => $login_errormessage,
767                       CookieSecret => $cooks,
768                       Params => $r->chain_params() })
769         }
770         $r->_db_record_login_ok($parmh,$username);
771         return ({ Kind => 'REDIRECT-LOGGEDIN',
772                   Message => $r->_gt("Logging in..."),
773                   CookieSecret => $cooks,
774                   Params => $r->chain_params() });
775     }
776     if ($cookt eq 't') {
777         $cookt = '';
778     }
779     die if $parmt eq 't';
780
781     if ($cookt eq 'y' && $parmt eq 'y' && $cookh ne $parmh) {
782         $r->_db_revoke($parmh) if $meth eq 'POST';
783         $parmt = 'n';
784     }
785
786     if ($cookt ne 'y') {
787         die unless !$cookt || $cookt eq 'n';
788         die unless !$parmt || $parmt eq 'n' || $parmt eq 'y';
789         my $news = $r->_fresh_secret();
790         if ($meth eq 'GET') {
791             return ({ Kind => 'LOGIN-INCOMINGLINK',
792                       Message => $r->_gt("You need to log in."),
793                       CookieSecret => $news,
794                       Params => $r->chain_params() });
795         } else {
796             $r->_db_revoke($parmh);
797             return ({ Kind => 'LOGIN-FRESH',
798                       Message => $r->_gt("You need to log in."),
799                       CookieSecret => $news,
800                       Params => { } });
801         }
802     }
803
804     if (!$r->{S}{promise_check_mutate}) {
805         if ($meth ne 'POST') {
806             return ({ Kind => 'MAINPAGEONLY',
807                       Message => $r->_gt('Entering via cross-site link.'),
808                       CookieSecret => $cooks,
809                       Params => { } });
810             # NB caller must then ignore params & path!
811             # if this is too hard they can spit out a small form
812             # with a "click to continue"
813         }
814     }
815
816     die unless $cookt eq 'y';
817     unless ($r->{S}{promise_check_mutate} && $meth eq 'GET') {
818         die unless $parmt eq 'y';
819         die unless $cookh eq $parmh;
820     }
821     $r->{AssocSecret} = $cooks;
822     $r->{UserOK} = $cooku;
823 #print STDERR "C-D-C OK\n";
824     return undef;
825 }
826
827 sub chain_params ($) {
828     my ($r) = @_;
829     my %p = %{ $r->_ch('get_params') };
830     foreach my $pncn (keys %{ $r->{S} }) {
831         my $names;
832         if ($pncn =~ m/_param_name$/) {
833             my $name = $r->{S}{$pncn};
834             die "$pncn ?" if ref $name;
835             $names = [ $name ];
836         } elsif ($pncn =~ m/_param_names$/) {
837             $names = $r->{S}{$pncn};
838         } else {
839             next;
840         }
841         foreach my $name (@$names) {
842             delete $p{$name};
843         }
844     }
845     my $dummy_prefix = $r->{S}{dummy_param_name_prefix};
846     foreach my $name (grep /^$dummy_prefix/, keys %p) {
847         delete $p{$name};
848     }
849     die if exists $p{''};
850     $p{''} = [ $r->_ch('get_path_info') ];
851     return \%p;
852 }
853
854 sub _identify ($$) {
855     my ($r,$h,$s) = @_;
856     # returns ($t,$username)
857     # where $t is one of "t" "y" "n", or "" (for -)
858     # either $s must be undef, or $h eq $r->hash($s)
859
860 #print STDERR "_identify\n";
861     return '' unless defined $h && length $h;
862 #print STDERR "_identify h=$h s=".(defined $s ? $s : '<undef>')."\n";
863
864     my $dbh = $r->{Dbh};
865
866     $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
867              " WHERE last < ?", {},
868              time - $r->{S}{login_timeout});
869
870     my $row = $dbh->selectrow_arrayref("SELECT username, last".
871                               " FROM $r->{S}{assocdb_table}".
872                               " WHERE assochash = ?", {}, $h);
873     if (defined $row) {
874 #print STDERR "_identify h=$h s=$s YES @$row\n";
875         my ($nusername, $nlast) = @$row;
876         return ('y', $nusername);
877     }
878
879     # Well, it's not in the database.  But maybe it's a hash of a
880     # temporary secret.
881
882     return 'n' unless defined $s;
883
884     my ($keyt, $signature, $message, $noncet, $nonce) =
885         $s =~ m/^(\d+)\.(\w+)\.((\d+)\.(\w+))$/ or die;
886
887     return 'n' if time > $noncet + $r->{S}{login_form_timeout};
888
889 #print STDERR "_identify noncet=$noncet ok\n";
890
891     my $keys = $r->_open_keys();
892     while (my ($rkeyt, $rkey, $line) = $r->_read_key($keys)) {
893 #print STDERR "_identify  search rkeyt=$rkeyt rkey=$rkey\n";
894         last if $rkeyt < $keyt; # too far down in the file
895         my $trysignature = $r->_hmac($rkey, $message);
896 #print STDERR "_identify  search rkeyt=$rkeyt rkey=$rkey try=$trysignature\n";
897         return 't' if $trysignature eq $signature;
898     }
899     # oh well
900 #print STDERR "_identify NO\n";
901
902     $keys->error and die $!;
903     return 'n';
904 }
905
906 sub _db_revoke ($$) {
907     # revokes $h if it's valid; no-op if it's not
908     my ($r,$h) = @_;
909
910     my $dbh = $r->{Dbh};
911
912     $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
913              " WHERE assochash = ?", {}, $h);
914 }
915
916 sub _db_record_login_ok ($$$) {
917     my ($r,$h,$user) = @_;
918     $r->_db_revoke($h);
919     my $dbh = $r->{Dbh};
920     $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
921              " (assochash, username, last) VALUES (?,?,?)", {},
922              $h, $user, time);
923 }
924
925 sub check_divert ($) {
926     my ($r) = @_;
927     if (exists $r->{Divert}) {
928         return $r->{Divert};
929     }
930     my $dbh = $r->{Dbh};
931     $r->{Divert} = $r->_db_transaction(sub { $r->_check_divert_core(); });
932     $dbh->commit();
933     $r->_debug(Data::Dumper->Dump([$r->{Divert}],[qw(divert)]));
934     return $r->{Divert};
935 }
936
937 sub get_divert ($) {
938     my ($r) = @_;
939     die "unchecked" unless exists $r->{Divert};
940     return $r->{Divert};
941 }
942
943 sub get_username ($) {
944     my ($r) = @_;
945     my $divert = $r->get_divert();
946     return undef if $divert;
947     return $r->{UserOK};
948 }
949
950 sub url_with_query_params ($$) {
951     my ($r, $params) = @_;
952 #print STDERR "PARAMS ",Dumper($params);
953     my $uri = URI->new($r->_ch('get_url'));
954     $uri->path($uri->path() . $params->{''}[0]) if $params->{''};
955     $uri->query_form(flatten_params($params));
956     return $uri->as_string();
957 }
958
959 sub _cgi_header_args ($$@) {
960     my ($r, $cookie, @ha) = @_;
961     unshift @ha, qw(-type text/html);
962     push @ha, (-cookie => $cookie) if defined $cookie;
963 #print STDERR "_cgi_header_args ",join('|',@ha),".\n";
964     return @ha;
965 }
966
967 sub check_ok ($) {
968     my ($r) = @_;
969
970     my ($divert) = $r->check_divert();
971     return 1 if !$divert;
972
973     my $handled = $r->_ch('handle_divert',$divert);
974     return 0 if $handled;
975
976     my $kind = $divert->{Kind};
977     my $cookiesecret = $divert->{CookieSecret};
978     my $params = $divert->{Params};
979     my $cookie = $r->construct_cookie($cookiesecret);
980
981     if ($kind =~ m/^SRCDUMP-(\w+)$/) {
982         $r->_ch('srcdump_dump_thing', (lc $1));
983         return 0;
984     }
985
986     if ($kind =~ m/^REDIRECT-/) {
987         # for redirects, we honour stored NextParams and SetCookie,
988         # as we would for non-divert
989         if ($kind eq 'REDIRECT-LOGGEDOUT') {
990             $params->{$r->{S}{loggedout_param_names}[0]} = [ 1 ];
991         } elsif ($kind eq 'REDIRECT-LOGOUT') {
992             $params->{$r->{S}{logout_param_names}[0]} = [ 1 ];
993         } elsif ($kind =~ m/REDIRECT-(?:LOGGEDIN|HTTPS)/) {
994         } else {
995             die;
996         }
997         my $new_url = $r->url_with_query_params($params);
998         if ($kind eq 'REDIRECT-HTTPS') {
999             my $uri = URI->new($new_url);
1000             die unless $uri->scheme eq 'http';
1001             $uri->scheme('https');
1002             $new_url = $uri->as_string();
1003         }
1004         $r->_ch('do_redirect',$new_url, $cookie);
1005         return 0;
1006     }
1007
1008     if (defined $cookiesecret) {
1009         $params->{$r->{S}{assoc_param_name}} = [ $r->hash($cookiesecret) ];
1010     }
1011
1012     my ($title, @body);
1013     if ($kind =~ m/^LOGIN-/) {
1014         $title = $r->_gt('Login');
1015         push @body, $divert->{Message};
1016         push @body, $r->_ch('gen_login_form', $params);
1017     } elsif ($kind =~ m/^SMALLPAGE-/) {
1018         $title = $r->_gt('Not logged in');
1019         push @body, $divert->{Message};
1020         push @body, $r->_ch('gen_login_link', $params);
1021     } elsif ($kind =~ m/^MAINPAGEONLY$/) {
1022         $title = $r->_gt('Entering secure site.');
1023         push @body, $divert->{Message};
1024         push @body, $r->_ch('gen_postmainpage_form', $params);
1025     } else {
1026         die $kind;
1027     }
1028
1029     $r->_print($r->{Cgi}->header($r->_cgi_header_args($cookie)),
1030                $r->_ch('gen_start_html',$title),
1031                (join "\n", (@body,
1032                             $r->_ch('gen_footer_html'),
1033                             $r->_ch('gen_end_html'))));
1034     return 0;
1035 }
1036
1037 sub _random ($$) {
1038     my ($r, $bytes) = @_;
1039     my $v = $r->{V};
1040     my $rsf = $v->{RandomHandle};
1041     my $rsp = $r->{S}{random_source};
1042     if (!$rsf) {
1043         $v->{RandomHandle} = $rsf = new IO::File $rsp, '<' or die "$rsp $!";
1044 #print STDERR "RH $rsf\n";
1045     }
1046     my $bin;
1047     $!=0;
1048     read($rsf,$bin,$bytes) == $bytes or die "$rsp $!";
1049     my $out = unpack "H*", $bin;
1050 #print STDERR "_random out $out\n";
1051     return $out;
1052 }
1053
1054 sub _random_key ($) {
1055     my ($r) = @_;
1056 #print STDERR "_random_key\n";
1057     my $bytes = ($r->{S}{secretbits} + 7) >> 3;
1058     return $r->_random($bytes);
1059 }
1060
1061 sub _read_key ($$) {
1062     my ($r, $keys) = @_;
1063     # returns $gen_time_t, $key_value_in_hex, $complete_line
1064     while (<$keys>) {
1065         my ($gen, $k) = m/^(\d+) (\S+)$/ or die "$_ ?";
1066         my $age = time - $gen;
1067         next if $age > $r->{S}{key_rollover} &&
1068             $age > $r->{S}{login_form_timeout}*2;
1069         return ($gen, $k, $_);
1070     }
1071     return ();
1072 }
1073
1074 sub _open_keys ($) {
1075     my ($r) = @_;
1076     my $spath = $r->_get_path('keys');
1077     for (;;) {
1078 #print STDERR "_open_keys\n";
1079         my $keys = new IO::File $spath, 'r+';
1080         if ($keys) {
1081 #print STDERR "_open_keys open\n";
1082             stat $keys or die $!; # NB must not disturb stat _
1083             my $size = (stat _)[7];
1084             my $age = time - (stat _)[9];
1085 #print STDERR "_open_keys open size=$size age=$age\n";
1086             return $keys
1087                 if $size && $age <= $r->{S}{key_rollover} / 2;
1088 #print STDERR "_open_keys open bad\n";
1089         }
1090         # file doesn't exist, or is empty or too old
1091         if (!$keys) {
1092 #print STDERR "_open_keys closed\n";
1093             die "$spath $!" unless $!==&ENOENT;
1094             # doesn't exist, so create it just so we can lock it
1095             $keys = new IO::File $spath, 'a+';
1096             die "$keys $!" unless $keys;
1097             stat $keys or die $!; # NB must not disturb stat _
1098             my $size = (stat _)[7];
1099 #print STDERR "_open_keys created size=$size\n";
1100             next if $size; # oh someone else has done it, reopen and read it
1101         }
1102         # file now exists is empty or too old, we must try to replace it
1103         my $our_inum = (stat _)[1]; # last use of that stat _
1104         flock $keys, LOCK_EX or die "$spath $!";
1105         stat $spath or die "$spath $!";
1106         my $path_inum = (stat _)[1];
1107 #print STDERR "_open_keys locked our=$our_inum path=$path_inum\n";
1108         next if $our_inum != $path_inum; # someone else has done it
1109         # We now hold the lock!
1110 #print STDERR "_open_keys creating\n";
1111         my $newkeys = new IO::Handle;
1112         sysopen $newkeys, "$spath.new", O_CREAT|O_TRUNC|O_WRONLY, 0600
1113             or die "$spath.new $!";
1114         # we add the new key to the front which means it's always sorted
1115         print $newkeys time, ' ', $r->_random_key(), "\n" or die $!;
1116         while (my ($gen,$key,$line) = $r->_read_key($keys)) {
1117 #print STDERR "_open_keys copy1\n";
1118             print $newkeys, $line or die $!;
1119         }
1120         $keys->error and die $!;
1121         close $newkeys or die "$spath.new $!";
1122         rename "$spath.new", "$spath" or die "$spath: $!";
1123 #print STDERR "_open_keys installed\n";
1124         # that rename effective unlocks, since it makes the name refer
1125         #  to the new file which we haven't locked
1126         # we go round again opening the file at the beginning
1127         #  so that our caller gets a fresh handle onto the existing key file
1128     }
1129 }
1130
1131 sub _fresh_secret ($) {
1132     my ($r) = @_;
1133 #print STDERR "_fresh_secret\n";
1134
1135     my $keys = $r->_open_keys();
1136     my ($keyt, $key) = $r->_read_key($keys);
1137     die unless defined $keyt;
1138
1139     my $nonce = $r->_random_key();
1140     my $noncet = time;
1141     my $message = "$noncet.$nonce";
1142
1143     my $signature = $r->_hmac($key, $message);
1144     my $secret = "$keyt.$signature.$message";
1145 #print STDERR "FRESH $secret\n";
1146     return $secret;
1147 }
1148
1149 sub _hmac ($$$) {
1150     my ($r, $keyhex, $message) = @_;
1151     my $keybin = pack "H*", $keyhex;
1152     my $alg = $r->{S}{hash_algorithm};
1153 #print STDERR "hmac $alg\n";
1154     my $base = new Digest $alg;
1155 #print STDERR "hmac $alg $base\n";
1156     my $digest = new Digest::HMAC $keybin, $base;
1157 #print STDERR "hmac $alg $base $digest\n";
1158     $digest->add($message);
1159     return $digest->hexdigest();
1160 }
1161
1162 sub hash ($$) {
1163     my ($r, $message) = @_;
1164     my $alg = $r->{S}{hash_algorithm};
1165 #print STDERR "hash $alg\n";
1166     my $digest = new Digest $alg;
1167     $digest->add($message);
1168     return $digest->hexdigest();
1169 }
1170
1171 sub _assert_checked ($) {
1172     my ($r) = @_;
1173     die "unchecked" unless exists $r->{Divert};
1174 }
1175
1176 sub _is_post ($) {
1177     my ($r) = @_;
1178     my $meth = $r->_ch('get_method');
1179     return $meth eq 'POST';
1180 }
1181
1182 sub _must_be_post ($) {
1183     my ($r) = @_;
1184     my $meth = $r->_ch('get_method');
1185     die "mutating non-POST" if $meth ne 'POST';
1186 }
1187
1188 sub check_mutate ($) {
1189     my ($r) = @_;
1190     $r->_assert_checked();
1191     die if $r->{Divert};
1192     $r->_must_be_post();
1193 }
1194
1195 sub mutate_ok ($) {
1196     my ($r) = @_;
1197     $r->_assert_checked();
1198     die if $r->{Divert};
1199     return $r->_is_post();
1200 }
1201
1202 #---------- output ----------
1203
1204 sub secret_cookie_val ($) {
1205     my ($r) = @_;
1206     $r->_assert_checked();
1207     return defined $r->{AssocSecret} ? $r->{AssocSecret} : '';
1208 }
1209
1210 sub secret_hidden_val ($) {
1211     my ($r) = @_;
1212     $r->_assert_checked();
1213     return defined $r->{AssocSecret} ? $r->hash($r->{AssocSecret}) : '';
1214 }
1215
1216 sub secret_hidden_html ($) {
1217     my ($r) = @_;
1218     return $r->{Cgi}->hidden(-name => $r->{S}{assoc_param_name},
1219                              -default => $r->secret_hidden_val());
1220 }
1221
1222 sub secret_cookie ($) {
1223     my ($r) = @_;
1224     my $secret = $r->secret_cookie_val();
1225     return undef if !defined $secret;
1226 #print STDERR "SC\n";
1227     my $cookv = $r->construct_cookie($secret); 
1228 #print STDERR "SC=$cookv\n";
1229     return $cookv;
1230 }
1231
1232 1;
1233
1234 __END__
1235
1236 =head1 NAME
1237
1238 CGI::Auth::Flexible - web authentication optionally using cookies
1239
1240 =head1 SYNOPSYS
1241
1242  my $verifier = CGI::Auth::Flexible->new_verifier(setting => value,...);
1243  my $authreq = $verifier->new_request($cgi_request_object);
1244
1245  my $authreq = CGI::Auth::Flexible->new_request($cgi_request_object,
1246                                               setting => value,...);
1247
1248 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
1249
1250  $authreq->check_ok() or return;
1251
1252  blah blah blah
1253  $authreq->check_mutate();
1254  blah blah blah
1255
1256 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
1257
1258  my $divert_kind = $authreq->check_divert();
1259  if ($divert_kind) {
1260      if ($divert_kind eq 'LOGGEDOUT') {
1261          print "goodbye you are now logged out" and quit
1262      } elsif ($divert_kind eq 'NOCOOKIES') {
1263          print "you need cookies" and quit
1264      ... etc.
1265      }
1266  }
1267
1268  blah blah blah
1269  $authreq->check_mutate();
1270  blah blah blah