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