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