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! ],
35 @EXPORT_OK = qw(setup);
40 use CGI qw/escapeHTML/;
51 #---------- public utilities ----------
53 sub flatten_params ($) {
56 foreach my $k (keys %$p) {
57 foreach my $v (@{ $p->{$k} }) {
64 #---------- default callbacks ----------
66 sub has_a_param ($$) {
68 foreach my $pn (@{ $r->{S}{$cn} }) {
69 return 1 if $r->_ch('get_param',$pn);
78 foreach my $name ($c->param()) {
79 $p{$name} = [ $c->param($name) ];
84 sub get_cookie_domain ($$$) {
86 my $uri = new URI $r->_ch('get_url');
90 sub login_ok_password ($$) {
92 my $username_params = $r->{S}{username_param_names};
93 my $username = $r->_ch('get_param',$username_params->[0]);
94 my $password = $r->_rp('password_param_name');
95 return undef unless $r->_ch('username_password_ok', $username, $password);
99 sub do_redirect_cgi ($$$$) {
100 my ($c, $r, $new_url, $cookie) = @_;
101 $r->_print($c->header($r->_cgi_header_args($cookie,
102 -status => '303 See other',
103 -location => $new_url)),
104 $r->_ch('gen_start_html',$r->_gt('Redirection')),
105 '<a href="'.escapeHTML($new_url).'">',
106 $r->_gt("If you aren't redirected, click to continue."),
108 $r->_ch('gen_end_html'));
111 sub gen_some_form ($$) {
112 my ($r, $params, $bodyfn) = @_;
113 # Calls $bodyfn->($c,$r) which returns @formbits
116 push @form, ('<form method="POST" action="'.
117 escapeHTML($r->_ch('get_url')).'">');
118 push @form, $bodyfn->($c,$r);
119 foreach my $n (keys %$params) {
120 foreach my $val (@{ $params->{$n} }) {
121 push @form, ('<input type="hidden"'.
122 ' name="'.escapeHTML($n).'"'.
123 ' value="'.escapeHTML($val).'">');
126 push @form, ('</form>');
127 return join "\n", @form;
130 sub gen_plain_login_form ($$) {
131 my ($c,$r, $params) = @_;
132 return $r->gen_some_form($params, sub {
134 push @form, ('<table>');
135 my $sz = 'size="'.$r->{S}{form_entry_size}.'"';
136 foreach my $up (@{ $r->{S}{username_param_names}}) {
137 push @form, ('<tr><td>',$r->_gt(ucfirst $up),'</td>',
138 '<td><input type="text" '.$sz.
139 ' name='.$up.'></td></tr>');
141 push @form, ('<tr><td>'.$r->_gt('Password').'</td>',
142 '<td><input type="password" '.$sz.
143 ' name="'.$r->{S}{password_param_name}.'"></td></tr>');
144 push @form, ('<tr><td colspan="2">',
145 '<input type="submit"'.
146 ' name="'.$r->{S}{dummy_param_name_prefix}.'login"'.
147 ' value="'.$r->_gt('Login').'"></td></tr>',
153 sub gen_postmainpage_form ($$$) {
154 my ($c,$r, $params) = @_;
155 return $r->gen_some_form($params, sub {
157 push @form, ('<input type="submit"',
158 ' name="'.$r->{S}{dummy_param_name_prefix}.'submit"'.
159 ' value="'.$r->_gt('Continue').'">');
164 sub gen_plain_login_link ($$) {
165 my ($c,$r, $params) = @_;
166 my $url = $r->url_with_query_params($params);
167 return ('<a href="'.escapeHTML($url).'">'.
168 $r->_gt('Log in again to continue.').
172 #---------- verifier object methods ----------
179 assocdb_path => 'caf-assocs.db',
180 keys_path => 'caf-keys',
181 assocdb_dsn => undef,
183 assocdb_password => '',
184 assocdb_table => 'caf_assocs',
185 random_source => '/dev/urandom',
186 secretbits => 128, # bits
187 hash_algorithm => "SHA-256",
188 login_timeout => 86400, # seconds
189 login_form_timeout => 3600, # seconds
190 key_rollover => 86400, # seconds
191 assoc_param_name => 'caf_assochash',
192 dummy_param_name_prefix => 'caf__',
193 cookie_name => "caf_assocsecret",
194 password_param_name => 'password',
195 username_param_names => [qw(username)],
196 form_entry_size => 60,
197 logout_param_names => [qw(caf_logout)],
198 loggedout_param_names => [qw(caf_loggedout)],
199 promise_check_mutate => 0,
200 get_param => sub { $_[0]->param($_[2]) },
201 get_params => sub { $_[1]->get_params() },
202 get_cookie => sub { $_[0]->cookie($_[1]->{S}{cookie_name}) },
203 get_method => sub { $_[0]->request_method() },
204 get_url => sub { $_[0]->url(); },
205 is_login => sub { defined $_[1]->_rp('password_param_name') },
206 login_ok => \&login_ok_password,
207 username_password_ok => sub { die },
208 is_logout => sub { $_[1]->has_a_param('logout_param_names') },
209 is_loggedout => sub { $_[1]->has_a_param('loggedout_param_names') },
210 is_page => sub { return 1 },
211 handle_divert => sub { return 0 },
212 do_redirect => \&do_redirect_cgi, # this hook is allowed to throw
214 get_cookie_domain => \&get_cookie_domain,
216 gen_start_html => sub { $_[0]->start_html($_[2]); },
217 gen_end_html => sub { $_[0]->end_html(); },
218 gen_login_form => \&gen_plain_login_form,
219 gen_login_link => \&gen_plain_login_link,
220 gen_postmainpage_form => \&gen_postmainpage_form,
221 gettext => sub { gettext($_[2]); },
222 print => sub { print $_[2] or die $!; },
227 while (($k,$v,@_) = @_) {
228 die "unknown setting $k" unless exists $verifier->{S}{$k};
229 $verifier->{S}{$k} = $v;
231 bless $verifier, $class;
232 $verifier->_dbopen();
236 sub _db_setup_do ($$) {
240 $v->_db_transaction(sub {
241 local ($dbh->{PrintError}) = 0;
252 $v->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=".$v->_get_path('assocdb');
253 my $dsn = $v->{S}{assocdb_dsn};
256 $dbh = DBI->connect($dsn, $v->{S}{assocdb_user},
257 $v->{S}{assocdb_password}, {
260 ShowErrorStatement => 1,
262 die "$dsn $! ?" unless $dbh;
265 $v->_db_setup_do("CREATE TABLE $v->{S}{assocdb_table} (".
266 " assochash VARCHAR PRIMARY KEY,".
267 " username VARCHAR NOT NULL,".
268 " last INTEGER NOT NULL".
270 $v->_db_setup_do("CREATE INDEX $v->{S}{assocdb_table}_timeout_index".
271 " ON $v->{S}{assocdb_table}".
283 sub _db_transaction ($$) {
288 print STDERR "DT entry\n";
290 print STDERR "DT loop\n";
293 print STDERR "DT fn ok\n";
296 print STDERR "DT fn error\n";
297 { local ($@); $dbh->rollback(); }
298 print STDERR "DT fn throwing\n";
301 print STDERR "DT fn eval ok\n";
304 print STDERR "DT commit ok\n";
307 print STDERR "DT commit eval ok ",Dumper($rv);
310 print STDERR "DT commit throw?\n";
311 die $@ if !--$retries;
312 print STDERR "DT loop again\n";
316 #---------- request object methods ----------
319 my ($classbase, $cgi, @extra) = @_;
320 if (!ref $classbase) {
321 $classbase = $classbase->new_verifier(@extra);
327 S => $classbase->{S},
328 Dbh => $classbase->{Dbh},
331 bless $r, ref $classbase;
334 sub _ch ($$@) { # calls an application hook
335 my ($r,$methname, @args) = @_;
336 my $methfunc = $r->{S}{$methname};
337 die "$methname ?" unless $methfunc;
338 return $methfunc->($r->{Cgi}, $r, @args);
343 my $pn = $r->{S}{$pnvb};
344 my $p = scalar $r->_ch('get_param',$pn)
348 my ($v,$keybase) = @_;
349 my $leaf = $v->{S}{"${keybase}_path"};
350 my $dir = $v->{S}{dir};
351 return $leaf if $leaf =~ m,^/,;
352 die "relying on cwd by default ?! set dir" unless defined $dir;
356 sub _gt ($$) { my ($r, $t) = @_; return $r->_ch('gettext',$t); }
357 sub _print ($$) { my ($r, @t) = @_; return $r->_ch('print', join '', @t); }
359 sub construct_cookie ($$$) {
360 my ($r, $cooks) = @_;
361 return undef unless $cooks;
363 my @ca = (-name => $r->{S}{cookie_name},
365 -path => $r->{S}{cookie_path},
366 -domain => $r->_ch('get_cookie_domain'),
367 -expires => '+'.$r->{S}{login_timeout}.'s',
368 -secure => $r->{S}{encrypted_only});
369 my $cookie = $c->cookie(@ca);
370 print STDERR "CC $r $c $cooks $cookie (@ca).\n";
374 # pages/param-sets are
375 # n normal non-mutating page
376 # r retrieval of information for JS, non-mutating
378 # u update of information by JS, mutating
381 # O "you have just logged out" page load
384 # - no value supplied (represented in code as $cookt='')
385 # n, nN value not in our db
386 # t, tN temporary value (in our db, no logged in user yet)
387 # y, yN value corresponds to logged-in user
388 # and, aggregated conditions:
389 # a, aN anything including -
391 # if N differs the case applies only when the two values differ
392 # (eg, a1 y2 does not apply when the logged-in value is supplied twice)
394 # "stale session" means request originates from a page from a login
395 # session which has been revoked (eg by logout); "cleared session"
396 # means request originates from a browser which has a different (or
399 # Case analysis, cookie mode, app promises re mutate:
400 # cook parm meth form
402 # any - POST nrmuoi bug or attack, fail
403 # any - GET rmuoi bug or attack, fail
404 # any any GET muoi bug or attack, fail
405 # any t any nrmu bug or attack, fail
407 # - - GET O "just logged out" page
408 # (any other) O bug or attack, fail
410 # a1 a2 POST o logout
411 # if a1 is valid, revoke it
412 # if a2 is valid, revoke it
414 # redirect to "just logged out" page
415 # (which contains link to login form)
417 # - t POST i complain about cookies being disabled
418 # (with link to login form)
420 # t1 t1 POST i login (or switch user)
422 # show new login form
424 # upgrade t1 to y1 in our db (setting username)
425 # redirect to GET of remaining params
427 # y1 a2 POST i complain about stale login form
429 # show new login form
431 # (other) POST i complain about stale login form
432 # show new login form
434 # t1 a2 ANY nrmu treat as - a2 ANY
436 # y - GET n cross-site link
439 # y y GET nr fine, show page or send data
440 # y y POST nrmu mutation is OK, do operation
442 # y1 y2 GET nr request from stale page
443 # do not revoke y2 as not RESTful
446 # y1 y2 POST nrmu request from stale page
450 # y n GET n intra-site link from stale page,
451 # treat as cross-site link, show data
453 # y n POST n m intra-site form submission from stale page
454 # show "session interrupted"
455 # with link to main data page
457 # y n GET r intra-site request from stale page
460 # y n POST r u intra-site request from stale page
463 # -/n y2 GET nr intra-site link from cleared session
464 # do not revoke y2 as not RESTful
467 # -/n y2 POST nrmu request from cleared session
469 # treat as -/n n POST
471 # -/n -/n GET n cross-site link but user not logged in
472 # show login form with redirect to orig params
473 # generate fresh cookie
475 # -/n n GET rmu user not logged in
478 # -/n n POST n m user not logged in
481 # -/n n POST r u user not logged in
484 sub _check_divert_core ($) {
487 my $meth = $r->_ch('get_method');
488 my $cooks = $r->_ch('get_cookie');
489 my $parmh = $r->_rp('assoc_param_name');
490 my $cookh = defined $cooks ? $r->hash($cooks) : undef;
492 my ($cookt,$cooku) = $r->_identify($cookh, $cooks);
493 my $parms = (defined $cooks && defined $parmh && $parmh eq $cookh)
495 my ($parmt) = $r->_identify($parmh, $parms);
497 print STDERR "_c_d_c cookt=$cookt parmt=$parmt\n";
499 if ($r->_ch('is_logout')) {
502 $r->_db_revoke($cookh);
503 $r->_db_revoke($parmh);
504 return ({ Kind => 'REDIRECT-LOGGEDOUT',
505 Message => "Logging out...",
509 if ($r->_ch('is_loggedout')) {
510 die unless $meth eq 'GET';
513 return ({ Kind => 'SMALLPAGE-LOGGEDOUT',
514 Message => "You have been logged out.",
518 if ($r->_ch('is_login')) {
521 if (!$cookt && $parmt eq 't') {
522 return ({ Kind => 'SMALLPAGE-NOCOOKIE',
523 Message => "You do not seem to have cookies enabled. ".
524 "You must enable cookies as we use them for login.",
525 CookieSecret => $r->_fresh_secret(),
526 Params => $r->chain_params() })
528 if (!$cookt || $cookt eq 'n' || $cookh ne $parmh) {
529 $r->_db_revoke($cookh);
530 return ({ Kind => 'LOGIN-STALE',
531 Message => "Stale session; you need to log in again.",
532 CookieSecret => $r->_fresh_secret(),
535 die unless $parmt eq 't' || $parmt eq 'y';
536 my $username = $r->_ch('login_ok');
537 unless (defined $username && length $username) {
538 return ({ Kind => 'LOGIN-BAD',
539 Message => "Incorrect username/password.",
540 CookieSecret => $cooks,
541 Params => $r->chain_params() })
543 $r->_db_record_login_ok($parmh,$username);
544 return ({ Kind => 'REDIRECT-LOGGEDIN',
545 Message => "Logging in...",
546 CookieSecret => $cooks,
547 Params => $r->chain_params() });
552 die if $parmt eq 't';
554 if ($cookt eq 'y' && $parmt eq 'y' && $cookh ne $parmh) {
555 $r->_db_revoke($parmh) if $meth eq 'POST';
560 die unless !$cookt || $cookt eq 'n';
561 die unless !$parmt || $parmt eq 'n' || $parmt eq 'y';
562 my $news = $r->_fresh_secret();
563 if ($meth eq 'GET') {
564 return ({ Kind => 'LOGIN-INCOMINGLINK',
565 Message => "You need to log in.",
566 CookieSecret => $news,
567 Params => $r->chain_params() });
569 $r->_db_revoke($parmh);
570 return ({ Kind => 'LOGIN-FRESH',
571 Message => "You need to log in.",
572 CookieSecret => $news,
577 if (!$r->{S}{promise_check_mutate}) {
578 if ($meth ne 'POST') {
579 return ({ Kind => 'MAINPAGEONLY',
580 Message => 'Entering via cross-site link.',
581 CookieSecret => $cooks,
583 # NB caller must then ignore params & path!
584 # if this is too hard they can spit out a small form
585 # with a "click to continue"
589 die unless $cookt eq 'y';
590 unless ($r->{S}{promise_check_mutate} && $meth eq 'GET') {
591 die unless $parmt eq 'y';
592 die unless $cookh eq $parmh;
594 $r->{AssocSecret} = $cooks;
595 $r->{UserOK} = $cooku;
596 print STDERR "C-D-C OK\n";
600 sub chain_params ($) {
602 my %p = %{ $r->_ch('get_params') };
603 foreach my $pncn (keys %{ $r->{S} }) {
605 if ($pncn =~ m/_param_name$/) {
606 my $name = $r->{S}{$pncn};
607 die "$pncn ?" if ref $name;
609 } elsif ($pncn =~ m/_param_names$/) {
610 $names = $r->{S}{$pncn};
614 foreach my $name (@$names) {
618 my $dummy_prefix = $r->{S}{dummy_param_name_prefix};
619 foreach my $name (grep /^$dummy_prefix/, keys %p) {
627 # returns ($t,$username)
628 # where $t is one of "t" "y" "n", or "" (for -)
629 # either $s must be undef, or $h eq $r->hash($s)
631 print STDERR "_identify\n";
632 return '' unless defined $h && length $h;
633 print STDERR "_identify h=$h s=".(defined $s ? $s : '<undef>')."\n";
637 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
638 " WHERE last < ?", {},
639 time - $r->{S}{login_timeout});
641 my $row = $dbh->selectrow_arrayref("SELECT username, last".
642 " FROM $r->{S}{assocdb_table}".
643 " WHERE assochash = ?", {}, $h);
645 print STDERR "_identify h=$h s=$s YES @$row\n";
646 my ($nusername, $nlast) = @$row;
647 return ('y', $nusername);
650 # Well, it's not in the database. But maybe it's a hash of a
653 return 'n' unless defined $s;
655 my ($keyt, $signature, $message, $noncet, $nonce) =
656 $s =~ m/^(\d+)\.(\w+)\.((\d+)\.(\w+))$/ or die;
658 return 'n' if time > $noncet + $r->{S}{login_form_timeout};
660 print STDERR "_identify noncet=$noncet ok\n";
662 my $keys = $r->_open_keys();
663 while (my ($rkeyt, $rkey, $line) = $r->_read_key($keys)) {
664 print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey\n";
665 last if $rkeyt < $keyt; # too far down in the file
666 my $trysignature = $r->_hmac($rkey, $message);
667 print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey trysig=$trysignature\n";
668 return 't' if $trysignature eq $signature;
671 print STDERR "_identify NO\n";
673 $keys->error and die $!;
677 sub _db_revoke ($$) {
678 # revokes $h if it's valid; no-op if it's not
683 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
684 " WHERE assochash = ?", {}, $h);
687 sub _db_record_login_ok ($$$) {
688 my ($r,$h,$user) = @_;
691 $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
692 " (assochash, username, last) VALUES (?,?,?)", {},
696 sub check_divert ($) {
698 if (exists $r->{Divert}) {
702 $r->{Divert} = $r->_db_transaction(sub { $r->_check_divert_core(); });
704 print STDERR Dumper($r->{Divert});
710 die "unchecked" unless exists $r->{Divert};
714 sub get_username ($) {
716 my $divert = $r->get_divert();
717 return undef if $divert;
721 sub url_with_query_params ($$) {
722 my ($r, $params) = @_;
723 print STDERR "PARAMS ",Dumper($params);
724 my $uri = URI->new($r->_ch('get_url'));
725 $uri->query_form(flatten_params($params));
726 return $uri->as_string();
729 sub _cgi_header_args ($$@) {
730 my ($r, $cookie, @ha) = @_;
731 unshift @ha, qw(-type text/html);
732 push @ha, (-cookie => $cookie) if defined $cookie;
733 print STDERR "_cgi_header_args ",join('|',@ha),".\n";
740 my ($divert) = $r->check_divert();
741 return 1 if !$divert;
743 my $handled = $r->_ch('handle_divert',$divert);
744 return 0 if $handled;
746 my $kind = $divert->{Kind};
747 my $cookiesecret = $divert->{CookieSecret};
748 my $params = $divert->{Params};
749 my $cookie = $r->construct_cookie($cookiesecret);
751 if (defined $cookiesecret) {
752 $params->{$r->{S}{assoc_param_name}} = [ $r->hash($cookiesecret) ];
755 if ($kind =~ m/^REDIRECT-/) {
756 # for redirects, we honour stored NextParams and SetCookie,
757 # as we would for non-divert
758 if ($kind eq 'REDIRECT-LOGGEDOUT') {
759 $params->{$r->{S}{loggedout_param_names}[0]} = [ 1 ];
760 } elsif ($kind eq 'REDIRECT-LOGOUT') {
761 $params->{$r->{S}{logout_param_names}[0]} = [ 1 ];
762 } elsif ($kind eq 'REDIRECT-LOGGEDIN') {
766 my $new_url = $r->url_with_query_params($params);
767 $r->_ch('do_redirect',$new_url, $cookie);
772 if ($kind =~ m/^LOGIN-/) {
773 $title = $r->_gt('Login');
774 push @body, $r->_gt($divert->{Message});
775 push @body, $r->_ch('gen_login_form', $params);
776 } elsif ($kind =~ m/^SMALLPAGE-/) {
777 $title = $r->_gt('Not logged in');
778 push @body, $r->_gt($divert->{Message});
779 push @body, $r->_ch('gen_login_link', $params);
780 } elsif ($kind =~ m/^MAINPAGEONLY$/) {
781 $title = $r->_gt('Entering secure site.');
782 push @body, $r->_gt($divert->{Message});
783 push @body, $r->_ch('gen_postmainpage_form', $params);
788 $r->_print($r->{Cgi}->header($r->_cgi_header_args($cookie)),
789 $r->_ch('gen_start_html',$title),
791 $r->_ch('gen_end_html'));
796 my ($r, $bytes) = @_;
798 my $rsf = $v->{RandomHandle};
799 my $rsp = $r->{S}{random_source};
801 $v->{RandomHandle} = $rsf = new IO::File $rsp, '<' or die "$rsp $!";
802 print STDERR "RH $rsf\n";
806 read($rsf,$bin,$bytes) == $bytes or die "$rsp $!";
807 my $out = unpack "H*", $bin;
808 print STDERR "_random out $out\n";
812 sub _random_key ($) {
814 print STDERR "_random_key\n";
815 my $bytes = ($r->{S}{secretbits} + 7) >> 3;
816 return $r->_random($bytes);
821 # returns $gen_time_t, $key_value_in_hex, $complete_line
823 my ($gen, $k) = m/^(\d+) (\S+)$/ or die "$_ ?";
824 my $age = time - $gen;
825 next if $age > $r->{S}{key_rollover} &&
826 $age > $r->{S}{login_form_timeout}*2;
827 return ($gen, $k, $_);
834 my $spath = $r->_get_path('keys');
836 print STDERR "_open_keys\n";
837 my $keys = new IO::File $spath, 'r+';
839 print STDERR "_open_keys open\n";
840 stat $keys or die $!; # NB must not disturb stat _
841 my $size = (stat _)[7];
842 my $age = time - (stat _)[9];
843 print STDERR "_open_keys open size=$size age=$age\n";
845 if $size && $age <= $r->{S}{key_rollover} / 2;
846 print STDERR "_open_keys open bad\n";
848 # file doesn't exist, or is empty or too old
850 print STDERR "_open_keys closed\n";
851 die "$spath $!" unless $!==&ENOENT;
852 # doesn't exist, so create it just so we can lock it
853 $keys = new IO::File $spath, 'a+';
854 die "$keys $!" unless $keys;
855 stat $keys or die $!; # NB must not disturb stat _
856 my $size = (stat _)[7];
857 print STDERR "_open_keys created size=$size\n";
858 next if $size; # oh someone else has done it, reopen and read it
860 # file now exists is empty or too old, we must try to replace it
861 my $our_inum = (stat _)[1]; # last use of that stat _
862 flock $keys, LOCK_EX or die "$spath $!";
863 stat $spath or die "$spath $!";
864 my $path_inum = (stat _)[1];
865 print STDERR "_open_keys locked our=$our_inum path=$path_inum\n";
866 next if $our_inum != $path_inum; # someone else has done it
867 # We now hold the lock!
868 print STDERR "_open_keys creating\n";
869 my $newkeys = new IO::Handle;
870 sysopen $newkeys, "$spath.new", O_CREAT|O_TRUNC|O_WRONLY, 0600
871 or die "$spath.new $!";
872 # we add the new key to the front which means it's always sorted
873 print $newkeys time, ' ', $r->_random_key(), "\n" or die $!;
874 while (my ($gen,$key,$line) = $r->_read_key($keys)) {
875 print STDERR "_open_keys copy1\n";
876 print $newkeys, $line or die $!;
878 $keys->error and die $!;
879 close $newkeys or die "$spath.new $!";
880 rename "$spath.new", "$spath" or die "$spath: $!";
881 print STDERR "_open_keys installed\n";
882 # that rename effective unlocks, since it makes the name refer
883 # to the new file which we haven't locked
884 # we go round again opening the file at the beginning
885 # so that our caller gets a fresh handle onto the existing key file
889 sub _fresh_secret ($) {
891 print STDERR "_fresh_secret\n";
893 my $keys = $r->_open_keys();
894 my ($keyt, $key) = $r->_read_key($keys);
895 die unless defined $keyt;
897 my $nonce = $r->_random_key();
899 my $message = "$noncet.$nonce";
901 my $signature = $r->_hmac($key, $message);
902 my $secret = "$keyt.$signature.$message";
903 print STDERR "FRESH $secret\n";
908 my ($r, $keyhex, $message) = @_;
909 my $keybin = pack "H*", $keyhex;
910 my $alg = $r->{S}{hash_algorithm};
911 print STDERR "hmac $alg\n";
912 my $base = new Digest $alg;
913 print STDERR "hmac $alg $base\n";
914 my $digest = new Digest::HMAC $keybin, $base;
915 print STDERR "hmac $alg $base $digest\n";
916 $digest->add($message);
917 return $digest->hexdigest();
921 my ($r, $message) = @_;
922 my $alg = $r->{S}{hash_algorithm};
923 print STDERR "hash $alg\n";
924 my $digest = new Digest $alg;
925 $digest->add($message);
926 return $digest->hexdigest();
929 sub _assert_checked ($) {
931 die "unchecked" unless exists $r->{Divert};
936 my $meth = $r->_ch('get_method');
937 return $meth eq 'POST';
940 sub _must_be_post ($) {
942 my $meth = $r->_ch('get_method');
943 die "mutating non-POST" if $meth ne 'POST';
946 sub check_mutate ($) {
948 $r->_assert_checked();
955 $r->_assert_checked();
957 return $r->_is_post();
960 #---------- output ----------
962 sub secret_cookie_val ($) {
964 $r->_assert_checked();
965 return defined $r->{AssocSecret} ? $r->{AssocSecret} : '';
968 sub secret_hidden_val ($) {
970 $r->_assert_checked();
971 return defined $r->{AssocSecret} ? $r->hash($r->{AssocSecret}) : '';
974 sub secret_hidden_html ($) {
976 return $r->{Cgi}->hidden(-name => $r->{S}{assoc_param_name},
977 -default => $r->secret_hidden_val());
980 sub secret_cookie ($) {
982 my $secret = $r->secret_cookie_val();
983 return undef if !defined $secret;
984 #print STDERR "SC\n";
985 my $cookv = $r->construct_cookie($secret);
986 #print STDERR "SC=$cookv\n";
994 CGI::Auth::Flexible - web authentication optionally using cookies
998 my $verifier = CGI::Auth::Flexible->new_verifier(setting => value,...);
999 my $authreq = $verifier->new_request($cgi_request_object);
1001 my $authreq = CGI::Auth::Flexible->new_request($cgi_request_object,
1002 setting => value,...);
1004 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
1006 $authreq->check_ok() or return;
1009 $authreq->check_mutate();
1012 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
1014 my $divert_kind = $authreq->check_divert();
1016 if ($divert_kind eq 'LOGGEDOUT') {
1017 print "goodbye you are now logged out" and quit
1018 } elsif ($divert_kind eq 'NOCOOKIES') {
1019 print "you need cookies" and quit
1025 $authreq->check_mutate();