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