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