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