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