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