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) {
58 foreach my $v (@{ $p->{$k} }) {
65 #---------- default callbacks ----------
67 sub has_a_param ($$) {
69 foreach my $pn (@{ $r->{S}{$cn} }) {
70 return 1 if $r->_ch('get_param',$pn);
79 foreach my $name ($c->param()) {
80 $p{$name} = [ $c->param($name) ];
85 sub get_cookie_domain ($$$) {
87 my $uri = new URI $r->_ch('get_url');
91 sub login_ok_password ($$) {
93 my $username_params = $r->{S}{username_param_names};
94 my $username = $r->_ch('get_param',$username_params->[0]);
95 my $password = $r->_rp('password_param_name');
96 return undef unless $r->_ch('username_password_ok', $username, $password);
100 sub do_redirect_cgi ($$$$) {
101 my ($c, $r, $new_url, $cookie) = @_;
102 $r->_print($c->header($r->_cgi_header_args($cookie,
103 -status => '303 See other',
104 -location => $new_url)),
105 $r->_ch('gen_start_html',$r->_gt('Redirection')),
106 '<a href="'.escapeHTML($new_url).'">',
107 $r->_gt("If you aren't redirected, click to continue."),
109 $r->_ch('gen_end_html'));
112 sub gen_some_form ($$) {
113 my ($r, $params, $bodyfn) = @_;
114 # Calls $bodyfn->($c,$r) which returns @formbits
118 $pathinfo .= $params->{''}[0] if $params->{''};
119 push @form, ('<form method="POST" action="'.
120 escapeHTML($r->_ch('get_url').$pathinfo).'">');
121 push @form, $bodyfn->($c,$r);
122 foreach my $n (keys %$params) {
124 foreach my $val (@{ $params->{$n} }) {
125 push @form, ('<input type="hidden"'.
126 ' name="'.escapeHTML($n).'"'.
127 ' value="'.escapeHTML($val).'">');
130 push @form, ('</form>');
131 return join "\n", @form;
134 sub gen_plain_login_form ($$) {
135 my ($c,$r, $params) = @_;
136 return $r->gen_some_form($params, sub {
138 push @form, ('<table>');
139 my $sz = 'size="'.$r->{S}{form_entry_size}.'"';
140 foreach my $up (@{ $r->{S}{username_param_names}}) {
141 push @form, ('<tr><td>',$r->_gt(ucfirst $up),'</td>',
142 '<td><input type="text" '.$sz.
143 ' name='.$up.'></td></tr>');
145 push @form, ('<tr><td>'.$r->_gt('Password').'</td>',
146 '<td><input type="password" '.$sz.
147 ' name="'.$r->{S}{password_param_name}.'"></td></tr>');
148 push @form, ('<tr><td colspan="2">',
149 '<input type="submit"'.
150 ' name="'.$r->{S}{dummy_param_name_prefix}.'login"'.
151 ' value="'.$r->_gt('Login').'"></td></tr>',
157 sub gen_postmainpage_form ($$$) {
158 my ($c,$r, $params) = @_;
159 return $r->gen_some_form($params, sub {
161 push @form, ('<input type="submit"',
162 ' name="'.$r->{S}{dummy_param_name_prefix}.'submit"'.
163 ' value="'.$r->_gt('Continue').'">');
168 sub gen_plain_login_link ($$) {
169 my ($c,$r, $params) = @_;
170 my $url = $r->url_with_query_params($params);
171 return ('<a href="'.escapeHTML($url).'">'.
172 $r->_gt('Log in again to continue.').
176 #---------- verifier object methods ----------
183 assocdb_path => 'caf-assocs.db',
184 keys_path => 'caf-keys',
185 assocdb_dsn => undef,
187 assocdb_password => '',
188 assocdb_table => 'caf_assocs',
189 random_source => '/dev/urandom',
190 secretbits => 128, # bits
191 hash_algorithm => "SHA-256",
192 login_timeout => 86400, # seconds
193 login_form_timeout => 3600, # seconds
194 key_rollover => 86400, # seconds
195 assoc_param_name => 'caf_assochash',
196 dummy_param_name_prefix => 'caf__',
197 cookie_name => "caf_assocsecret",
198 password_param_name => 'password',
199 username_param_names => [qw(username)],
200 form_entry_size => 60,
201 logout_param_names => [qw(caf_logout)],
202 loggedout_param_names => [qw(caf_loggedout)],
203 promise_check_mutate => 0,
204 get_param => sub { $_[0]->param($_[2]) },
205 get_params => sub { $_[1]->get_params() },
206 get_path_info => sub { $_[0]->path_info() },
207 get_cookie => sub { $_[0]->cookie($_[1]->{S}{cookie_name}) },
208 get_method => sub { $_[0]->request_method() },
209 get_url => sub { $_[0]->url(); },
210 is_login => sub { defined $_[1]->_rp('password_param_name') },
211 login_ok => \&login_ok_password,
212 username_password_ok => sub { die },
213 is_logout => sub { $_[1]->has_a_param('logout_param_names') },
214 is_loggedout => sub { $_[1]->has_a_param('loggedout_param_names') },
215 is_page => sub { return 1 },
216 handle_divert => sub { return 0 },
217 do_redirect => \&do_redirect_cgi, # this hook is allowed to throw
219 get_cookie_domain => \&get_cookie_domain,
221 gen_start_html => sub { $_[0]->start_html($_[2]); },
222 gen_end_html => sub { $_[0]->end_html(); },
223 gen_login_form => \&gen_plain_login_form,
224 gen_login_link => \&gen_plain_login_link,
225 gen_postmainpage_form => \&gen_postmainpage_form,
226 gettext => sub { gettext($_[2]); },
227 print => sub { print $_[2] or die $!; },
232 while (($k,$v,@_) = @_) {
233 die "unknown setting $k" unless exists $verifier->{S}{$k};
234 $verifier->{S}{$k} = $v;
236 bless $verifier, $class;
237 $verifier->_dbopen();
241 sub _db_setup_do ($$) {
245 $v->_db_transaction(sub {
246 local ($dbh->{PrintError}) = 0;
257 $v->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=".$v->_get_path('assocdb');
258 my $dsn = $v->{S}{assocdb_dsn};
261 $dbh = DBI->connect($dsn, $v->{S}{assocdb_user},
262 $v->{S}{assocdb_password}, {
265 ShowErrorStatement => 1,
267 die "$dsn $! ?" unless $dbh;
270 $v->_db_setup_do("CREATE TABLE $v->{S}{assocdb_table} (".
271 " assochash VARCHAR PRIMARY KEY,".
272 " username VARCHAR NOT NULL,".
273 " last INTEGER NOT NULL".
275 $v->_db_setup_do("CREATE INDEX $v->{S}{assocdb_table}_timeout_index".
276 " ON $v->{S}{assocdb_table}".
288 sub _db_transaction ($$) {
293 print STDERR "DT entry\n";
295 print STDERR "DT loop\n";
298 print STDERR "DT fn ok\n";
301 print STDERR "DT fn error\n";
302 { local ($@); $dbh->rollback(); }
303 print STDERR "DT fn throwing\n";
306 print STDERR "DT fn eval ok\n";
309 print STDERR "DT commit ok\n";
312 print STDERR "DT commit eval ok ",Dumper($rv);
315 print STDERR "DT commit throw?\n";
316 die $@ if !--$retries;
317 print STDERR "DT loop again\n";
321 #---------- request object methods ----------
324 my ($classbase, $cgi, @extra) = @_;
325 if (!ref $classbase) {
326 $classbase = $classbase->new_verifier(@extra);
332 S => $classbase->{S},
333 Dbh => $classbase->{Dbh},
336 bless $r, ref $classbase;
339 sub _ch ($$@) { # calls an application hook
340 my ($r,$methname, @args) = @_;
341 my $methfunc = $r->{S}{$methname};
342 die "$methname ?" unless $methfunc;
343 return $methfunc->($r->{Cgi}, $r, @args);
348 my $pn = $r->{S}{$pnvb};
349 my $p = scalar $r->_ch('get_param',$pn)
353 my ($v,$keybase) = @_;
354 my $leaf = $v->{S}{"${keybase}_path"};
355 my $dir = $v->{S}{dir};
356 return $leaf if $leaf =~ m,^/,;
357 die "relying on cwd by default ?! set dir" unless defined $dir;
361 sub _gt ($$) { my ($r, $t) = @_; return $r->_ch('gettext',$t); }
362 sub _print ($$) { my ($r, @t) = @_; return $r->_ch('print', join '', @t); }
364 sub construct_cookie ($$$) {
365 my ($r, $cooks) = @_;
366 return undef unless $cooks;
368 my @ca = (-name => $r->{S}{cookie_name},
370 -path => $r->{S}{cookie_path},
371 -domain => $r->_ch('get_cookie_domain'),
372 -expires => '+'.$r->{S}{login_timeout}.'s',
373 -secure => $r->{S}{encrypted_only});
374 my $cookie = $c->cookie(@ca);
375 print STDERR "CC $r $c $cooks $cookie (@ca).\n";
379 # pages/param-sets are
380 # n normal non-mutating page
381 # r retrieval of information for JS, non-mutating
383 # u update of information by JS, mutating
386 # O "you have just logged out" page load
389 # - no value supplied (represented in code as $cookt='')
390 # n, nN value not in our db
391 # t, tN temporary value (in our db, no logged in user yet)
392 # y, yN value corresponds to logged-in user
393 # and, aggregated conditions:
394 # a, aN anything including -
396 # if N differs the case applies only when the two values differ
397 # (eg, a1 y2 does not apply when the logged-in value is supplied twice)
399 # "stale session" means request originates from a page from a login
400 # session which has been revoked (eg by logout); "cleared session"
401 # means request originates from a browser which has a different (or
404 # Case analysis, cookie mode, app promises re mutate:
405 # cook parm meth form
407 # any - POST nrmuoi bug or attack, fail
408 # any - GET rmuoi bug or attack, fail
409 # any any GET muoi bug or attack, fail
410 # any t any nrmu bug or attack, fail
412 # - - GET O "just logged out" page
413 # (any other) O bug or attack, fail
415 # a1 a2 POST o logout
416 # if a1 is valid, revoke it
417 # if a2 is valid, revoke it
419 # redirect to "just logged out" page
420 # (which contains link to login form)
422 # - t POST i complain about cookies being disabled
423 # (with link to login form)
425 # t1 t1 POST i login (or switch user)
427 # show new login form
429 # upgrade t1 to y1 in our db (setting username)
430 # redirect to GET of remaining params
432 # y1 a2 POST i complain about stale login form
434 # show new login form
436 # (other) POST i complain about stale login form
437 # show new login form
439 # t1 a2 ANY nrmu treat as - a2 ANY
441 # y - GET n cross-site link
444 # y y GET nr fine, show page or send data
445 # y y POST nrmu mutation is OK, do operation
447 # y1 y2 GET nr request from stale page
448 # do not revoke y2 as not RESTful
451 # y1 y2 POST nrmu request from stale page
455 # y n GET n intra-site link from stale page,
456 # treat as cross-site link, show data
458 # y n POST n m intra-site form submission from stale page
459 # show "session interrupted"
460 # with link to main data page
462 # y n GET r intra-site request from stale page
465 # y n POST r u intra-site request from stale page
468 # -/n y2 GET nr intra-site link from cleared session
469 # do not revoke y2 as not RESTful
472 # -/n y2 POST nrmu request from cleared session
474 # treat as -/n n POST
476 # -/n -/n GET n cross-site link but user not logged in
477 # show login form with redirect to orig params
478 # generate fresh cookie
480 # -/n n GET rmu user not logged in
483 # -/n n POST n m user not logged in
486 # -/n n POST r u user not logged in
489 sub _check_divert_core ($) {
492 my $meth = $r->_ch('get_method');
493 my $cooks = $r->_ch('get_cookie');
494 my $parmh = $r->_rp('assoc_param_name');
495 my $cookh = defined $cooks ? $r->hash($cooks) : undef;
497 my ($cookt,$cooku) = $r->_identify($cookh, $cooks);
498 my $parms = (defined $cooks && defined $parmh && $parmh eq $cookh)
500 my ($parmt) = $r->_identify($parmh, $parms);
502 print STDERR "_c_d_c cookt=$cookt parmt=$parmt\n";
504 if ($r->_ch('is_logout')) {
507 $r->_db_revoke($cookh);
508 $r->_db_revoke($parmh);
509 return ({ Kind => 'REDIRECT-LOGGEDOUT',
510 Message => "Logging out...",
514 if ($r->_ch('is_loggedout')) {
515 die unless $meth eq 'GET';
518 return ({ Kind => 'SMALLPAGE-LOGGEDOUT',
519 Message => "You have been logged out.",
523 if ($r->_ch('is_login')) {
526 if (!$cookt && $parmt eq 't') {
527 return ({ Kind => 'SMALLPAGE-NOCOOKIE',
528 Message => "You do not seem to have cookies enabled. ".
529 "You must enable cookies as we use them for login.",
530 CookieSecret => $r->_fresh_secret(),
531 Params => $r->chain_params() })
533 if (!$cookt || $cookt eq 'n' || $cookh ne $parmh) {
534 $r->_db_revoke($cookh);
535 return ({ Kind => 'LOGIN-STALE',
536 Message => "Stale session; you need to log in again.",
537 CookieSecret => $r->_fresh_secret(),
540 die unless $parmt eq 't' || $parmt eq 'y';
541 my $username = $r->_ch('login_ok');
542 unless (defined $username && length $username) {
543 return ({ Kind => 'LOGIN-BAD',
544 Message => "Incorrect username/password.",
545 CookieSecret => $cooks,
546 Params => $r->chain_params() })
548 $r->_db_record_login_ok($parmh,$username);
549 return ({ Kind => 'REDIRECT-LOGGEDIN',
550 Message => "Logging in...",
551 CookieSecret => $cooks,
552 Params => $r->chain_params() });
557 die if $parmt eq 't';
559 if ($cookt eq 'y' && $parmt eq 'y' && $cookh ne $parmh) {
560 $r->_db_revoke($parmh) if $meth eq 'POST';
565 die unless !$cookt || $cookt eq 'n';
566 die unless !$parmt || $parmt eq 'n' || $parmt eq 'y';
567 my $news = $r->_fresh_secret();
568 if ($meth eq 'GET') {
569 return ({ Kind => 'LOGIN-INCOMINGLINK',
570 Message => "You need to log in.",
571 CookieSecret => $news,
572 Params => $r->chain_params() });
574 $r->_db_revoke($parmh);
575 return ({ Kind => 'LOGIN-FRESH',
576 Message => "You need to log in.",
577 CookieSecret => $news,
582 if (!$r->{S}{promise_check_mutate}) {
583 if ($meth ne 'POST') {
584 return ({ Kind => 'MAINPAGEONLY',
585 Message => 'Entering via cross-site link.',
586 CookieSecret => $cooks,
588 # NB caller must then ignore params & path!
589 # if this is too hard they can spit out a small form
590 # with a "click to continue"
594 die unless $cookt eq 'y';
595 unless ($r->{S}{promise_check_mutate} && $meth eq 'GET') {
596 die unless $parmt eq 'y';
597 die unless $cookh eq $parmh;
599 $r->{AssocSecret} = $cooks;
600 $r->{UserOK} = $cooku;
601 print STDERR "C-D-C OK\n";
605 sub chain_params ($) {
607 my %p = %{ $r->_ch('get_params') };
608 foreach my $pncn (keys %{ $r->{S} }) {
610 if ($pncn =~ m/_param_name$/) {
611 my $name = $r->{S}{$pncn};
612 die "$pncn ?" if ref $name;
614 } elsif ($pncn =~ m/_param_names$/) {
615 $names = $r->{S}{$pncn};
619 foreach my $name (@$names) {
623 my $dummy_prefix = $r->{S}{dummy_param_name_prefix};
624 foreach my $name (grep /^$dummy_prefix/, keys %p) {
627 die if exists $p{''};
628 $p{''} = [ $r->_ch('get_path_info') ];
634 # returns ($t,$username)
635 # where $t is one of "t" "y" "n", or "" (for -)
636 # either $s must be undef, or $h eq $r->hash($s)
638 print STDERR "_identify\n";
639 return '' unless defined $h && length $h;
640 print STDERR "_identify h=$h s=".(defined $s ? $s : '<undef>')."\n";
644 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
645 " WHERE last < ?", {},
646 time - $r->{S}{login_timeout});
648 my $row = $dbh->selectrow_arrayref("SELECT username, last".
649 " FROM $r->{S}{assocdb_table}".
650 " WHERE assochash = ?", {}, $h);
652 print STDERR "_identify h=$h s=$s YES @$row\n";
653 my ($nusername, $nlast) = @$row;
654 return ('y', $nusername);
657 # Well, it's not in the database. But maybe it's a hash of a
660 return 'n' unless defined $s;
662 my ($keyt, $signature, $message, $noncet, $nonce) =
663 $s =~ m/^(\d+)\.(\w+)\.((\d+)\.(\w+))$/ or die;
665 return 'n' if time > $noncet + $r->{S}{login_form_timeout};
667 print STDERR "_identify noncet=$noncet ok\n";
669 my $keys = $r->_open_keys();
670 while (my ($rkeyt, $rkey, $line) = $r->_read_key($keys)) {
671 print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey\n";
672 last if $rkeyt < $keyt; # too far down in the file
673 my $trysignature = $r->_hmac($rkey, $message);
674 print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey trysig=$trysignature\n";
675 return 't' if $trysignature eq $signature;
678 print STDERR "_identify NO\n";
680 $keys->error and die $!;
684 sub _db_revoke ($$) {
685 # revokes $h if it's valid; no-op if it's not
690 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
691 " WHERE assochash = ?", {}, $h);
694 sub _db_record_login_ok ($$$) {
695 my ($r,$h,$user) = @_;
698 $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
699 " (assochash, username, last) VALUES (?,?,?)", {},
703 sub check_divert ($) {
705 if (exists $r->{Divert}) {
709 $r->{Divert} = $r->_db_transaction(sub { $r->_check_divert_core(); });
711 print STDERR Dumper($r->{Divert});
717 die "unchecked" unless exists $r->{Divert};
721 sub get_username ($) {
723 my $divert = $r->get_divert();
724 return undef if $divert;
728 sub url_with_query_params ($$) {
729 my ($r, $params) = @_;
730 print STDERR "PARAMS ",Dumper($params);
731 my $uri = URI->new($r->_ch('get_url'));
732 $uri->path($uri->path() . $params->{''}[0]) if $params->{''};
733 $uri->query_form(flatten_params($params));
734 return $uri->as_string();
737 sub _cgi_header_args ($$@) {
738 my ($r, $cookie, @ha) = @_;
739 unshift @ha, qw(-type text/html);
740 push @ha, (-cookie => $cookie) if defined $cookie;
741 print STDERR "_cgi_header_args ",join('|',@ha),".\n";
748 my ($divert) = $r->check_divert();
749 return 1 if !$divert;
751 my $handled = $r->_ch('handle_divert',$divert);
752 return 0 if $handled;
754 my $kind = $divert->{Kind};
755 my $cookiesecret = $divert->{CookieSecret};
756 my $params = $divert->{Params};
757 my $cookie = $r->construct_cookie($cookiesecret);
759 if ($kind =~ m/^REDIRECT-/) {
760 # for redirects, we honour stored NextParams and SetCookie,
761 # as we would for non-divert
762 if ($kind eq 'REDIRECT-LOGGEDOUT') {
763 $params->{$r->{S}{loggedout_param_names}[0]} = [ 1 ];
764 } elsif ($kind eq 'REDIRECT-LOGOUT') {
765 $params->{$r->{S}{logout_param_names}[0]} = [ 1 ];
766 } elsif ($kind eq 'REDIRECT-LOGGEDIN') {
770 my $new_url = $r->url_with_query_params($params);
771 $r->_ch('do_redirect',$new_url, $cookie);
775 if (defined $cookiesecret) {
776 $params->{$r->{S}{assoc_param_name}} = [ $r->hash($cookiesecret) ];
780 if ($kind =~ m/^LOGIN-/) {
781 $title = $r->_gt('Login');
782 push @body, $r->_gt($divert->{Message});
783 push @body, $r->_ch('gen_login_form', $params);
784 } elsif ($kind =~ m/^SMALLPAGE-/) {
785 $title = $r->_gt('Not logged in');
786 push @body, $r->_gt($divert->{Message});
787 push @body, $r->_ch('gen_login_link', $params);
788 } elsif ($kind =~ m/^MAINPAGEONLY$/) {
789 $title = $r->_gt('Entering secure site.');
790 push @body, $r->_gt($divert->{Message});
791 push @body, $r->_ch('gen_postmainpage_form', $params);
796 $r->_print($r->{Cgi}->header($r->_cgi_header_args($cookie)),
797 $r->_ch('gen_start_html',$title),
799 $r->_ch('gen_end_html'));
804 my ($r, $bytes) = @_;
806 my $rsf = $v->{RandomHandle};
807 my $rsp = $r->{S}{random_source};
809 $v->{RandomHandle} = $rsf = new IO::File $rsp, '<' or die "$rsp $!";
810 print STDERR "RH $rsf\n";
814 read($rsf,$bin,$bytes) == $bytes or die "$rsp $!";
815 my $out = unpack "H*", $bin;
816 print STDERR "_random out $out\n";
820 sub _random_key ($) {
822 print STDERR "_random_key\n";
823 my $bytes = ($r->{S}{secretbits} + 7) >> 3;
824 return $r->_random($bytes);
829 # returns $gen_time_t, $key_value_in_hex, $complete_line
831 my ($gen, $k) = m/^(\d+) (\S+)$/ or die "$_ ?";
832 my $age = time - $gen;
833 next if $age > $r->{S}{key_rollover} &&
834 $age > $r->{S}{login_form_timeout}*2;
835 return ($gen, $k, $_);
842 my $spath = $r->_get_path('keys');
844 print STDERR "_open_keys\n";
845 my $keys = new IO::File $spath, 'r+';
847 print STDERR "_open_keys open\n";
848 stat $keys or die $!; # NB must not disturb stat _
849 my $size = (stat _)[7];
850 my $age = time - (stat _)[9];
851 print STDERR "_open_keys open size=$size age=$age\n";
853 if $size && $age <= $r->{S}{key_rollover} / 2;
854 print STDERR "_open_keys open bad\n";
856 # file doesn't exist, or is empty or too old
858 print STDERR "_open_keys closed\n";
859 die "$spath $!" unless $!==&ENOENT;
860 # doesn't exist, so create it just so we can lock it
861 $keys = new IO::File $spath, 'a+';
862 die "$keys $!" unless $keys;
863 stat $keys or die $!; # NB must not disturb stat _
864 my $size = (stat _)[7];
865 print STDERR "_open_keys created size=$size\n";
866 next if $size; # oh someone else has done it, reopen and read it
868 # file now exists is empty or too old, we must try to replace it
869 my $our_inum = (stat _)[1]; # last use of that stat _
870 flock $keys, LOCK_EX or die "$spath $!";
871 stat $spath or die "$spath $!";
872 my $path_inum = (stat _)[1];
873 print STDERR "_open_keys locked our=$our_inum path=$path_inum\n";
874 next if $our_inum != $path_inum; # someone else has done it
875 # We now hold the lock!
876 print STDERR "_open_keys creating\n";
877 my $newkeys = new IO::Handle;
878 sysopen $newkeys, "$spath.new", O_CREAT|O_TRUNC|O_WRONLY, 0600
879 or die "$spath.new $!";
880 # we add the new key to the front which means it's always sorted
881 print $newkeys time, ' ', $r->_random_key(), "\n" or die $!;
882 while (my ($gen,$key,$line) = $r->_read_key($keys)) {
883 print STDERR "_open_keys copy1\n";
884 print $newkeys, $line or die $!;
886 $keys->error and die $!;
887 close $newkeys or die "$spath.new $!";
888 rename "$spath.new", "$spath" or die "$spath: $!";
889 print STDERR "_open_keys installed\n";
890 # that rename effective unlocks, since it makes the name refer
891 # to the new file which we haven't locked
892 # we go round again opening the file at the beginning
893 # so that our caller gets a fresh handle onto the existing key file
897 sub _fresh_secret ($) {
899 print STDERR "_fresh_secret\n";
901 my $keys = $r->_open_keys();
902 my ($keyt, $key) = $r->_read_key($keys);
903 die unless defined $keyt;
905 my $nonce = $r->_random_key();
907 my $message = "$noncet.$nonce";
909 my $signature = $r->_hmac($key, $message);
910 my $secret = "$keyt.$signature.$message";
911 print STDERR "FRESH $secret\n";
916 my ($r, $keyhex, $message) = @_;
917 my $keybin = pack "H*", $keyhex;
918 my $alg = $r->{S}{hash_algorithm};
919 print STDERR "hmac $alg\n";
920 my $base = new Digest $alg;
921 print STDERR "hmac $alg $base\n";
922 my $digest = new Digest::HMAC $keybin, $base;
923 print STDERR "hmac $alg $base $digest\n";
924 $digest->add($message);
925 return $digest->hexdigest();
929 my ($r, $message) = @_;
930 my $alg = $r->{S}{hash_algorithm};
931 print STDERR "hash $alg\n";
932 my $digest = new Digest $alg;
933 $digest->add($message);
934 return $digest->hexdigest();
937 sub _assert_checked ($) {
939 die "unchecked" unless exists $r->{Divert};
944 my $meth = $r->_ch('get_method');
945 return $meth eq 'POST';
948 sub _must_be_post ($) {
950 my $meth = $r->_ch('get_method');
951 die "mutating non-POST" if $meth ne 'POST';
954 sub check_mutate ($) {
956 $r->_assert_checked();
963 $r->_assert_checked();
965 return $r->_is_post();
968 #---------- output ----------
970 sub secret_cookie_val ($) {
972 $r->_assert_checked();
973 return defined $r->{AssocSecret} ? $r->{AssocSecret} : '';
976 sub secret_hidden_val ($) {
978 $r->_assert_checked();
979 return defined $r->{AssocSecret} ? $r->hash($r->{AssocSecret}) : '';
982 sub secret_hidden_html ($) {
984 return $r->{Cgi}->hidden(-name => $r->{S}{assoc_param_name},
985 -default => $r->secret_hidden_val());
988 sub secret_cookie ($) {
990 my $secret = $r->secret_cookie_val();
991 return undef if !defined $secret;
992 #print STDERR "SC\n";
993 my $cookv = $r->construct_cookie($secret);
994 #print STDERR "SC=$cookv\n";
1002 CGI::Auth::Flexible - web authentication optionally using cookies
1006 my $verifier = CGI::Auth::Flexible->new_verifier(setting => value,...);
1007 my $authreq = $verifier->new_request($cgi_request_object);
1009 my $authreq = CGI::Auth::Flexible->new_request($cgi_request_object,
1010 setting => value,...);
1012 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
1014 $authreq->check_ok() or return;
1017 $authreq->check_mutate();
1020 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
1022 my $divert_kind = $authreq->check_divert();
1024 if ($divert_kind eq 'LOGGEDOUT') {
1025 print "goodbye you are now logged out" and quit
1026 } elsif ($divert_kind eq 'NOCOOKIES') {
1027 print "you need cookies" and quit
1033 $authreq->check_mutate();