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