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