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