3 # This is part of CGI::Auth::Flexible, a perl CGI authentication module.
4 # Copyright (C) 2012 Ian Jackson.
5 # Copyright (C) 2012 Citrix.
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.
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.
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/>.
21 use warnings FATAL => 'all';
23 package CGI::Auth::Flexible;
28 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
33 %EXPORT_TAGS = ( ); # eg: TAG => [ qw!name1 name2! ],
40 use CGI qw/escapeHTML/;
52 #---------- public utilities ----------
54 sub flatten_params ($) {
57 foreach my $k (keys %$p) {
59 foreach my $v (@{ $p->{$k} }) {
66 #---------- default callbacks ----------
68 sub has_a_param ($$) {
70 foreach my $pn (@{ $r->{S}{$cn} }) {
71 return 1 if $r->_ch('get_param',$pn);
80 foreach my $name ($c->param()) {
81 $p{$name} = [ $c->param($name) ];
86 sub get_cookie_domain ($$$) {
88 my $uri = new URI $r->_ch('get_url');
92 sub login_ok_password ($$) {
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);
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."),
110 $r->_ch('gen_end_html'));
113 sub gen_some_form ($$) {
114 my ($r, $params, $bodyfn) = @_;
115 # Calls $bodyfn->($c,$r) which returns @formbits
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) {
125 foreach my $val (@{ $params->{$n} }) {
126 push @form, ('<input type="hidden"'.
127 ' name="'.escapeHTML($n).'"'.
128 ' value="'.escapeHTML($val).'">');
131 push @form, ('</form>');
132 return join "\n", @form;
135 sub gen_plain_login_form ($$) {
136 my ($c,$r, $params) = @_;
137 return $r->gen_some_form($params, sub {
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>');
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>',
158 sub gen_postmainpage_form ($$$) {
159 my ($c,$r, $params) = @_;
160 return $r->gen_some_form($params, sub {
162 push @form, ('<input type="submit"',
163 ' name="'.$r->{S}{dummy_param_name_prefix}.'submit"'.
164 ' value="'.$r->_gt('Continue').'">');
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.').
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)).'">'.
183 sub gen_plain_licence_link_html ($$) {
185 gen_srcdump_link_html($c,$r, 'GNU Affero GPL', 'licence');
187 sub gen_plain_source_link_html ($$) {
189 gen_srcdump_link_html($c,$r, 'Source available', 'source');
192 sub gen_plain_footer_html ($$) {
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').".",
201 #---------- licence and source code ----------
203 #sub dump_licence ($$$) {
205 # my ($c,$r, $fh) = @_;
206 # foreach my $incdir ($r->_ch('getsource_includedirs')) {
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 $!";
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);
225 sub dump_plain ($$$$) {
226 my ($c, $r, $ct, $df) = @_;
227 $r->_print($c->header(-type $ct));
230 my $got = read $df, $buffer, 65536;
231 die $! unless defined $got;
237 #---------- verifier object methods ----------
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,
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
284 get_cookie_domain => \&get_cookie_domain,
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
303 while (($k,$v,@_) = @_) {
304 die "unknown setting $k" unless exists $verifier->{S}{$k};
305 $verifier->{S}{$k} = $v;
307 bless $verifier, $class;
308 $verifier->_dbopen();
312 sub _db_setup_do ($$) {
316 $v->_db_transaction(sub {
317 local ($dbh->{PrintError}) = 0;
328 $dbh = $v->{S}{assocdb_dbh};
330 die if $dbh->{AutoCommit};
331 die unless $dbh->{RaiseError};
333 $v->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=".$v->_get_path('assocdb');
334 my $dsn = $v->{S}{assocdb_dsn};
337 $dbh = DBI->connect($dsn, $v->{S}{assocdb_user},
338 $v->{S}{assocdb_password}, {
341 ShowErrorStatement => 1,
344 die "$dsn $! ?" unless $dbh;
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".
353 $v->_db_setup_do("CREATE INDEX $v->{S}{assocdb_table}_timeout_index".
354 " ON $v->{S}{assocdb_table}".
366 sub _db_transaction ($$) {
371 #print STDERR "DT entry\n";
373 #print STDERR "DT loop\n";
376 #print STDERR "DT fn ok\n";
379 #print STDERR "DT fn error\n";
380 { local ($@); $dbh->rollback(); }
381 #print STDERR "DT fn throwing\n";
384 #print STDERR "DT fn eval ok\n";
387 #print STDERR "DT commit ok\n";
390 #print STDERR "DT commit eval ok ",Dumper($rv);
393 #print STDERR "DT commit throw?\n";
394 die $@ if !--$retries;
395 #print STDERR "DT loop again\n";
399 #---------- request object methods ----------
402 my ($classbase, $cgi, @extra) = @_;
403 if (!ref $classbase) {
404 $classbase = $classbase->new_verifier(@extra);
410 S => $classbase->{S},
411 Dbh => $classbase->{Dbh},
414 bless $r, ref $classbase;
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);
426 my $pn = $r->{S}{$pnvb};
427 my $p = scalar $r->_ch('get_param',$pn)
432 $r->_ch('debug',@args);
436 my ($r,$keybase) = @_;
437 my $leaf = $r->{S}{"${keybase}_path"};
438 return $r->_absify_path($leaf);
441 sub _absify_path ($$) {
443 return $leaf if $leaf =~ m,^/,;
444 my $dir = $v->{S}{dir};
445 die "relying on cwd by default ?! set dir" unless defined $dir;
449 sub _gt ($$) { my ($r, $t) = @_; return $r->_ch('gettext',$t); }
450 sub _print ($$) { my ($r, @t) = @_; return $r->_ch('print', join '', @t); }
452 sub construct_cookie ($$$) {
453 my ($r, $cooks) = @_;
454 return undef unless $cooks;
456 my @ca = (-name => $r->{S}{cookie_name},
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";
467 # pages/param-sets are
468 # n normal non-mutating page
469 # r retrieval of information for JS, non-mutating
471 # u update of information by JS, mutating
474 # O "you have just logged out" page load
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 -
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)
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
492 # Case analysis, cookie mode, app promises re mutate:
493 # cook parm meth form
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
500 # - - GET O "just logged out" page
501 # (any other) O bug or attack, fail
503 # a1 a2 POST o logout
504 # if a1 is valid, revoke it
505 # if a2 is valid, revoke it
507 # redirect to "just logged out" page
508 # (which contains link to login form)
510 # - t POST i complain about cookies being disabled
511 # (with link to login form)
513 # t1 t1 POST i login (or switch user)
515 # show new login form
517 # upgrade t1 to y1 in our db (setting username)
518 # redirect to GET of remaining params
520 # y1 a2 POST i complain about stale login form
522 # show new login form
524 # (other) POST i complain about stale login form
525 # show new login form
527 # t1 a2 ANY nrmu treat as - a2 ANY
529 # y - GET n cross-site link
532 # y y GET nr fine, show page or send data
533 # y y POST nrmu mutation is OK, do operation
535 # y1 y2 GET nr request from stale page
536 # do not revoke y2 as not RESTful
539 # y1 y2 POST nrmu request from stale page
543 # y n GET n intra-site link from stale page,
544 # treat as cross-site link, show data
546 # y n POST n m intra-site form submission from stale page
547 # show "session interrupted"
548 # with link to main data page
550 # y n GET r intra-site request from stale page
553 # y n POST r u intra-site request from stale page
556 # -/n y2 GET nr intra-site link from cleared session
557 # do not revoke y2 as not RESTful
560 # -/n y2 POST nrmu request from cleared session
562 # treat as -/n n POST
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
568 # -/n n GET rmu user not logged in
571 # -/n n POST n m user not logged in
574 # -/n n POST r u user not logged in
577 sub _check_divert_core ($) {
580 my $srcdump = $r->_rp('srcdump_param_name');
582 die if $srcdump =~ m/\W/;
583 return ({ Kind => 'SRCDUMP-'.uc $srcdump,
585 CookieSecret => undef,
589 my $cooks = $r->_ch('get_cookie');
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,
598 my $meth = $r->_ch('get_method');
599 my $parmh = $r->_rp('assoc_param_name');
600 my $cookh = defined $cooks ? $r->hash($cooks) : undef;
602 my ($cookt,$cooku) = $r->_identify($cookh, $cooks);
603 my $parms = (defined $cooks && defined $parmh && $parmh eq $cookh)
605 my ($parmt) = $r->_identify($parmh, $parms);
607 $r->_debug("_c_d_c cookt=$cookt parmt=$parmt\n");
609 if ($r->_ch('is_logout')) {
612 $r->_db_revoke($cookh);
613 $r->_db_revoke($parmh);
614 return ({ Kind => 'REDIRECT-LOGGEDOUT',
615 Message => $r->_gt("Logging out..."),
619 if ($r->_ch('is_loggedout')) {
620 die unless $meth eq 'GET';
621 die if $cookt eq 'y';
623 return ({ Kind => 'SMALLPAGE-LOGGEDOUT',
624 Message => $r->_gt("You have been logged out."),
628 if ($r->_ch('is_login')) {
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() })
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(),
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() })
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() });
666 die if $parmt eq 't';
668 if ($cookt eq 'y' && $parmt eq 'y' && $cookh ne $parmh) {
669 $r->_db_revoke($parmh) if $meth eq 'POST';
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() });
683 $r->_db_revoke($parmh);
684 return ({ Kind => 'LOGIN-FRESH',
685 Message => $r->_gt("You need to log in."),
686 CookieSecret => $news,
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,
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"
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;
708 $r->{AssocSecret} = $cooks;
709 $r->{UserOK} = $cooku;
710 #print STDERR "C-D-C OK\n";
714 sub chain_params ($) {
716 my %p = %{ $r->_ch('get_params') };
717 foreach my $pncn (keys %{ $r->{S} }) {
719 if ($pncn =~ m/_param_name$/) {
720 my $name = $r->{S}{$pncn};
721 die "$pncn ?" if ref $name;
723 } elsif ($pncn =~ m/_param_names$/) {
724 $names = $r->{S}{$pncn};
728 foreach my $name (@$names) {
732 my $dummy_prefix = $r->{S}{dummy_param_name_prefix};
733 foreach my $name (grep /^$dummy_prefix/, keys %p) {
736 die if exists $p{''};
737 $p{''} = [ $r->_ch('get_path_info') ];
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)
747 #print STDERR "_identify\n";
748 return '' unless defined $h && length $h;
749 #print STDERR "_identify h=$h s=".(defined $s ? $s : '<undef>')."\n";
753 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
754 " WHERE last < ?", {},
755 time - $r->{S}{login_timeout});
757 my $row = $dbh->selectrow_arrayref("SELECT username, last".
758 " FROM $r->{S}{assocdb_table}".
759 " WHERE assochash = ?", {}, $h);
761 #print STDERR "_identify h=$h s=$s YES @$row\n";
762 my ($nusername, $nlast) = @$row;
763 return ('y', $nusername);
766 # Well, it's not in the database. But maybe it's a hash of a
769 return 'n' unless defined $s;
771 my ($keyt, $signature, $message, $noncet, $nonce) =
772 $s =~ m/^(\d+)\.(\w+)\.((\d+)\.(\w+))$/ or die;
774 return 'n' if time > $noncet + $r->{S}{login_form_timeout};
776 #print STDERR "_identify noncet=$noncet ok\n";
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;
787 #print STDERR "_identify NO\n";
789 $keys->error and die $!;
793 sub _db_revoke ($$) {
794 # revokes $h if it's valid; no-op if it's not
799 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
800 " WHERE assochash = ?", {}, $h);
803 sub _db_record_login_ok ($$$) {
804 my ($r,$h,$user) = @_;
807 $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
808 " (assochash, username, last) VALUES (?,?,?)", {},
812 sub check_divert ($) {
814 if (exists $r->{Divert}) {
818 $r->{Divert} = $r->_db_transaction(sub { $r->_check_divert_core(); });
820 $r->_debug(Data::Dumper->Dump([$r->{Divert}],[qw(divert)]));
826 die "unchecked" unless exists $r->{Divert};
830 sub get_username ($) {
832 my $divert = $r->get_divert();
833 return undef if $divert;
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();
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";
857 my ($divert) = $r->check_divert();
858 return 1 if !$divert;
860 my $handled = $r->_ch('handle_divert',$divert);
861 return 0 if $handled;
863 my $kind = $divert->{Kind};
864 my $cookiesecret = $divert->{CookieSecret};
865 my $params = $divert->{Params};
866 my $cookie = $r->construct_cookie($cookiesecret);
868 if ($kind =~ m/^SRCDUMP-(\w+)$/) {
869 $r->_ch('srcdump_dump_thing', (lc $1));
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)/) {
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();
891 $r->_ch('do_redirect',$new_url, $cookie);
895 if (defined $cookiesecret) {
896 $params->{$r->{S}{assoc_param_name}} = [ $r->hash($cookiesecret) ];
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);
916 $r->_print($r->{Cgi}->header($r->_cgi_header_args($cookie)),
917 $r->_ch('gen_start_html',$title),
919 $r->_ch('gen_footer_html'),
920 $r->_ch('gen_end_html'))));
925 my ($r, $bytes) = @_;
927 my $rsf = $v->{RandomHandle};
928 my $rsp = $r->{S}{random_source};
930 $v->{RandomHandle} = $rsf = new IO::File $rsp, '<' or die "$rsp $!";
931 #print STDERR "RH $rsf\n";
935 read($rsf,$bin,$bytes) == $bytes or die "$rsp $!";
936 my $out = unpack "H*", $bin;
937 #print STDERR "_random out $out\n";
941 sub _random_key ($) {
943 #print STDERR "_random_key\n";
944 my $bytes = ($r->{S}{secretbits} + 7) >> 3;
945 return $r->_random($bytes);
950 # returns $gen_time_t, $key_value_in_hex, $complete_line
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, $_);
963 my $spath = $r->_get_path('keys');
965 #print STDERR "_open_keys\n";
966 my $keys = new IO::File $spath, 'r+';
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";
974 if $size && $age <= $r->{S}{key_rollover} / 2;
975 #print STDERR "_open_keys open bad\n";
977 # file doesn't exist, or is empty or too old
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
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 $!;
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
1018 sub _fresh_secret ($) {
1020 #print STDERR "_fresh_secret\n";
1022 my $keys = $r->_open_keys();
1023 my ($keyt, $key) = $r->_read_key($keys);
1024 die unless defined $keyt;
1026 my $nonce = $r->_random_key();
1028 my $message = "$noncet.$nonce";
1030 my $signature = $r->_hmac($key, $message);
1031 my $secret = "$keyt.$signature.$message";
1032 #print STDERR "FRESH $secret\n";
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();
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();
1058 sub _assert_checked ($) {
1060 die "unchecked" unless exists $r->{Divert};
1065 my $meth = $r->_ch('get_method');
1066 return $meth eq 'POST';
1069 sub _must_be_post ($) {
1071 my $meth = $r->_ch('get_method');
1072 die "mutating non-POST" if $meth ne 'POST';
1075 sub check_mutate ($) {
1077 $r->_assert_checked();
1078 die if $r->{Divert};
1079 $r->_must_be_post();
1084 $r->_assert_checked();
1085 die if $r->{Divert};
1086 return $r->_is_post();
1089 #---------- output ----------
1091 sub secret_cookie_val ($) {
1093 $r->_assert_checked();
1094 return defined $r->{AssocSecret} ? $r->{AssocSecret} : '';
1097 sub secret_hidden_val ($) {
1099 $r->_assert_checked();
1100 return defined $r->{AssocSecret} ? $r->hash($r->{AssocSecret}) : '';
1103 sub secret_hidden_html ($) {
1105 return $r->{Cgi}->hidden(-name => $r->{S}{assoc_param_name},
1106 -default => $r->secret_hidden_val());
1109 sub secret_cookie ($) {
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";
1125 CGI::Auth::Flexible - web authentication optionally using cookies
1129 my $verifier = CGI::Auth::Flexible->new_verifier(setting => value,...);
1130 my $authreq = $verifier->new_request($cgi_request_object);
1132 my $authreq = CGI::Auth::Flexible->new_request($cgi_request_object,
1133 setting => value,...);
1135 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
1137 $authreq->check_ok() or return;
1140 $authreq->check_mutate();
1143 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
1145 my $divert_kind = $authreq->check_divert();
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
1156 $authreq->check_mutate();