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