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/;
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 my $error = $r->_ch('username_password_error', $username, $password);
97 return defined($error) ? (undef,$error) : ($username,undef);
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 sub gen_special_link_html ($$$$) {
177 my ($c,$r,$anchor,$specval) = @_;
178 my %params = ($r->{S}{special_param_name} => [ $specval ]);
179 return '<a href="'.escapeHTML($r->url_with_query_params(\%params)).'">'.
182 sub gen_plain_licence_link_html ($$) {
184 gen_special_link_html($c,$r, 'GNU Affero GPL', 'licence');
186 sub gen_plain_source_link_html ($$) {
188 gen_special_link_html($c,$r, 'Source available', 'source');
191 sub gen_plain_footer_html ($$) {
193 return ('<hr><address>',
194 ("Powered by Free / Libre / Open Source Software".
195 " according to the ".$r->_ch('gen_licence_link_html')."."),
196 $r->_ch('gen_source_link_html').".",
200 #---------- verifier object methods ----------
207 assocdb_dbh => undef, # must have AutoCommit=0, RaiseError=1
208 assocdb_path => 'caf-assocs.db',
209 keys_path => 'caf-keys',
210 assocdb_dsn => undef,
212 assocdb_password => '',
213 assocdb_table => 'caf_assocs',
214 random_source => '/dev/urandom',
215 secretbits => 128, # bits
216 hash_algorithm => "SHA-256",
217 login_timeout => 86400, # seconds
218 login_form_timeout => 3600, # seconds
219 key_rollover => 86400, # seconds
220 assoc_param_name => 'caf_assochash',
221 dummy_param_name_prefix => 'caf__',
222 cookie_name => "caf_assocsecret",
223 password_param_name => 'password',
224 special_param_name => 'caf_special',
225 username_param_names => [qw(username)],
226 form_entry_size => 60,
227 logout_param_names => [qw(caf_logout)],
228 loggedout_param_names => [qw(caf_loggedout)],
229 promise_check_mutate => 0,
230 get_param => sub { $_[0]->param($_[2]) },
231 get_params => sub { $_[1]->get_params() },
232 get_path_info => sub { $_[0]->path_info() },
233 get_cookie => sub { $_[0]->cookie($_[1]->{S}{cookie_name}) },
234 get_method => sub { $_[0]->request_method() },
235 check_https => sub { !!$_[0]->https() },
236 get_url => sub { $_[0]->url(); },
237 is_login => sub { defined $_[1]->_rp('password_param_name') },
238 login_ok => \&login_ok_password,
239 username_password_error => sub { die },
240 is_logout => sub { $_[1]->has_a_param('logout_param_names') },
241 is_loggedout => sub { $_[1]->has_a_param('loggedout_param_names') },
242 is_page => sub { return 1 },
243 handle_divert => sub { return 0 },
244 do_redirect => \&do_redirect_cgi, # this hook is allowed to throw
246 get_cookie_domain => \&get_cookie_domain,
248 gen_start_html => sub { $_[0]->start_html($_[2]); },
249 gen_footer_html => \&gen_plain_footer_html,
250 gen_licence_link_html => \&gen_plain_licence_link_html,
251 gen_source_link_html => \&gen_plain_source_link_html,
252 gen_end_html => sub { $_[0]->end_html(); },
253 gen_login_form => \&gen_plain_login_form,
254 gen_login_link => \&gen_plain_login_link,
255 gen_postmainpage_form => \&gen_postmainpage_form,
256 gettext => sub { gettext($_[2]); },
257 print => sub { print $_[2] or die $!; },
258 debug => sub { }, # like print; msgs contain trailing \n
263 while (($k,$v,@_) = @_) {
264 die "unknown setting $k" unless exists $verifier->{S}{$k};
265 $verifier->{S}{$k} = $v;
267 bless $verifier, $class;
268 $verifier->_dbopen();
272 sub _db_setup_do ($$) {
276 $v->_db_transaction(sub {
277 local ($dbh->{PrintError}) = 0;
288 $dbh = $v->{S}{assocdb_dbh};
290 die if $dbh->{AutoCommit};
291 die unless $dbh->{RaiseError};
293 $v->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=".$v->_get_path('assocdb');
294 my $dsn = $v->{S}{assocdb_dsn};
297 $dbh = DBI->connect($dsn, $v->{S}{assocdb_user},
298 $v->{S}{assocdb_password}, {
301 ShowErrorStatement => 1,
304 die "$dsn $! ?" unless $dbh;
308 $v->_db_setup_do("CREATE TABLE $v->{S}{assocdb_table} (".
309 " assochash VARCHAR PRIMARY KEY,".
310 " username VARCHAR NOT NULL,".
311 " last INTEGER NOT NULL".
313 $v->_db_setup_do("CREATE INDEX $v->{S}{assocdb_table}_timeout_index".
314 " ON $v->{S}{assocdb_table}".
326 sub _db_transaction ($$) {
331 #print STDERR "DT entry\n";
333 #print STDERR "DT loop\n";
336 #print STDERR "DT fn ok\n";
339 #print STDERR "DT fn error\n";
340 { local ($@); $dbh->rollback(); }
341 #print STDERR "DT fn throwing\n";
344 #print STDERR "DT fn eval ok\n";
347 #print STDERR "DT commit ok\n";
350 #print STDERR "DT commit eval ok ",Dumper($rv);
353 #print STDERR "DT commit throw?\n";
354 die $@ if !--$retries;
355 #print STDERR "DT loop again\n";
359 #---------- request object methods ----------
362 my ($classbase, $cgi, @extra) = @_;
363 if (!ref $classbase) {
364 $classbase = $classbase->new_verifier(@extra);
370 S => $classbase->{S},
371 Dbh => $classbase->{Dbh},
374 bless $r, ref $classbase;
377 sub _ch ($$@) { # calls an application hook
378 my ($r,$methname, @args) = @_;
379 my $methfunc = $r->{S}{$methname};
380 die "$methname ?" unless $methfunc;
381 return $methfunc->($r->{Cgi}, $r, @args);
386 my $pn = $r->{S}{$pnvb};
387 my $p = scalar $r->_ch('get_param',$pn)
392 $r->_ch('debug',@args);
396 my ($v,$keybase) = @_;
397 my $leaf = $v->{S}{"${keybase}_path"};
398 my $dir = $v->{S}{dir};
399 return $leaf if $leaf =~ m,^/,;
400 die "relying on cwd by default ?! set dir" unless defined $dir;
404 sub _gt ($$) { my ($r, $t) = @_; return $r->_ch('gettext',$t); }
405 sub _print ($$) { my ($r, @t) = @_; return $r->_ch('print', join '', @t); }
407 sub construct_cookie ($$$) {
408 my ($r, $cooks) = @_;
409 return undef unless $cooks;
411 my @ca = (-name => $r->{S}{cookie_name},
413 -path => $r->{S}{cookie_path},
414 -domain => $r->_ch('get_cookie_domain'),
415 -expires => '+'.$r->{S}{login_timeout}.'s',
416 -secure => $r->{S}{encrypted_only});
417 my $cookie = $c->cookie(@ca);
418 #print STDERR "CC $r $c $cooks $cookie (@ca).\n";
422 # pages/param-sets are
423 # n normal non-mutating page
424 # r retrieval of information for JS, non-mutating
426 # u update of information by JS, mutating
429 # O "you have just logged out" page load
432 # - no value supplied (represented in code as $cookt='')
433 # n, nN value not in our db
434 # t, tN temporary value (in our db, no logged in user yet)
435 # y, yN value corresponds to logged-in user
436 # and, aggregated conditions:
437 # a, aN anything including -
439 # if N differs the case applies only when the two values differ
440 # (eg, a1 y2 does not apply when the logged-in value is supplied twice)
442 # "stale session" means request originates from a page from a login
443 # session which has been revoked (eg by logout); "cleared session"
444 # means request originates from a browser which has a different (or
447 # Case analysis, cookie mode, app promises re mutate:
448 # cook parm meth form
450 # any - POST nrmuoi bug or attack, fail
451 # any - GET rmuoi bug or attack, fail
452 # any any GET muoi bug or attack, fail
453 # any t any nrmu bug or attack, fail
455 # - - GET O "just logged out" page
456 # (any other) O bug or attack, fail
458 # a1 a2 POST o logout
459 # if a1 is valid, revoke it
460 # if a2 is valid, revoke it
462 # redirect to "just logged out" page
463 # (which contains link to login form)
465 # - t POST i complain about cookies being disabled
466 # (with link to login form)
468 # t1 t1 POST i login (or switch user)
470 # show new login form
472 # upgrade t1 to y1 in our db (setting username)
473 # redirect to GET of remaining params
475 # y1 a2 POST i complain about stale login form
477 # show new login form
479 # (other) POST i complain about stale login form
480 # show new login form
482 # t1 a2 ANY nrmu treat as - a2 ANY
484 # y - GET n cross-site link
487 # y y GET nr fine, show page or send data
488 # y y POST nrmu mutation is OK, do operation
490 # y1 y2 GET nr request from stale page
491 # do not revoke y2 as not RESTful
494 # y1 y2 POST nrmu request from stale page
498 # y n GET n intra-site link from stale page,
499 # treat as cross-site link, show data
501 # y n POST n m intra-site form submission from stale page
502 # show "session interrupted"
503 # with link to main data page
505 # y n GET r intra-site request from stale page
508 # y n POST r u intra-site request from stale page
511 # -/n y2 GET nr intra-site link from cleared session
512 # do not revoke y2 as not RESTful
515 # -/n y2 POST nrmu request from cleared session
517 # treat as -/n n POST
519 # -/n -/n GET n cross-site link but user not logged in
520 # show login form with redirect to orig params
521 # generate fresh cookie
523 # -/n n GET rmu user not logged in
526 # -/n n POST n m user not logged in
529 # -/n n POST r u user not logged in
532 sub _check_divert_core ($) {
535 my $special = $r->_rp('special_param_name');
537 die if $special =~ m/\W/;
538 return ({ Kind => 'SPECIAL-'.uc $special,
540 CookieSecret => undef,
544 my $cooks = $r->_ch('get_cookie');
546 if ($r->{S}{encrypted_only} && !$r->_ch('check_https')) {
547 return ({ Kind => 'REDIRECT-HTTPS',
548 Message => $r->_gt("Redirecting to secure server..."),
549 CookieSecret => undef,
553 my $meth = $r->_ch('get_method');
554 my $parmh = $r->_rp('assoc_param_name');
555 my $cookh = defined $cooks ? $r->hash($cooks) : undef;
557 my ($cookt,$cooku) = $r->_identify($cookh, $cooks);
558 my $parms = (defined $cooks && defined $parmh && $parmh eq $cookh)
560 my ($parmt) = $r->_identify($parmh, $parms);
562 $r->_debug("_c_d_c cookt=$cookt parmt=$parmt\n");
564 if ($r->_ch('is_logout')) {
567 $r->_db_revoke($cookh);
568 $r->_db_revoke($parmh);
569 return ({ Kind => 'REDIRECT-LOGGEDOUT',
570 Message => $r->_gt("Logging out..."),
574 if ($r->_ch('is_loggedout')) {
575 die unless $meth eq 'GET';
576 die if $cookt eq 'y';
578 return ({ Kind => 'SMALLPAGE-LOGGEDOUT',
579 Message => $r->_gt("You have been logged out."),
583 if ($r->_ch('is_login')) {
586 if (!$cookt && $parmt eq 'n') {
587 return ({ Kind => 'SMALLPAGE-NOCOOKIE',
588 Message => $r->_gt("You do not seem to have cookies".
589 " enabled. You must enable cookies".
590 " as we use them for login."),
591 CookieSecret => $r->_fresh_secret(),
592 Params => $r->chain_params() })
594 if (!$cookt || $cookt eq 'n' || $cookh ne $parmh) {
595 $r->_db_revoke($cookh);
596 return ({ Kind => 'LOGIN-STALE',
597 Message => $r->_gt("Stale session;".
598 " you need to log in again."),
599 CookieSecret => $r->_fresh_secret(),
602 die unless $parmt eq 't' || $parmt eq 'y';
603 my ($username, $login_errormessage) = $r->_ch('login_ok');
604 unless (defined $username && length $username) {
605 $login_errormessage = $r->_gt("Incorrect username/password.")
606 if !$login_errormessage;
607 return ({ Kind => 'LOGIN-BAD',
608 Message => $login_errormessage,
609 CookieSecret => $cooks,
610 Params => $r->chain_params() })
612 $r->_db_record_login_ok($parmh,$username);
613 return ({ Kind => 'REDIRECT-LOGGEDIN',
614 Message => $r->_gt("Logging in..."),
615 CookieSecret => $cooks,
616 Params => $r->chain_params() });
621 die if $parmt eq 't';
623 if ($cookt eq 'y' && $parmt eq 'y' && $cookh ne $parmh) {
624 $r->_db_revoke($parmh) if $meth eq 'POST';
629 die unless !$cookt || $cookt eq 'n';
630 die unless !$parmt || $parmt eq 'n' || $parmt eq 'y';
631 my $news = $r->_fresh_secret();
632 if ($meth eq 'GET') {
633 return ({ Kind => 'LOGIN-INCOMINGLINK',
634 Message => $r->_gt("You need to log in."),
635 CookieSecret => $news,
636 Params => $r->chain_params() });
638 $r->_db_revoke($parmh);
639 return ({ Kind => 'LOGIN-FRESH',
640 Message => $r->_gt("You need to log in."),
641 CookieSecret => $news,
646 if (!$r->{S}{promise_check_mutate}) {
647 if ($meth ne 'POST') {
648 return ({ Kind => 'MAINPAGEONLY',
649 Message => $r->_gt('Entering via cross-site link.'),
650 CookieSecret => $cooks,
652 # NB caller must then ignore params & path!
653 # if this is too hard they can spit out a small form
654 # with a "click to continue"
658 die unless $cookt eq 'y';
659 unless ($r->{S}{promise_check_mutate} && $meth eq 'GET') {
660 die unless $parmt eq 'y';
661 die unless $cookh eq $parmh;
663 $r->{AssocSecret} = $cooks;
664 $r->{UserOK} = $cooku;
665 #print STDERR "C-D-C OK\n";
669 sub chain_params ($) {
671 my %p = %{ $r->_ch('get_params') };
672 foreach my $pncn (keys %{ $r->{S} }) {
674 if ($pncn =~ m/_param_name$/) {
675 my $name = $r->{S}{$pncn};
676 die "$pncn ?" if ref $name;
678 } elsif ($pncn =~ m/_param_names$/) {
679 $names = $r->{S}{$pncn};
683 foreach my $name (@$names) {
687 my $dummy_prefix = $r->{S}{dummy_param_name_prefix};
688 foreach my $name (grep /^$dummy_prefix/, keys %p) {
691 die if exists $p{''};
692 $p{''} = [ $r->_ch('get_path_info') ];
698 # returns ($t,$username)
699 # where $t is one of "t" "y" "n", or "" (for -)
700 # either $s must be undef, or $h eq $r->hash($s)
702 #print STDERR "_identify\n";
703 return '' unless defined $h && length $h;
704 #print STDERR "_identify h=$h s=".(defined $s ? $s : '<undef>')."\n";
708 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
709 " WHERE last < ?", {},
710 time - $r->{S}{login_timeout});
712 my $row = $dbh->selectrow_arrayref("SELECT username, last".
713 " FROM $r->{S}{assocdb_table}".
714 " WHERE assochash = ?", {}, $h);
716 #print STDERR "_identify h=$h s=$s YES @$row\n";
717 my ($nusername, $nlast) = @$row;
718 return ('y', $nusername);
721 # Well, it's not in the database. But maybe it's a hash of a
724 return 'n' unless defined $s;
726 my ($keyt, $signature, $message, $noncet, $nonce) =
727 $s =~ m/^(\d+)\.(\w+)\.((\d+)\.(\w+))$/ or die;
729 return 'n' if time > $noncet + $r->{S}{login_form_timeout};
731 #print STDERR "_identify noncet=$noncet ok\n";
733 my $keys = $r->_open_keys();
734 while (my ($rkeyt, $rkey, $line) = $r->_read_key($keys)) {
735 #print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey\n";
736 last if $rkeyt < $keyt; # too far down in the file
737 my $trysignature = $r->_hmac($rkey, $message);
738 #print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey try=$trysignature\n";
739 return 't' if $trysignature eq $signature;
742 #print STDERR "_identify NO\n";
744 $keys->error and die $!;
748 sub _db_revoke ($$) {
749 # revokes $h if it's valid; no-op if it's not
754 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
755 " WHERE assochash = ?", {}, $h);
758 sub _db_record_login_ok ($$$) {
759 my ($r,$h,$user) = @_;
762 $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
763 " (assochash, username, last) VALUES (?,?,?)", {},
767 sub check_divert ($) {
769 if (exists $r->{Divert}) {
773 $r->{Divert} = $r->_db_transaction(sub { $r->_check_divert_core(); });
775 $r->_debug(Data::Dumper->Dump([$r->{Divert}],[qw(divert)]));
781 die "unchecked" unless exists $r->{Divert};
785 sub get_username ($) {
787 my $divert = $r->get_divert();
788 return undef if $divert;
792 sub url_with_query_params ($$) {
793 my ($r, $params) = @_;
794 #print STDERR "PARAMS ",Dumper($params);
795 my $uri = URI->new($r->_ch('get_url'));
796 $uri->path($uri->path() . $params->{''}[0]) if $params->{''};
797 $uri->query_form(flatten_params($params));
798 return $uri->as_string();
801 sub _cgi_header_args ($$@) {
802 my ($r, $cookie, @ha) = @_;
803 unshift @ha, qw(-type text/html);
804 push @ha, (-cookie => $cookie) if defined $cookie;
805 #print STDERR "_cgi_header_args ",join('|',@ha),".\n";
812 my ($divert) = $r->check_divert();
813 return 1 if !$divert;
815 my $handled = $r->_ch('handle_divert',$divert);
816 return 0 if $handled;
818 my $kind = $divert->{Kind};
819 my $cookiesecret = $divert->{CookieSecret};
820 my $params = $divert->{Params};
821 my $cookie = $r->construct_cookie($cookiesecret);
823 if ($kind =~ m/^REDIRECT-/) {
824 # for redirects, we honour stored NextParams and SetCookie,
825 # as we would for non-divert
826 if ($kind eq 'REDIRECT-LOGGEDOUT') {
827 $params->{$r->{S}{loggedout_param_names}[0]} = [ 1 ];
828 } elsif ($kind eq 'REDIRECT-LOGOUT') {
829 $params->{$r->{S}{logout_param_names}[0]} = [ 1 ];
830 } elsif ($kind =~ m/REDIRECT-(?:LOGGEDIN|HTTPS)/) {
834 my $new_url = $r->url_with_query_params($params);
835 if ($kind eq 'REDIRECT-HTTPS') {
836 my $uri = URI->new($new_url);
837 die unless $uri->scheme eq 'http';
838 $uri->scheme('https');
839 $new_url = $uri->as_string();
841 $r->_ch('do_redirect',$new_url, $cookie);
845 if (defined $cookiesecret) {
846 $params->{$r->{S}{assoc_param_name}} = [ $r->hash($cookiesecret) ];
850 if ($kind =~ m/^LOGIN-/) {
851 $title = $r->_gt('Login');
852 push @body, $divert->{Message};
853 push @body, $r->_ch('gen_login_form', $params);
854 } elsif ($kind =~ m/^SMALLPAGE-/) {
855 $title = $r->_gt('Not logged in');
856 push @body, $divert->{Message};
857 push @body, $r->_ch('gen_login_link', $params);
858 } elsif ($kind =~ m/^MAINPAGEONLY$/) {
859 $title = $r->_gt('Entering secure site.');
860 push @body, $divert->{Message};
861 push @body, $r->_ch('gen_postmainpage_form', $params);
866 $r->_print($r->{Cgi}->header($r->_cgi_header_args($cookie)),
867 $r->_ch('gen_start_html',$title),
869 $r->_ch('gen_footer_html'),
870 $r->_ch('gen_end_html'))));
875 my ($r, $bytes) = @_;
877 my $rsf = $v->{RandomHandle};
878 my $rsp = $r->{S}{random_source};
880 $v->{RandomHandle} = $rsf = new IO::File $rsp, '<' or die "$rsp $!";
881 #print STDERR "RH $rsf\n";
885 read($rsf,$bin,$bytes) == $bytes or die "$rsp $!";
886 my $out = unpack "H*", $bin;
887 #print STDERR "_random out $out\n";
891 sub _random_key ($) {
893 #print STDERR "_random_key\n";
894 my $bytes = ($r->{S}{secretbits} + 7) >> 3;
895 return $r->_random($bytes);
900 # returns $gen_time_t, $key_value_in_hex, $complete_line
902 my ($gen, $k) = m/^(\d+) (\S+)$/ or die "$_ ?";
903 my $age = time - $gen;
904 next if $age > $r->{S}{key_rollover} &&
905 $age > $r->{S}{login_form_timeout}*2;
906 return ($gen, $k, $_);
913 my $spath = $r->_get_path('keys');
915 #print STDERR "_open_keys\n";
916 my $keys = new IO::File $spath, 'r+';
918 #print STDERR "_open_keys open\n";
919 stat $keys or die $!; # NB must not disturb stat _
920 my $size = (stat _)[7];
921 my $age = time - (stat _)[9];
922 #print STDERR "_open_keys open size=$size age=$age\n";
924 if $size && $age <= $r->{S}{key_rollover} / 2;
925 #print STDERR "_open_keys open bad\n";
927 # file doesn't exist, or is empty or too old
929 #print STDERR "_open_keys closed\n";
930 die "$spath $!" unless $!==&ENOENT;
931 # doesn't exist, so create it just so we can lock it
932 $keys = new IO::File $spath, 'a+';
933 die "$keys $!" unless $keys;
934 stat $keys or die $!; # NB must not disturb stat _
935 my $size = (stat _)[7];
936 #print STDERR "_open_keys created size=$size\n";
937 next if $size; # oh someone else has done it, reopen and read it
939 # file now exists is empty or too old, we must try to replace it
940 my $our_inum = (stat _)[1]; # last use of that stat _
941 flock $keys, LOCK_EX or die "$spath $!";
942 stat $spath or die "$spath $!";
943 my $path_inum = (stat _)[1];
944 #print STDERR "_open_keys locked our=$our_inum path=$path_inum\n";
945 next if $our_inum != $path_inum; # someone else has done it
946 # We now hold the lock!
947 #print STDERR "_open_keys creating\n";
948 my $newkeys = new IO::Handle;
949 sysopen $newkeys, "$spath.new", O_CREAT|O_TRUNC|O_WRONLY, 0600
950 or die "$spath.new $!";
951 # we add the new key to the front which means it's always sorted
952 print $newkeys time, ' ', $r->_random_key(), "\n" or die $!;
953 while (my ($gen,$key,$line) = $r->_read_key($keys)) {
954 #print STDERR "_open_keys copy1\n";
955 print $newkeys, $line or die $!;
957 $keys->error and die $!;
958 close $newkeys or die "$spath.new $!";
959 rename "$spath.new", "$spath" or die "$spath: $!";
960 #print STDERR "_open_keys installed\n";
961 # that rename effective unlocks, since it makes the name refer
962 # to the new file which we haven't locked
963 # we go round again opening the file at the beginning
964 # so that our caller gets a fresh handle onto the existing key file
968 sub _fresh_secret ($) {
970 #print STDERR "_fresh_secret\n";
972 my $keys = $r->_open_keys();
973 my ($keyt, $key) = $r->_read_key($keys);
974 die unless defined $keyt;
976 my $nonce = $r->_random_key();
978 my $message = "$noncet.$nonce";
980 my $signature = $r->_hmac($key, $message);
981 my $secret = "$keyt.$signature.$message";
982 #print STDERR "FRESH $secret\n";
987 my ($r, $keyhex, $message) = @_;
988 my $keybin = pack "H*", $keyhex;
989 my $alg = $r->{S}{hash_algorithm};
990 #print STDERR "hmac $alg\n";
991 my $base = new Digest $alg;
992 #print STDERR "hmac $alg $base\n";
993 my $digest = new Digest::HMAC $keybin, $base;
994 #print STDERR "hmac $alg $base $digest\n";
995 $digest->add($message);
996 return $digest->hexdigest();
1000 my ($r, $message) = @_;
1001 my $alg = $r->{S}{hash_algorithm};
1002 #print STDERR "hash $alg\n";
1003 my $digest = new Digest $alg;
1004 $digest->add($message);
1005 return $digest->hexdigest();
1008 sub _assert_checked ($) {
1010 die "unchecked" unless exists $r->{Divert};
1015 my $meth = $r->_ch('get_method');
1016 return $meth eq 'POST';
1019 sub _must_be_post ($) {
1021 my $meth = $r->_ch('get_method');
1022 die "mutating non-POST" if $meth ne 'POST';
1025 sub check_mutate ($) {
1027 $r->_assert_checked();
1028 die if $r->{Divert};
1029 $r->_must_be_post();
1034 $r->_assert_checked();
1035 die if $r->{Divert};
1036 return $r->_is_post();
1039 #---------- output ----------
1041 sub secret_cookie_val ($) {
1043 $r->_assert_checked();
1044 return defined $r->{AssocSecret} ? $r->{AssocSecret} : '';
1047 sub secret_hidden_val ($) {
1049 $r->_assert_checked();
1050 return defined $r->{AssocSecret} ? $r->hash($r->{AssocSecret}) : '';
1053 sub secret_hidden_html ($) {
1055 return $r->{Cgi}->hidden(-name => $r->{S}{assoc_param_name},
1056 -default => $r->secret_hidden_val());
1059 sub secret_cookie ($) {
1061 my $secret = $r->secret_cookie_val();
1062 return undef if !defined $secret;
1063 #print STDERR "SC\n";
1064 my $cookv = $r->construct_cookie($secret);
1065 #print STDERR "SC=$cookv\n";
1075 CGI::Auth::Flexible - web authentication optionally using cookies
1079 my $verifier = CGI::Auth::Flexible->new_verifier(setting => value,...);
1080 my $authreq = $verifier->new_request($cgi_request_object);
1082 my $authreq = CGI::Auth::Flexible->new_request($cgi_request_object,
1083 setting => value,...);
1085 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
1087 $authreq->check_ok() or return;
1090 $authreq->check_mutate();
1093 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
1095 my $divert_kind = $authreq->check_divert();
1097 if ($divert_kind eq 'LOGGEDOUT') {
1098 print "goodbye you are now logged out" and quit
1099 } elsif ($divert_kind eq 'NOCOOKIES') {
1100 print "you need cookies" and quit
1106 $authreq->check_mutate();