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_special_link_html ($$$$) {
178 my ($c,$r,$anchor,$specval) = @_;
179 my %params = ($r->{S}{special_param_name} => [ $specval ]);
180 return '<a href="'.escapeHTML($r->url_with_query_params(\%params)).'">'.
183 sub gen_plain_licence_link_html ($$) {
185 gen_special_link_html($c,$r, 'GNU Affero GPL', 'licence');
187 sub gen_plain_source_link_html ($$) {
189 gen_special_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 source_dump_get_path ($$$) {
212 my ($c,$r, $thing) = @_;
213 die if $thing =~ m/\W/;
214 my $pat = $r->{S}('source_dump_path_pat');
215 my $leaf = sprintf $pat, $thing;
216 return $r->_absify_path($leaf);
219 sub source_dump_thing ($$$) {
220 my ($c,$r, $thing, $outfn) = @_;
221 my $path = $r->_ch('source_dump_get_path', $thing);
224 #---------- verifier object methods ----------
231 assocdb_dbh => undef, # must have AutoCommit=0, RaiseError=1
232 assocdb_path => 'caf-assocs.db',
233 keys_path => 'caf-keys',
234 source_dump_path_pat => 'caf-%s.dump',
235 source_dump_get_path => \&source_dump_get_path,
236 assocdb_dsn => undef,
238 assocdb_password => '',
239 assocdb_table => 'caf_assocs',
240 random_source => '/dev/urandom',
241 secretbits => 128, # bits
242 hash_algorithm => "SHA-256",
243 login_timeout => 86400, # seconds
244 login_form_timeout => 3600, # seconds
245 key_rollover => 86400, # seconds
246 assoc_param_name => 'caf_assochash',
247 dummy_param_name_prefix => 'caf__',
248 cookie_name => "caf_assocsecret",
249 password_param_name => 'password',
250 special_param_name => 'caf_special',
251 username_param_names => [qw(username)],
252 form_entry_size => 60,
253 logout_param_names => [qw(caf_logout)],
254 loggedout_param_names => [qw(caf_loggedout)],
255 promise_check_mutate => 0,
256 get_param => sub { $_[0]->param($_[2]) },
257 get_params => sub { $_[1]->get_params() },
258 get_path_info => sub { $_[0]->path_info() },
259 get_cookie => sub { $_[0]->cookie($_[1]->{S}{cookie_name}) },
260 get_method => sub { $_[0]->request_method() },
261 check_https => sub { !!$_[0]->https() },
262 get_url => sub { $_[0]->url(); },
263 is_login => sub { defined $_[1]->_rp('password_param_name') },
264 login_ok => \&login_ok_password,
265 username_password_error => sub { die },
266 is_logout => sub { $_[1]->has_a_param('logout_param_names') },
267 is_loggedout => sub { $_[1]->has_a_param('loggedout_param_names') },
268 is_page => sub { return 1 },
269 handle_divert => sub { return 0 },
270 do_redirect => \&do_redirect_cgi, # this hook is allowed to throw
272 get_cookie_domain => \&get_cookie_domain,
274 gen_start_html => sub { $_[0]->start_html($_[2]); },
275 gen_footer_html => \&gen_plain_footer_html,
276 gen_licence_link_html => \&gen_plain_licence_link_html,
277 gen_source_link_html => \&gen_plain_source_link_html,
278 gen_end_html => sub { $_[0]->end_html(); },
279 gen_login_form => \&gen_plain_login_form,
280 gen_login_link => \&gen_plain_login_link,
281 gen_postmainpage_form => \&gen_postmainpage_form,
282 source_dump_thing => \&source_dump_thing,
283 source_includedirs => sub { grep { !m#^/etc/# } @INC; },
284 gettext => sub { gettext($_[2]); },
285 print => sub { print $_[2] or die $!; },
286 debug => sub { }, # like print; msgs contain trailing \n
291 while (($k,$v,@_) = @_) {
292 die "unknown setting $k" unless exists $verifier->{S}{$k};
293 $verifier->{S}{$k} = $v;
295 bless $verifier, $class;
296 $verifier->_dbopen();
300 sub _db_setup_do ($$) {
304 $v->_db_transaction(sub {
305 local ($dbh->{PrintError}) = 0;
316 $dbh = $v->{S}{assocdb_dbh};
318 die if $dbh->{AutoCommit};
319 die unless $dbh->{RaiseError};
321 $v->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=".$v->_get_path('assocdb');
322 my $dsn = $v->{S}{assocdb_dsn};
325 $dbh = DBI->connect($dsn, $v->{S}{assocdb_user},
326 $v->{S}{assocdb_password}, {
329 ShowErrorStatement => 1,
332 die "$dsn $! ?" unless $dbh;
336 $v->_db_setup_do("CREATE TABLE $v->{S}{assocdb_table} (".
337 " assochash VARCHAR PRIMARY KEY,".
338 " username VARCHAR NOT NULL,".
339 " last INTEGER NOT NULL".
341 $v->_db_setup_do("CREATE INDEX $v->{S}{assocdb_table}_timeout_index".
342 " ON $v->{S}{assocdb_table}".
354 sub _db_transaction ($$) {
359 #print STDERR "DT entry\n";
361 #print STDERR "DT loop\n";
364 #print STDERR "DT fn ok\n";
367 #print STDERR "DT fn error\n";
368 { local ($@); $dbh->rollback(); }
369 #print STDERR "DT fn throwing\n";
372 #print STDERR "DT fn eval ok\n";
375 #print STDERR "DT commit ok\n";
378 #print STDERR "DT commit eval ok ",Dumper($rv);
381 #print STDERR "DT commit throw?\n";
382 die $@ if !--$retries;
383 #print STDERR "DT loop again\n";
387 #---------- request object methods ----------
390 my ($classbase, $cgi, @extra) = @_;
391 if (!ref $classbase) {
392 $classbase = $classbase->new_verifier(@extra);
398 S => $classbase->{S},
399 Dbh => $classbase->{Dbh},
402 bless $r, ref $classbase;
405 sub _ch ($$@) { # calls an application hook
406 my ($r,$methname, @args) = @_;
407 my $methfunc = $r->{S}{$methname};
408 die "$methname ?" unless $methfunc;
409 return $methfunc->($r->{Cgi}, $r, @args);
414 my $pn = $r->{S}{$pnvb};
415 my $p = scalar $r->_ch('get_param',$pn)
420 $r->_ch('debug',@args);
424 my ($v,$keybase) = @_;
425 my $leaf = $v->{S}{"${keybase}_path"};
426 return $r->_absify_path($leaf);
429 sub _absify_path ($$) {
431 return $leaf if $leaf =~ m,^/,;
432 my $dir = $v->{S}{dir};
433 die "relying on cwd by default ?! set dir" unless defined $dir;
437 sub _gt ($$) { my ($r, $t) = @_; return $r->_ch('gettext',$t); }
438 sub _print ($$) { my ($r, @t) = @_; return $r->_ch('print', join '', @t); }
440 sub construct_cookie ($$$) {
441 my ($r, $cooks) = @_;
442 return undef unless $cooks;
444 my @ca = (-name => $r->{S}{cookie_name},
446 -path => $r->{S}{cookie_path},
447 -domain => $r->_ch('get_cookie_domain'),
448 -expires => '+'.$r->{S}{login_timeout}.'s',
449 -secure => $r->{S}{encrypted_only});
450 my $cookie = $c->cookie(@ca);
451 #print STDERR "CC $r $c $cooks $cookie (@ca).\n";
455 # pages/param-sets are
456 # n normal non-mutating page
457 # r retrieval of information for JS, non-mutating
459 # u update of information by JS, mutating
462 # O "you have just logged out" page load
465 # - no value supplied (represented in code as $cookt='')
466 # n, nN value not in our db
467 # t, tN temporary value (in our db, no logged in user yet)
468 # y, yN value corresponds to logged-in user
469 # and, aggregated conditions:
470 # a, aN anything including -
472 # if N differs the case applies only when the two values differ
473 # (eg, a1 y2 does not apply when the logged-in value is supplied twice)
475 # "stale session" means request originates from a page from a login
476 # session which has been revoked (eg by logout); "cleared session"
477 # means request originates from a browser which has a different (or
480 # Case analysis, cookie mode, app promises re mutate:
481 # cook parm meth form
483 # any - POST nrmuoi bug or attack, fail
484 # any - GET rmuoi bug or attack, fail
485 # any any GET muoi bug or attack, fail
486 # any t any nrmu bug or attack, fail
488 # - - GET O "just logged out" page
489 # (any other) O bug or attack, fail
491 # a1 a2 POST o logout
492 # if a1 is valid, revoke it
493 # if a2 is valid, revoke it
495 # redirect to "just logged out" page
496 # (which contains link to login form)
498 # - t POST i complain about cookies being disabled
499 # (with link to login form)
501 # t1 t1 POST i login (or switch user)
503 # show new login form
505 # upgrade t1 to y1 in our db (setting username)
506 # redirect to GET of remaining params
508 # y1 a2 POST i complain about stale login form
510 # show new login form
512 # (other) POST i complain about stale login form
513 # show new login form
515 # t1 a2 ANY nrmu treat as - a2 ANY
517 # y - GET n cross-site link
520 # y y GET nr fine, show page or send data
521 # y y POST nrmu mutation is OK, do operation
523 # y1 y2 GET nr request from stale page
524 # do not revoke y2 as not RESTful
527 # y1 y2 POST nrmu request from stale page
531 # y n GET n intra-site link from stale page,
532 # treat as cross-site link, show data
534 # y n POST n m intra-site form submission from stale page
535 # show "session interrupted"
536 # with link to main data page
538 # y n GET r intra-site request from stale page
541 # y n POST r u intra-site request from stale page
544 # -/n y2 GET nr intra-site link from cleared session
545 # do not revoke y2 as not RESTful
548 # -/n y2 POST nrmu request from cleared session
550 # treat as -/n n POST
552 # -/n -/n GET n cross-site link but user not logged in
553 # show login form with redirect to orig params
554 # generate fresh cookie
556 # -/n n GET rmu user not logged in
559 # -/n n POST n m user not logged in
562 # -/n n POST r u user not logged in
565 sub _check_divert_core ($) {
568 my $special = $r->_rp('special_param_name');
570 die if $special =~ m/\W/;
571 return ({ Kind => 'SPECIAL-'.uc $special,
573 CookieSecret => undef,
577 my $cooks = $r->_ch('get_cookie');
579 if ($r->{S}{encrypted_only} && !$r->_ch('check_https')) {
580 return ({ Kind => 'REDIRECT-HTTPS',
581 Message => $r->_gt("Redirecting to secure server..."),
582 CookieSecret => undef,
586 my $meth = $r->_ch('get_method');
587 my $parmh = $r->_rp('assoc_param_name');
588 my $cookh = defined $cooks ? $r->hash($cooks) : undef;
590 my ($cookt,$cooku) = $r->_identify($cookh, $cooks);
591 my $parms = (defined $cooks && defined $parmh && $parmh eq $cookh)
593 my ($parmt) = $r->_identify($parmh, $parms);
595 $r->_debug("_c_d_c cookt=$cookt parmt=$parmt\n");
597 if ($r->_ch('is_logout')) {
600 $r->_db_revoke($cookh);
601 $r->_db_revoke($parmh);
602 return ({ Kind => 'REDIRECT-LOGGEDOUT',
603 Message => $r->_gt("Logging out..."),
607 if ($r->_ch('is_loggedout')) {
608 die unless $meth eq 'GET';
609 die if $cookt eq 'y';
611 return ({ Kind => 'SMALLPAGE-LOGGEDOUT',
612 Message => $r->_gt("You have been logged out."),
616 if ($r->_ch('is_login')) {
619 if (!$cookt && $parmt eq 'n') {
620 return ({ Kind => 'SMALLPAGE-NOCOOKIE',
621 Message => $r->_gt("You do not seem to have cookies".
622 " enabled. You must enable cookies".
623 " as we use them for login."),
624 CookieSecret => $r->_fresh_secret(),
625 Params => $r->chain_params() })
627 if (!$cookt || $cookt eq 'n' || $cookh ne $parmh) {
628 $r->_db_revoke($cookh);
629 return ({ Kind => 'LOGIN-STALE',
630 Message => $r->_gt("Stale session;".
631 " you need to log in again."),
632 CookieSecret => $r->_fresh_secret(),
635 die unless $parmt eq 't' || $parmt eq 'y';
636 my ($username, $login_errormessage) = $r->_ch('login_ok');
637 unless (defined $username && length $username) {
638 $login_errormessage = $r->_gt("Incorrect username/password.")
639 if !$login_errormessage;
640 return ({ Kind => 'LOGIN-BAD',
641 Message => $login_errormessage,
642 CookieSecret => $cooks,
643 Params => $r->chain_params() })
645 $r->_db_record_login_ok($parmh,$username);
646 return ({ Kind => 'REDIRECT-LOGGEDIN',
647 Message => $r->_gt("Logging in..."),
648 CookieSecret => $cooks,
649 Params => $r->chain_params() });
654 die if $parmt eq 't';
656 if ($cookt eq 'y' && $parmt eq 'y' && $cookh ne $parmh) {
657 $r->_db_revoke($parmh) if $meth eq 'POST';
662 die unless !$cookt || $cookt eq 'n';
663 die unless !$parmt || $parmt eq 'n' || $parmt eq 'y';
664 my $news = $r->_fresh_secret();
665 if ($meth eq 'GET') {
666 return ({ Kind => 'LOGIN-INCOMINGLINK',
667 Message => $r->_gt("You need to log in."),
668 CookieSecret => $news,
669 Params => $r->chain_params() });
671 $r->_db_revoke($parmh);
672 return ({ Kind => 'LOGIN-FRESH',
673 Message => $r->_gt("You need to log in."),
674 CookieSecret => $news,
679 if (!$r->{S}{promise_check_mutate}) {
680 if ($meth ne 'POST') {
681 return ({ Kind => 'MAINPAGEONLY',
682 Message => $r->_gt('Entering via cross-site link.'),
683 CookieSecret => $cooks,
685 # NB caller must then ignore params & path!
686 # if this is too hard they can spit out a small form
687 # with a "click to continue"
691 die unless $cookt eq 'y';
692 unless ($r->{S}{promise_check_mutate} && $meth eq 'GET') {
693 die unless $parmt eq 'y';
694 die unless $cookh eq $parmh;
696 $r->{AssocSecret} = $cooks;
697 $r->{UserOK} = $cooku;
698 #print STDERR "C-D-C OK\n";
702 sub chain_params ($) {
704 my %p = %{ $r->_ch('get_params') };
705 foreach my $pncn (keys %{ $r->{S} }) {
707 if ($pncn =~ m/_param_name$/) {
708 my $name = $r->{S}{$pncn};
709 die "$pncn ?" if ref $name;
711 } elsif ($pncn =~ m/_param_names$/) {
712 $names = $r->{S}{$pncn};
716 foreach my $name (@$names) {
720 my $dummy_prefix = $r->{S}{dummy_param_name_prefix};
721 foreach my $name (grep /^$dummy_prefix/, keys %p) {
724 die if exists $p{''};
725 $p{''} = [ $r->_ch('get_path_info') ];
731 # returns ($t,$username)
732 # where $t is one of "t" "y" "n", or "" (for -)
733 # either $s must be undef, or $h eq $r->hash($s)
735 #print STDERR "_identify\n";
736 return '' unless defined $h && length $h;
737 #print STDERR "_identify h=$h s=".(defined $s ? $s : '<undef>')."\n";
741 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
742 " WHERE last < ?", {},
743 time - $r->{S}{login_timeout});
745 my $row = $dbh->selectrow_arrayref("SELECT username, last".
746 " FROM $r->{S}{assocdb_table}".
747 " WHERE assochash = ?", {}, $h);
749 #print STDERR "_identify h=$h s=$s YES @$row\n";
750 my ($nusername, $nlast) = @$row;
751 return ('y', $nusername);
754 # Well, it's not in the database. But maybe it's a hash of a
757 return 'n' unless defined $s;
759 my ($keyt, $signature, $message, $noncet, $nonce) =
760 $s =~ m/^(\d+)\.(\w+)\.((\d+)\.(\w+))$/ or die;
762 return 'n' if time > $noncet + $r->{S}{login_form_timeout};
764 #print STDERR "_identify noncet=$noncet ok\n";
766 my $keys = $r->_open_keys();
767 while (my ($rkeyt, $rkey, $line) = $r->_read_key($keys)) {
768 #print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey\n";
769 last if $rkeyt < $keyt; # too far down in the file
770 my $trysignature = $r->_hmac($rkey, $message);
771 #print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey try=$trysignature\n";
772 return 't' if $trysignature eq $signature;
775 #print STDERR "_identify NO\n";
777 $keys->error and die $!;
781 sub _db_revoke ($$) {
782 # revokes $h if it's valid; no-op if it's not
787 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
788 " WHERE assochash = ?", {}, $h);
791 sub _db_record_login_ok ($$$) {
792 my ($r,$h,$user) = @_;
795 $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
796 " (assochash, username, last) VALUES (?,?,?)", {},
800 sub check_divert ($) {
802 if (exists $r->{Divert}) {
806 $r->{Divert} = $r->_db_transaction(sub { $r->_check_divert_core(); });
808 $r->_debug(Data::Dumper->Dump([$r->{Divert}],[qw(divert)]));
814 die "unchecked" unless exists $r->{Divert};
818 sub get_username ($) {
820 my $divert = $r->get_divert();
821 return undef if $divert;
825 sub url_with_query_params ($$) {
826 my ($r, $params) = @_;
827 #print STDERR "PARAMS ",Dumper($params);
828 my $uri = URI->new($r->_ch('get_url'));
829 $uri->path($uri->path() . $params->{''}[0]) if $params->{''};
830 $uri->query_form(flatten_params($params));
831 return $uri->as_string();
834 sub _cgi_header_args ($$@) {
835 my ($r, $cookie, @ha) = @_;
836 unshift @ha, qw(-type text/html);
837 push @ha, (-cookie => $cookie) if defined $cookie;
838 #print STDERR "_cgi_header_args ",join('|',@ha),".\n";
845 my ($divert) = $r->check_divert();
846 return 1 if !$divert;
848 my $handled = $r->_ch('handle_divert',$divert);
849 return 0 if $handled;
851 my $kind = $divert->{Kind};
852 my $cookiesecret = $divert->{CookieSecret};
853 my $params = $divert->{Params};
854 my $cookie = $r->construct_cookie($cookiesecret);
856 if ($kind =~ m/^SPECIAL-(LICENCE|SOURCE)$/) {
857 $r->_ch('dump_'.lc $1, \*STDOUT);
861 if ($kind =~ m/^REDIRECT-/) {
862 # for redirects, we honour stored NextParams and SetCookie,
863 # as we would for non-divert
864 if ($kind eq 'REDIRECT-LOGGEDOUT') {
865 $params->{$r->{S}{loggedout_param_names}[0]} = [ 1 ];
866 } elsif ($kind eq 'REDIRECT-LOGOUT') {
867 $params->{$r->{S}{logout_param_names}[0]} = [ 1 ];
868 } elsif ($kind =~ m/REDIRECT-(?:LOGGEDIN|HTTPS)/) {
872 my $new_url = $r->url_with_query_params($params);
873 if ($kind eq 'REDIRECT-HTTPS') {
874 my $uri = URI->new($new_url);
875 die unless $uri->scheme eq 'http';
876 $uri->scheme('https');
877 $new_url = $uri->as_string();
879 $r->_ch('do_redirect',$new_url, $cookie);
883 if (defined $cookiesecret) {
884 $params->{$r->{S}{assoc_param_name}} = [ $r->hash($cookiesecret) ];
888 if ($kind =~ m/^LOGIN-/) {
889 $title = $r->_gt('Login');
890 push @body, $divert->{Message};
891 push @body, $r->_ch('gen_login_form', $params);
892 } elsif ($kind =~ m/^SMALLPAGE-/) {
893 $title = $r->_gt('Not logged in');
894 push @body, $divert->{Message};
895 push @body, $r->_ch('gen_login_link', $params);
896 } elsif ($kind =~ m/^MAINPAGEONLY$/) {
897 $title = $r->_gt('Entering secure site.');
898 push @body, $divert->{Message};
899 push @body, $r->_ch('gen_postmainpage_form', $params);
904 $r->_print($r->{Cgi}->header($r->_cgi_header_args($cookie)),
905 $r->_ch('gen_start_html',$title),
907 $r->_ch('gen_footer_html'),
908 $r->_ch('gen_end_html'))));
913 my ($r, $bytes) = @_;
915 my $rsf = $v->{RandomHandle};
916 my $rsp = $r->{S}{random_source};
918 $v->{RandomHandle} = $rsf = new IO::File $rsp, '<' or die "$rsp $!";
919 #print STDERR "RH $rsf\n";
923 read($rsf,$bin,$bytes) == $bytes or die "$rsp $!";
924 my $out = unpack "H*", $bin;
925 #print STDERR "_random out $out\n";
929 sub _random_key ($) {
931 #print STDERR "_random_key\n";
932 my $bytes = ($r->{S}{secretbits} + 7) >> 3;
933 return $r->_random($bytes);
938 # returns $gen_time_t, $key_value_in_hex, $complete_line
940 my ($gen, $k) = m/^(\d+) (\S+)$/ or die "$_ ?";
941 my $age = time - $gen;
942 next if $age > $r->{S}{key_rollover} &&
943 $age > $r->{S}{login_form_timeout}*2;
944 return ($gen, $k, $_);
951 my $spath = $r->_get_path('keys');
953 #print STDERR "_open_keys\n";
954 my $keys = new IO::File $spath, 'r+';
956 #print STDERR "_open_keys open\n";
957 stat $keys or die $!; # NB must not disturb stat _
958 my $size = (stat _)[7];
959 my $age = time - (stat _)[9];
960 #print STDERR "_open_keys open size=$size age=$age\n";
962 if $size && $age <= $r->{S}{key_rollover} / 2;
963 #print STDERR "_open_keys open bad\n";
965 # file doesn't exist, or is empty or too old
967 #print STDERR "_open_keys closed\n";
968 die "$spath $!" unless $!==&ENOENT;
969 # doesn't exist, so create it just so we can lock it
970 $keys = new IO::File $spath, 'a+';
971 die "$keys $!" unless $keys;
972 stat $keys or die $!; # NB must not disturb stat _
973 my $size = (stat _)[7];
974 #print STDERR "_open_keys created size=$size\n";
975 next if $size; # oh someone else has done it, reopen and read it
977 # file now exists is empty or too old, we must try to replace it
978 my $our_inum = (stat _)[1]; # last use of that stat _
979 flock $keys, LOCK_EX or die "$spath $!";
980 stat $spath or die "$spath $!";
981 my $path_inum = (stat _)[1];
982 #print STDERR "_open_keys locked our=$our_inum path=$path_inum\n";
983 next if $our_inum != $path_inum; # someone else has done it
984 # We now hold the lock!
985 #print STDERR "_open_keys creating\n";
986 my $newkeys = new IO::Handle;
987 sysopen $newkeys, "$spath.new", O_CREAT|O_TRUNC|O_WRONLY, 0600
988 or die "$spath.new $!";
989 # we add the new key to the front which means it's always sorted
990 print $newkeys time, ' ', $r->_random_key(), "\n" or die $!;
991 while (my ($gen,$key,$line) = $r->_read_key($keys)) {
992 #print STDERR "_open_keys copy1\n";
993 print $newkeys, $line or die $!;
995 $keys->error and die $!;
996 close $newkeys or die "$spath.new $!";
997 rename "$spath.new", "$spath" or die "$spath: $!";
998 #print STDERR "_open_keys installed\n";
999 # that rename effective unlocks, since it makes the name refer
1000 # to the new file which we haven't locked
1001 # we go round again opening the file at the beginning
1002 # so that our caller gets a fresh handle onto the existing key file
1006 sub _fresh_secret ($) {
1008 #print STDERR "_fresh_secret\n";
1010 my $keys = $r->_open_keys();
1011 my ($keyt, $key) = $r->_read_key($keys);
1012 die unless defined $keyt;
1014 my $nonce = $r->_random_key();
1016 my $message = "$noncet.$nonce";
1018 my $signature = $r->_hmac($key, $message);
1019 my $secret = "$keyt.$signature.$message";
1020 #print STDERR "FRESH $secret\n";
1025 my ($r, $keyhex, $message) = @_;
1026 my $keybin = pack "H*", $keyhex;
1027 my $alg = $r->{S}{hash_algorithm};
1028 #print STDERR "hmac $alg\n";
1029 my $base = new Digest $alg;
1030 #print STDERR "hmac $alg $base\n";
1031 my $digest = new Digest::HMAC $keybin, $base;
1032 #print STDERR "hmac $alg $base $digest\n";
1033 $digest->add($message);
1034 return $digest->hexdigest();
1038 my ($r, $message) = @_;
1039 my $alg = $r->{S}{hash_algorithm};
1040 #print STDERR "hash $alg\n";
1041 my $digest = new Digest $alg;
1042 $digest->add($message);
1043 return $digest->hexdigest();
1046 sub _assert_checked ($) {
1048 die "unchecked" unless exists $r->{Divert};
1053 my $meth = $r->_ch('get_method');
1054 return $meth eq 'POST';
1057 sub _must_be_post ($) {
1059 my $meth = $r->_ch('get_method');
1060 die "mutating non-POST" if $meth ne 'POST';
1063 sub check_mutate ($) {
1065 $r->_assert_checked();
1066 die if $r->{Divert};
1067 $r->_must_be_post();
1072 $r->_assert_checked();
1073 die if $r->{Divert};
1074 return $r->_is_post();
1077 #---------- output ----------
1079 sub secret_cookie_val ($) {
1081 $r->_assert_checked();
1082 return defined $r->{AssocSecret} ? $r->{AssocSecret} : '';
1085 sub secret_hidden_val ($) {
1087 $r->_assert_checked();
1088 return defined $r->{AssocSecret} ? $r->hash($r->{AssocSecret}) : '';
1091 sub secret_hidden_html ($) {
1093 return $r->{Cgi}->hidden(-name => $r->{S}{assoc_param_name},
1094 -default => $r->secret_hidden_val());
1097 sub secret_cookie ($) {
1099 my $secret = $r->secret_cookie_val();
1100 return undef if !defined $secret;
1101 #print STDERR "SC\n";
1102 my $cookv = $r->construct_cookie($secret);
1103 #print STDERR "SC=$cookv\n";
1113 CGI::Auth::Flexible - web authentication optionally using cookies
1117 my $verifier = CGI::Auth::Flexible->new_verifier(setting => value,...);
1118 my $authreq = $verifier->new_request($cgi_request_object);
1120 my $authreq = CGI::Auth::Flexible->new_request($cgi_request_object,
1121 setting => value,...);
1123 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
1125 $authreq->check_ok() or return;
1128 $authreq->check_mutate();
1131 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
1133 my $divert_kind = $authreq->check_divert();
1135 if ($divert_kind eq 'LOGGEDOUT') {
1136 print "goodbye you are now logged out" and quit
1137 } elsif ($divert_kind eq 'NOCOOKIES') {
1138 print "you need cookies" and quit
1144 $authreq->check_mutate();