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