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