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(@default_db_setup_stmts);
40 use CGI qw/escapeHTML/;
54 #---------- public utilities ----------
56 sub flatten_params ($) {
59 foreach my $k (keys %$p) {
61 foreach my $v (@{ $p->{$k} }) {
68 #---------- default callbacks ----------
70 sub has_a_param ($$) {
72 foreach my $pn (@{ $r->{S}{$cn} }) {
73 return 1 if $r->_ch('get_param',$pn);
81 my $vars = $c->Vars();
83 foreach my $name (keys %$vars) {
84 $p{$name} = [ split "\0", $vars->{$name} ];
89 sub get_cookie_domain ($$$) {
91 my $uri = new URI $r->_ch('get_url');
95 sub login_ok_password ($$) {
97 my $username_params = $r->{S}{username_param_names};
98 my $username = $r->_ch('get_param',$username_params->[0]);
99 my $password = $r->_rp('password_param_name');
100 my $error = $r->_ch('username_password_error', $username, $password);
101 return defined($error) ? (undef,$error) : ($username,undef);
104 sub do_redirect_cgi ($$$$) {
105 my ($c, $r, $new_url, $cookie) = @_;
106 $r->_print($c->header($r->_cgi_header_args($cookie,
107 -status => '303 See other',
108 -location => $new_url)),
109 $r->_ch('gen_start_html',$r->_gt('Redirection')),
110 '<a href="'.escapeHTML($new_url).'">',
111 $r->_gt("If you aren't redirected, click to continue."),
113 $r->_ch('gen_end_html'));
116 sub gen_some_form ($$) {
117 my ($r, $params, $bodyfn) = @_;
118 # Calls $bodyfn->($c,$r) which returns @formbits
122 $pathinfo .= $params->{''}[0] if $params->{''};
123 push @form, ('<form method="POST" action="'.
124 escapeHTML($r->_ch('get_url').$pathinfo).'">');
125 push @form, $bodyfn->($c,$r);
126 foreach my $n (keys %$params) {
128 foreach my $val (@{ $params->{$n} }) {
129 push @form, ('<input type="hidden"'.
130 ' name="'.escapeHTML($n).'"'.
131 ' value="'.escapeHTML($val).'">');
134 push @form, ('</form>');
135 return join "\n", @form;
138 sub gen_plain_login_form ($$) {
139 my ($c,$r, $params) = @_;
140 return $r->gen_some_form($params, sub {
142 push @form, ('<table>');
143 my $sz = 'size="'.$r->{S}{form_entry_size}.'"';
144 foreach my $up (@{ $r->{S}{username_param_names}}) {
145 push @form, ('<tr><td>',$r->_gt(ucfirst $up),'</td>',
146 '<td><input type="text" '.$sz.
147 ' name='.$up.'></td></tr>');
149 push @form, ('<tr><td>'.$r->_gt('Password').'</td>',
150 '<td><input type="password" '.$sz.
151 ' name="'.$r->{S}{password_param_name}.'"></td></tr>');
152 push @form, ('<tr><td colspan="2">',
153 '<input type="submit"'.
154 ' name="'.$r->{S}{dummy_param_name_prefix}.'login"'.
155 ' value="'.$r->_gt('Login').'"></td></tr>',
161 sub gen_postmainpage_form ($$$) {
162 my ($c,$r, $params) = @_;
163 return $r->gen_some_form($params, sub {
165 push @form, ('<input type="submit"',
166 ' name="'.$r->{S}{dummy_param_name_prefix}.'submit"'.
167 ' value="'.$r->_gt('Continue').'">');
172 sub gen_plain_login_link ($$) {
173 my ($c,$r, $params) = @_;
174 my $url = $r->url_with_query_params($params);
175 return ('<a href="'.escapeHTML($url).'">'.
176 $r->_gt('Log in again to continue.').
180 sub gen_srcdump_link_html ($$$$) {
181 my ($c,$r,$anchor,$specval) = @_;
182 my %params = ($r->{S}{srcdump_param_name} => [ $specval ]);
184 escapeHTML($r->url_with_query_params(\%params,'SRCDUMP')).
187 sub gen_plain_licence_link_html ($$) {
189 gen_srcdump_link_html($c,$r, 'GNU Affero GPL', 'licence');
191 sub gen_plain_source_link_html ($$) {
193 gen_srcdump_link_html($c,$r, 'Source available', 'source');
196 sub gen_plain_footer_html ($$) {
198 return ('<hr><address>',
199 ("Powered by Free / Libre / Open Source Software".
200 " according to the ".$r->_ch('gen_licence_link_html')."."),
201 $r->_ch('gen_source_link_html').".",
205 our @default_db_setup_stmts =
206 ("CREATE TABLE $v->{S}{db_prefix}_assocs (".
207 " assochash VARCHAR PRIMARY KEY,".
208 " username VARCHAR NOT NULL,".
209 " last INTEGER NOT NULL".
212 "CREATE INDEX $v->{S}{db_prefix}_assocs_timeout_index".
213 " ON $v->{S}{db_prefix}_assocs".
217 #---------- licence and source code ----------
219 sub srcdump_dump ($$$) {
220 my ($c,$r, $thing) = @_;
221 die if $thing =~ m/\W/ || $thing !~ m/\w/;
222 my $path = $r->_get_path('srcdump');
223 my $ctf = new IO::File "$path/$thing.ctype", 'r'
224 or die "$path/$thing.ctype $!";
226 chomp $ct or die "$path/$thing ?";
227 $ctf->close or die "$path/$thing $!";
228 my $df = new IO::File "$path/$thing.data", 'r'
229 or die "$path/$thing.data $!";
230 $r->_ch('dump', $ct, $df);
233 sub dump_plain ($$$$) {
234 my ($c, $r, $ct, $df) = @_;
235 $r->_print($c->header('-type' => $ct));
238 my $got = read $df, $buffer, 65536;
239 die $! unless defined $got;
245 sub srcdump_process_item ($$$$$$) {
246 my ($c, $v, $dumpdir, $item, $outfn, $needlicence, $dirsdone) = @_;
247 if ($v->_ch('srcdump_system_dir', $item)) {
248 $outfn->("srcdump_process_item: srcdump_system_dir, skipping $item");
254 $upwards =~ s#/+\.$##;
255 last unless $upwards =~ m#[^/]#;
256 foreach my $try (@{ $v->{S}{srcdump_vcs_dirs} }) {
257 #print STDERR "TRY $item $upwards $try\n";
258 if (!stat "$upwards/$try") {
259 $!==&ENOENT or $!==&ENOTDIR or die "check $upwards/$try $!";
262 #print STDERR "VCS $item $upwards $try\n";
263 if ($dirsdone->{$upwards}++) {
264 $outfn->("srcdump_process_item: did $upwards,".
268 #print STDERR "VCS $item $upwards $try GO\n";
269 $try =~ m/\w+/ or die;
270 return $v->_ch('srcdump_byvcs', $dumpdir, $upwards, $outfn, lc $&);
272 $upwards =~ s#/*[^/]+$##;
274 return $v->_ch('srcdump_novcs', $dumpdir, $item, $outfn);
277 sub srcdump_novcs ($$$$$) {
278 my ($c, $v, $dumpdir, $item, $outfn) = @_;
279 stat $item or die "$item $!";
281 my $script = 'find -type f -perm +004';
282 foreach my $excl (@{ $v->{S}{srcdump_excludes} }) {
283 $script .= " \\! -name '$excl'";
285 $script .= " -print0";
286 return srcdump_dir_cpio($c,$v,$dumpdir,$item,$outfn,'novcs',$script);
288 return srcdump_file($c,$v,$dumpdir,$item,$outfn);
290 die "$item not file or directory";
294 sub srcdump_byvcs ($$$$$$) {
295 my ($c, $v, $dumpdir, $dir, $outfn, $vcs) = @_;
296 #print STDERR "BYVCS GIT $dir\n";
297 my $script = $v->{S}{"srcdump_vcsscript"}{$vcs};
298 die "no script for vcs $vcs" unless defined $script;
299 return srcdump_dir_cpio($c,$v,$dumpdir,$dir,$outfn,$vcs,$script);
302 sub srcdump_file ($$$$) {
303 my ($c,$v,$dumpdir,$file,$outfn) = @_;
304 my $outfile = $outfn->("srcdump_file saved $file", "src");
305 copy($file,$outfile) or die "$file $outfile $!";
308 sub srcdump_dir_cpio ($$$$$$$) {
309 my ($c,$v,$dumpdir,$dir,$outfn,$how,$script) = @_;
310 my $outfile = $outfn->("srcdump_dir_cpio $how saved $dir", "tar");
311 #print STDERR "CPIO $dir >$script<\n";
313 defined $pid or die $!;
315 $SIG{__DIE__} = sub {
316 print STDERR "CGI::Auth::Flexible srcdump error: $@\n";
319 open STDOUT, ">", $outfile or die "$outfile $!";
320 chdir $dir or die "chdir $dir: $!";
321 exec '/bin/bash','-ec',"
326 cpio -Hustar -o --quiet -0 -R 1000:1000 || \
327 cpio -Hustar -o --quiet -0
332 $!=0; (waitpid $pid, 0) == $pid or die "$!";
333 die "$dir ($how $script) $outfile $?" if $?;
336 sub srcdump_dirscan_prepare ($$) {
338 my $dumpdir = $v->_get_path('srcdump');
339 mkdir $dumpdir or $!==&EEXIST or die "mkdir $dumpdir $!";
340 my $lockf = new IO::File "$dumpdir/generate.lock", 'w+'
341 or die "$dumpdir/generate.lock $!";
342 flock $lockf, LOCK_EX or die "$dumpdir/generate.lock $!";
343 my $needlicence = "$dumpdir/licence.tmp";
344 unlink $needlicence or $!==&ENOENT or die "rm $needlicence $!";
345 if (defined $v->{S}{srcdump_licence_path}) {
346 copy($v->{S}{srcdump_licence_path}, $needlicence)
347 or die "$v->{S}{srcdump_licence_path} $!";
348 $needlicence = undef;
350 unlink <"$dumpdir/s.[a-z][a-z][a-z].*">;
351 my @srcfiles = qw(licence.data manifest.txt);
352 my $srcoutcounter = 'aaa';
354 my $reportfh = new IO::File "$dumpdir/manifest.txt", 'w' or die $!;
356 my ($message, $extension) = @_;
357 if (defined $extension) {
358 my $leaf = "s.$srcoutcounter.$extension";
360 push @srcfiles, $leaf;
361 print $reportfh "$leaf: $message\n" or die $!;
362 return "$dumpdir/$leaf";
364 print $reportfh "none: $message\n" or die $!;
369 foreach my $item ($v->_ch('srcdump_listitems')) {
370 if ($item eq '.' && $v->{S}{srcdump_filter_cwd}) {
371 my @bad = grep { !m#^/# } values %INC;
372 die "filtering . from srcdump items and \@INC but already".
373 " included @bad " if @bad;
374 @INC = grep { $_ ne '.' } @INC;
377 if (!lstat "$item") {
378 die "stat $item $!" unless $!==&ENOENT;
379 $outfn->("srcdump_dirscan_prepare stat ENOENT, skipping $item");
383 $item = realpath($item);
384 if (!defined $item) {
385 die "realpath $item $!" unless $!==&ENOENT;
386 $outfn->("srcdump_dirscan_prepare realpath ENOENT,".
390 if (defined $needlicence) {
391 foreach my $try (@{ $v->{S}{srcdump_licence_files} }) {
392 last if copy("$item/$try", $needlicence);
393 $!==&ENOENT or $!==&ENOTDIR or die "copy $item/$try $!";
396 $v->_ch('srcdump_process_item', $dumpdir, $item,
397 $outfn, \$needlicence, \%dirsdone);
400 close $reportfh or die $!;
401 srcdump_install($c,$v, $dumpdir, 'licence', 'text/plain');
403 my @cmd = (qw(tar -zvvcf), "$dumpdir/source.tmp",
404 "-C", $dumpdir, qw( --), @srcfiles);
405 my $r = system(@cmd);
407 print STDERR "CGI::Auth::Flexible tar failed ($r $!) @cmd\n";
410 die "licence file not found" unless defined $needlicence;
411 srcdump_install($c,$v, $dumpdir, 'source', 'application/octet-stream');
412 close $lockf or die $!;
415 sub srcdump_install ($$$$$) {
416 my ($c,$v, $dumpdir, $which, $ctype) = @_;
417 rename "$dumpdir/$which.tmp", "$dumpdir/$which.data"
418 or die "$dumpdir/$which.data $!";
419 my $ctf = new IO::File "$dumpdir/$which.tmp", 'w'
420 or die "$dumpdir/$which.tmp $!";
421 print $ctf $ctype, "\n" or die $!;
422 close $ctf or die $!;
423 rename "$dumpdir/$which.tmp", "$dumpdir/$which.ctype"
424 or die "$dumpdir/$which.ctype $!";
427 #---------- verifier object methods ----------
434 assocdb_dbh => undef, # must have AutoCommit=0, RaiseError=1
435 assocdb_path => 'caf-assocs.db',
436 keys_path => 'caf-keys',
437 srcdump_path => 'caf-srcdump',
438 assocdb_dsn => undef,
440 assocdb_password => '',
442 assocdb_setup_stmts => [@_default_db_setup_statements],
443 random_source => '/dev/urandom',
444 secretbits => 128, # bits
445 hash_algorithm => "SHA-256",
446 login_timeout => 86400, # seconds
447 login_form_timeout => 3600, # seconds
448 key_rollover => 86400, # seconds
449 assoc_param_name => 'caf_assochash',
450 dummy_param_name_prefix => 'caf__',
451 cookie_name => "caf_assocsecret",
452 password_param_name => 'password',
453 srcdump_param_name => 'caf_srcdump',
454 username_param_names => [qw(username)],
455 form_entry_size => 60,
456 logout_param_names => [qw(caf_logout)],
457 loggedout_param_names => [qw(caf_loggedout)],
458 promise_check_mutate => 0,
459 get_param => sub { $_[0]->param($_[2]) },
460 get_params => sub { $_[1]->get_params() },
461 get_path_info => sub { $_[0]->path_info() },
462 get_cookie => sub { $_[0]->cookie($_[1]->{S}{cookie_name}) },
463 get_method => sub { $_[0]->request_method() },
464 is_https => sub { !!$_[0]->https() },
465 get_url => sub { $_[0]->url(); },
466 is_login => sub { defined $_[1]->_rp('password_param_name') },
467 login_ok => \&login_ok_password,
468 username_password_error => sub { die },
469 is_logout => sub { $_[1]->has_a_param('logout_param_names') },
470 is_loggedout => sub { $_[1]->has_a_param('loggedout_param_names') },
471 handle_divert => sub { return 0 },
472 do_redirect => \&do_redirect_cgi, # this hook is allowed to throw
474 get_cookie_domain => \&get_cookie_domain,
476 gen_start_html => sub { $_[0]->start_html($_[2]); },
477 gen_footer_html => \&gen_plain_footer_html,
478 gen_licence_link_html => \&gen_plain_licence_link_html,
479 gen_source_link_html => \&gen_plain_source_link_html,
480 gen_end_html => sub { $_[0]->end_html(); },
481 gen_login_form => \&gen_plain_login_form,
482 gen_login_link => \&gen_plain_login_link,
483 gen_postmainpage_form => \&gen_postmainpage_form,
484 srcdump_dump => \&srcdump_dump,
485 srcdump_prepare => \&srcdump_dirscan_prepare,
486 srcdump_licence_path => undef,
487 srcdump_licence_files => [qw(AGPLv3 CGI/Auth/Flexible/AGPLv3)],
488 srcdump_listitems => sub { (@INC, $ENV{'SCRIPT_FILENAME'}, $0); },
489 srcdump_filter_cwd => 1,
490 srcdump_system_dir => sub {
491 $_[2] =~ m#^/etc/|^/usr/(?!local/)(?!lib/cgi)#;
493 srcdump_process_item => \&srcdump_process_item,
494 srcdump_vcs_dirs => [qw(.git .hg .bzr .svn)],
495 srcdump_vcsscript => [git => "
497 git ls-files -z --others --exclude-from=.gitignore
500 srcdump_byvcs => \&srcdump_byvcs,
501 srcdump_novcs => \&srcdump_novcs,
502 srcdump_excludes => [qw(*~ *.bak *.tmp), '#*#'],
503 dump => \&dump_plain,
504 gettext => sub { gettext($_[2]); },
505 print => sub { print $_[2] or die $!; },
506 debug => sub { }, # like print; msgs contain trailing \n
511 while (($k,$v,@_) = @_) {
512 die "unknown setting $k" unless
513 $k =~ m/^promise_/ or
514 exists $verifier->{S}{$k};
515 $verifier->{S}{$k} = $v;
517 bless $verifier, $class;
518 $verifier->_dbopen();
519 $verifier->_ch('srcdump_prepare');
523 sub _db_setup_do ($$) {
527 $v->_db_transaction(sub {
528 local ($dbh->{PrintError}) = 0;
539 $dbh = $v->{S}{assocdb_dbh};
541 die if $dbh->{AutoCommit};
542 die unless $dbh->{RaiseError};
544 $v->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=".$v->_get_path('assocdb');
545 my $dsn = $v->{S}{assocdb_dsn};
548 $dbh = DBI->connect($dsn, $v->{S}{assocdb_user},
549 $v->{S}{assocdb_password}, {
552 ShowErrorStatement => 1,
555 die "$dsn $! ?" unless $dbh;
559 foreach my $stmt (@default_db_setup_stmts) {
560 $v->_db_setup_do($stmt);
572 sub _db_transaction ($$) {
577 #print STDERR "DT entry\n";
579 #print STDERR "DT loop\n";
582 #print STDERR "DT fn ok\n";
585 #print STDERR "DT fn error\n";
586 { local ($@); $dbh->rollback(); }
587 #print STDERR "DT fn throwing\n";
590 #print STDERR "DT fn eval ok\n";
593 #print STDERR "DT commit ok\n";
596 #print STDERR "DT commit eval ok ",Dumper($rv);
599 #print STDERR "DT commit throw?\n";
600 die $@ if !--$retries;
601 #print STDERR "DT loop again\n";
605 #---------- request object methods ----------
608 my ($classbase, $cgi, @extra) = @_;
609 if (!ref $classbase) {
610 $classbase = $classbase->new_verifier(@extra);
616 S => $classbase->{S},
617 Dbh => $classbase->{Dbh},
620 bless $r, ref $classbase;
623 sub _ch ($$@) { # calls an application hook
624 my ($r,$methname, @args) = @_;
625 my $methfunc = $r->{S}{$methname};
626 die "$methname ?" unless $methfunc;
627 return $methfunc->($r->{Cgi}, $r, @args);
632 my $pn = $r->{S}{$pnvb};
633 my $p = scalar $r->_ch('get_param',$pn)
638 $r->_ch('debug',@args);
642 my ($r,$keybase) = @_;
643 my $leaf = $r->{S}{"${keybase}_path"};
644 return $r->_absify_path($leaf);
647 sub _absify_path ($$) {
649 return $leaf if $leaf =~ m,^/,;
650 my $dir = $v->{S}{dir};
651 die "relying on cwd by default ?! set dir" unless defined $dir;
655 sub _gt ($$) { my ($r, $t) = @_; return $r->_ch('gettext',$t); }
656 sub _print ($$) { my ($r, @t) = @_; return $r->_ch('print', join '', @t); }
658 sub construct_cookie ($$$) {
659 my ($r, $cooks) = @_;
660 return undef unless $cooks;
662 my @ca = (-name => $r->{S}{cookie_name},
664 -path => $r->{S}{cookie_path},
665 -domain => $r->_ch('get_cookie_domain'),
666 -expires => '+'.$r->{S}{login_timeout}.'s',
667 -secure => $r->{S}{encrypted_only});
668 my $cookie = $c->cookie(@ca);
669 #print STDERR "CC $r $c $cooks $cookie (@ca).\n";
673 # pages/param-sets are
674 # n normal non-mutating page
675 # r retrieval of information for JS etc., non-mutating
677 # u update of information by JS etc., mutating
680 # O "you have just logged out" page load
683 # - no value supplied (represented in code as $cookt='')
684 # n, nN value not in our db
685 # t, tN temporary value (in our db, no logged in user yet)
686 # y, yN value corresponds to logged-in user
687 # and, aggregated conditions:
688 # a, aN anything including -
690 # if N differs the case applies only when the two values differ
691 # (eg, a1 y2 does not apply when the logged-in value is supplied twice)
693 # "stale session" means request originates from a page from a login
694 # session which has been revoked (eg by logout); "cleared session"
695 # means request originates from a browser which has a different (or
698 # Case analysis, cookie mode, app promises re mutate:
699 # cook parm meth form
701 # any - POST nrmuoi bug or attack, fail
702 # any - GET rmuoi bug or attack, fail
703 # any any GET muoi bug or attack, fail
704 # any t any nrmu bug or attack, fail
706 # - - GET O "just logged out" page
707 # (any other) O bug or attack, fail
709 # a1 a2 POST o logout
710 # if a1 is valid, revoke it
711 # if a2 is valid, revoke it
713 # redirect to "just logged out" page
714 # (which contains link to login form)
716 # - t POST i complain about cookies being disabled
717 # (with link to login form)
719 # t1 t1 POST i login (or switch user)
721 # show new login form
723 # upgrade t1 to y1 in our db (setting username)
724 # redirect to GET of remaining params
726 # y1 a2 POST i complain about stale login form
728 # show new login form
730 # (other) POST i complain about stale login form
731 # show new login form
733 # t1 a2 ANY nrmu treat as - a2 ANY
735 # y - GET n cross-site link
738 # y y GET nr fine, show page or send data
739 # y y POST nrmu mutation is OK, do operation
741 # y1 y2 GET nr request from stale page
742 # do not revoke y2 as not RESTful
745 # y1 y2 POST nrmu request from stale page
749 # y n GET n intra-site link from stale page,
750 # treat as cross-site link, show data
752 # y n POST n m intra-site form submission from stale page
753 # show "session interrupted"
754 # with link to main data page
756 # y n GET r intra-site request from stale page
759 # y n POST r u intra-site request from stale page
762 # -/n y2 GET nr intra-site link from cleared session
763 # do not revoke y2 as not RESTful
766 # -/n y2 POST nrmu request from cleared session
768 # treat as -/n n POST
770 # -/n -/n GET n cross-site link but user not logged in
771 # show login form with redirect to orig params
772 # generate fresh cookie
774 # -/n n GET rmu user not logged in
777 # -/n n POST n m user not logged in
780 # -/n n POST r u user not logged in
783 sub _check_divert_core ($) {
786 my $srcdump = $r->_rp('srcdump_param_name');
788 die if $srcdump =~ m/\W/;
789 return ({ Kind => 'SRCDUMP-'.uc $srcdump,
791 CookieSecret => undef,
795 my $cooks = $r->_ch('get_cookie');
797 if ($r->{S}{encrypted_only} && !$r->_ch('is_https')) {
798 return ({ Kind => 'REDIRECT-HTTPS',
799 Message => $r->_gt("Redirecting to secure server..."),
800 CookieSecret => undef,
804 my $meth = $r->_ch('get_method');
805 my $parmh = $r->_rp('assoc_param_name');
806 my $cookh = defined $cooks ? $r->hash($cooks) : undef;
808 my ($cookt,$cooku) = $r->_identify($cookh, $cooks);
809 my $parms = (defined $cooks && defined $parmh && $parmh eq $cookh)
811 my ($parmt) = $r->_identify($parmh, $parms);
813 $r->_debug("_c_d_c cookt=$cookt parmt=$parmt\n");
815 if ($r->_ch('is_logout')) {
818 $r->_db_revoke($cookh);
819 $r->_db_revoke($parmh);
820 return ({ Kind => 'REDIRECT-LOGGEDOUT',
821 Message => $r->_gt("Logging out..."),
825 if ($r->_ch('is_loggedout')) {
826 die unless $meth eq 'GET';
827 die if $cookt eq 'y';
829 return ({ Kind => 'SMALLPAGE-LOGGEDOUT',
830 Message => $r->_gt("You have been logged out."),
834 if ($r->_ch('is_login')) {
837 if (!$cookt && $parmt eq 'n') {
838 return ({ Kind => 'SMALLPAGE-NOCOOKIE',
839 Message => $r->_gt("You do not seem to have cookies".
840 " enabled. You must enable cookies".
841 " as we use them for login."),
842 CookieSecret => $r->_fresh_secret(),
843 Params => $r->_chain_params() })
845 if (!$cookt || $cookt eq 'n' || $cookh ne $parmh) {
846 $r->_db_revoke($cookh);
847 return ({ Kind => 'LOGIN-STALE',
848 Message => $r->_gt("Stale session;".
849 " you need to log in again."),
850 CookieSecret => $r->_fresh_secret(),
853 die unless $parmt eq 't' || $parmt eq 'y';
854 my ($username, $login_errormessage) = $r->_ch('login_ok');
855 unless (defined $username && length $username) {
856 $login_errormessage = $r->_gt("Incorrect username/password.")
857 if !$login_errormessage;
858 return ({ Kind => 'LOGIN-BAD',
859 Message => $login_errormessage,
860 CookieSecret => $cooks,
861 Params => $r->_chain_params() })
863 $r->_db_record_login_ok($parmh,$username);
864 return ({ Kind => 'REDIRECT-LOGGEDIN',
865 Message => $r->_gt("Logging in..."),
866 CookieSecret => $cooks,
867 Params => $r->_chain_params() });
872 die if $parmt eq 't';
874 if ($cookt eq 'y' && $parmt eq 'y' && $cookh ne $parmh) {
875 $r->_db_revoke($parmh) if $meth eq 'POST';
880 die unless !$cookt || $cookt eq 'n';
881 die unless !$parmt || $parmt eq 'n' || $parmt eq 'y';
882 my $news = $r->_fresh_secret();
883 if ($meth eq 'GET') {
884 return ({ Kind => 'LOGIN-INCOMINGLINK',
885 Message => $r->_gt("You need to log in."),
886 CookieSecret => $news,
887 Params => $r->_chain_params() });
889 $r->_db_revoke($parmh);
890 return ({ Kind => 'LOGIN-FRESH',
891 Message => $r->_gt("You need to log in."),
892 CookieSecret => $news,
897 if (!$r->{S}{promise_check_mutate}) {
898 if ($meth ne 'POST') {
899 return ({ Kind => 'MAINPAGEONLY',
900 Message => $r->_gt('Entering via cross-site link.'),
901 CookieSecret => $cooks,
903 # NB caller must then ignore params & path!
904 # if this is too hard they can spit out a small form
905 # with a "click to continue"
909 die unless $cookt eq 'y';
910 unless ($r->{S}{promise_check_mutate} && $meth eq 'GET') {
911 die unless $parmt eq 'y';
912 die unless $cookh eq $parmh;
914 $r->{ParmT} = $parmt;
915 $r->{AssocSecret} = $cooks;
916 $r->{UserOK} = $cooku;
917 #print STDERR "C-D-C OK\n";
921 sub _chain_params ($) {
922 # =item C<< $authreq->_chain_params() >>
924 # Returns a hash of the "relevant" parameters to this request, in a form
925 # used by C<url_with_query_params>. This is all of the query parameters
926 # which are not related to CGI::Auth::Flexible. The PATH_INFO from the
927 # request is returned as the parameter C<< '' >>.
930 my %p = %{ $r->_ch('get_params') };
931 foreach my $pncn (keys %{ $r->{S} }) {
933 if ($pncn =~ m/_param_name$/) {
934 my $name = $r->{S}{$pncn};
935 die "$pncn ?" if ref $name;
937 } elsif ($pncn =~ m/_param_names$/) {
938 $names = $r->{S}{$pncn};
942 foreach my $name (@$names) {
946 my $dummy_prefix = $r->{S}{dummy_param_name_prefix};
947 foreach my $name (grep /^$dummy_prefix/, keys %p) {
950 die if exists $p{''};
951 $p{''} = [ $r->_ch('get_path_info') ];
957 # returns ($t,$username)
958 # where $t is one of "t" "y" "n", or "" (for -)
959 # either $s must be undef, or $h eq $r->hash($s)
961 #print STDERR "_identify\n";
962 return '' unless defined $h && length $h;
963 #print STDERR "_identify h=$h s=".(defined $s ? $s : '<undef>')."\n";
967 $dbh->do("DELETE FROM $r->{S}{db_prefix}_assocs".
968 " WHERE last < ?", {},
969 time - $r->{S}{login_timeout});
971 my $row = $dbh->selectrow_arrayref("SELECT username, last".
972 " FROM $r->{S}{db_prefix}_assocs".
973 " WHERE assochash = ?", {}, $h);
975 #print STDERR "_identify h=$h s=$s YES @$row\n";
976 my ($nusername, $nlast) = @$row;
977 return ('y', $nusername);
980 # Well, it's not in the database. But maybe it's a hash of a
983 return 'n' unless defined $s;
985 my ($keyt, $signature, $message, $noncet, $nonce) =
986 $s =~ m/^(\d+)\.(\w+)\.((\d+)\.(\w+))$/ or die;
988 return 'n' if time > $noncet + $r->{S}{login_form_timeout};
990 #print STDERR "_identify noncet=$noncet ok\n";
992 my $keys = $r->_open_keys();
993 while (my ($rkeyt, $rkey, $line) = $r->_read_key($keys)) {
994 #print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey\n";
995 last if $rkeyt < $keyt; # too far down in the file
996 my $trysignature = $r->_hmac($rkey, $message);
997 #print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey try=$trysignature\n";
998 return 't' if $trysignature eq $signature;
1001 #print STDERR "_identify NO\n";
1003 $keys->error and die $!;
1007 sub _db_revoke ($$) {
1008 # revokes $h if it's valid; no-op if it's not
1011 my $dbh = $r->{Dbh};
1013 $dbh->do("DELETE FROM $r->{S}{db_prefix}_assocs".
1014 " WHERE assochash = ?", {}, $h);
1017 sub _db_record_login_ok ($$$) {
1018 my ($r,$h,$user) = @_;
1020 my $dbh = $r->{Dbh};
1021 $dbh->do("INSERT INTO $r->{S}{db_prefix}_assocs".
1022 " (assochash, username, last) VALUES (?,?,?)", {},
1026 sub check_divert ($) {
1028 if (exists $r->{Divert}) {
1029 return $r->{Divert};
1031 my $dbh = $r->{Dbh};
1032 $r->{Divert} = $r->_db_transaction(sub { $r->_check_divert_core(); });
1034 $r->_debug(Data::Dumper->Dump([$r->{Divert}],[qw(divert)]));
1035 return $r->{Divert};
1038 sub get_divert ($) {
1040 die "unchecked" unless exists $r->{Divert};
1041 return $r->{Divert};
1044 sub get_username ($) {
1046 my $divert = $r->get_divert();
1047 return undef if $divert;
1048 return $r->{UserOK};
1051 sub url_with_query_params ($$;$) {
1052 my ($r, $params, $nonpagetype) = @_;
1053 #print STDERR "PARAMS ",Dumper($params);
1054 my $uri = URI->new($r->_ch('get_url'));
1055 $uri->path($uri->path() . $params->{''}[0]) if $params->{''};
1056 my @flatparams = flatten_params($params);
1057 if (defined $nonpagetype && $r->need_add_hidden('GET',$nonpagetype)) {
1058 push @flatparams, $r->{S}{assoc_param_name}, $r->secret_hidden_val();
1060 $uri->query_form(@flatparams);
1061 return $uri->as_string();
1064 sub _cgi_header_args ($$@) {
1065 my ($r, $cookie, @ha) = @_;
1066 unshift @ha, qw(-type text/html);
1067 push @ha, (-cookie => $cookie) if defined $cookie;
1068 #print STDERR "_cgi_header_args ",join('|',@ha),".\n";
1075 my ($divert) = $r->check_divert();
1076 return 1 if !$divert;
1078 my $handled = $r->_ch('handle_divert',$divert);
1079 return 0 if $handled;
1081 my $kind = $divert->{Kind};
1082 my $cookiesecret = $divert->{CookieSecret};
1083 my $params = $divert->{Params};
1084 my $cookie = $r->construct_cookie($cookiesecret);
1086 if ($kind =~ m/^SRCDUMP-(\w+)$/) {
1087 $r->_ch('srcdump_dump', (lc $1));
1091 if ($kind =~ m/^REDIRECT-/) {
1092 # for redirects, we honour stored Params and Cookie,
1093 # as we would for non-divert
1094 if ($kind eq 'REDIRECT-LOGGEDOUT') {
1095 $params->{$r->{S}{loggedout_param_names}[0]} = [ 1 ];
1096 } elsif ($kind eq 'REDIRECT-LOGOUT') {
1097 $params->{$r->{S}{logout_param_names}[0]} = [ 1 ];
1098 } elsif ($kind =~ m/REDIRECT-(?:LOGGEDIN|HTTPS)/) {
1102 my $new_url = $r->url_with_query_params($params);
1103 if ($kind eq 'REDIRECT-HTTPS') {
1104 my $uri = URI->new($new_url);
1105 die unless $uri->scheme eq 'http';
1106 $uri->scheme('https');
1107 $new_url = $uri->as_string();
1109 $r->_ch('do_redirect',$new_url, $cookie);
1113 if (defined $cookiesecret) {
1114 $params->{$r->{S}{assoc_param_name}} = [ $r->hash($cookiesecret) ];
1118 if ($kind =~ m/^LOGIN-/) {
1119 $title = $r->_gt('Login');
1120 push @body, $divert->{Message};
1121 push @body, $r->_ch('gen_login_form', $params);
1122 } elsif ($kind =~ m/^SMALLPAGE-/) {
1123 $title = $r->_gt('Not logged in');
1124 push @body, $divert->{Message};
1125 push @body, $r->_ch('gen_login_link', $params);
1126 } elsif ($kind =~ m/^MAINPAGEONLY$/) {
1127 $title = $r->_gt('Entering secure site.');
1128 push @body, $divert->{Message};
1129 push @body, $r->_ch('gen_postmainpage_form', $params);
1134 $r->_print($r->{Cgi}->header($r->_cgi_header_args($cookie)),
1135 $r->_ch('gen_start_html',$title),
1137 $r->_ch('gen_footer_html'),
1138 $r->_ch('gen_end_html'))));
1143 my ($r, $bytes) = @_;
1145 my $rsf = $v->{RandomHandle};
1146 my $rsp = $r->{S}{random_source};
1148 $v->{RandomHandle} = $rsf = new IO::File $rsp, '<' or die "$rsp $!";
1149 #print STDERR "RH $rsf\n";
1153 read($rsf,$bin,$bytes) == $bytes or die "$rsp $!";
1154 my $out = unpack "H*", $bin;
1155 #print STDERR "_random out $out\n";
1159 sub _random_key ($) {
1161 #print STDERR "_random_key\n";
1162 my $bytes = ($r->{S}{secretbits} + 7) >> 3;
1163 return $r->_random($bytes);
1166 sub _read_key ($$) {
1167 my ($r, $keys) = @_;
1168 # returns $gen_time_t, $key_value_in_hex, $complete_line
1170 my ($gen, $k) = m/^(\d+) (\S+)$/ or die "$_ ?";
1171 my $age = time - $gen;
1172 next if $age > $r->{S}{key_rollover} &&
1173 $age > $r->{S}{login_form_timeout}*2;
1174 return ($gen, $k, $_);
1179 sub _open_keys ($) {
1181 my $spath = $r->_get_path('keys');
1183 #print STDERR "_open_keys\n";
1184 my $keys = new IO::File $spath, 'r+';
1186 #print STDERR "_open_keys open\n";
1187 stat $keys or die $!; # NB must not disturb stat _
1188 my $size = (stat _)[7];
1189 my $age = time - (stat _)[9];
1190 #print STDERR "_open_keys open size=$size age=$age\n";
1192 if $size && $age <= $r->{S}{key_rollover} / 2;
1193 #print STDERR "_open_keys open bad\n";
1195 # file doesn't exist, or is empty or too old
1197 #print STDERR "_open_keys closed\n";
1198 die "$spath $!" unless $!==&ENOENT;
1199 # doesn't exist, so create it just so we can lock it
1200 $keys = new IO::File $spath, 'a+';
1201 die "$keys $!" unless $keys;
1202 stat $keys or die $!; # NB must not disturb stat _
1203 my $size = (stat _)[7];
1204 #print STDERR "_open_keys created size=$size\n";
1205 next if $size; # oh someone else has done it, reopen and read it
1207 # file now exists is empty or too old, we must try to replace it
1208 my $our_inum = (stat _)[1]; # last use of that stat _
1209 flock $keys, LOCK_EX or die "$spath $!";
1210 stat $spath or die "$spath $!";
1211 my $path_inum = (stat _)[1];
1212 #print STDERR "_open_keys locked our=$our_inum path=$path_inum\n";
1213 next if $our_inum != $path_inum; # someone else has done it
1214 # We now hold the lock!
1215 #print STDERR "_open_keys creating\n";
1216 my $newkeys = new IO::Handle;
1217 sysopen $newkeys, "$spath.new", O_CREAT|O_TRUNC|O_WRONLY, 0600
1218 or die "$spath.new $!";
1219 # we add the new key to the front which means it's always sorted
1220 print $newkeys time, ' ', $r->_random_key(), "\n" or die $!;
1221 while (my ($gen,$key,$line) = $r->_read_key($keys)) {
1222 #print STDERR "_open_keys copy1\n";
1223 print $newkeys, $line or die $!;
1225 $keys->error and die $!;
1226 close $newkeys or die "$spath.new $!";
1227 rename "$spath.new", "$spath" or die "$spath: $!";
1228 #print STDERR "_open_keys installed\n";
1229 # that rename effective unlocks, since it makes the name refer
1230 # to the new file which we haven't locked
1231 # we go round again opening the file at the beginning
1232 # so that our caller gets a fresh handle onto the existing key file
1236 sub _fresh_secret ($) {
1238 #print STDERR "_fresh_secret\n";
1240 my $keys = $r->_open_keys();
1241 my ($keyt, $key) = $r->_read_key($keys);
1242 die unless defined $keyt;
1244 my $nonce = $r->_random_key();
1246 my $message = "$noncet.$nonce";
1248 my $signature = $r->_hmac($key, $message);
1249 my $secret = "$keyt.$signature.$message";
1250 #print STDERR "FRESH $secret\n";
1255 my ($r, $keyhex, $message) = @_;
1256 my $keybin = pack "H*", $keyhex;
1257 my $alg = $r->{S}{hash_algorithm};
1258 #print STDERR "hmac $alg\n";
1259 my $base = new Digest $alg;
1260 #print STDERR "hmac $alg $base\n";
1261 my $digest = new Digest::HMAC $keybin, $base;
1262 #print STDERR "hmac $alg $base $digest\n";
1263 $digest->add($message);
1264 return $digest->hexdigest();
1268 my ($r, $message) = @_;
1269 my $alg = $r->{S}{hash_algorithm};
1270 #print STDERR "hash $alg\n";
1271 my $digest = new Digest $alg;
1272 $digest->add($message);
1273 return $digest->hexdigest();
1276 sub _assert_checked ($) {
1278 die "unchecked" unless exists $r->{Divert};
1283 my $meth = $r->_ch('get_method');
1284 return $meth eq 'POST';
1287 sub _must_be_post ($) {
1289 my $meth = $r->_ch('get_method');
1290 die "mutating non-POST" if $meth ne 'POST';
1293 sub check_mutate ($) {
1295 $r->_assert_checked();
1296 die if $r->{Divert};
1297 $r->_must_be_post();
1300 our %_resource_get_needs_secret_hidden =
1301 (map { $_ => 0 } qw(PAGE FRAME IFRAME SRCDUMP STYLESHEET FAVICON ROBOTS),
1302 map { $_ => 1 } qw(IMAGE SCRIPT AJAX-XML AJAX-JSON AJAX-OTHER));
1304 sub update_get_need_add_hidden ($$;$) {
1305 my ($r, $reqtype, $value, $force) = @_;
1307 ? ($r->{GetNeedsSecretHidden} ||= { })
1308 : \%_resource_get_needs_secret_hidden;
1309 return if !$force &&
1310 (exists $_resource_get_needs_secret_hidden{$reqtype} ||
1311 exists $hash->{$reqtype});
1312 $hash->{$reqtype} = $value;
1315 sub need_add_hidden ($$) {
1316 my ($r, $method, $reqtype) = @_;
1317 return 1 if $method ne 'GET';
1319 my $ent = $r->{GetNeedsSecretHidden}{$reqtype};
1320 return $ent if defined $ent;
1322 my $ent = $_resource_get_needs_secret_hidden{$reqtype};
1323 return $ent if defined $ent;
1324 die "unsupported nonpage GET type $reqtype";
1327 sub check_nonpage ($$) {
1328 my ($r, $reqtype) = @_;
1329 $r->_assert_checked();
1330 return unless $r->resource_get_needs_secret_hidden($nonpagetype);
1331 return if $r->{ParmT};
1332 die "missing hidden secret parameter on nonpage request $nonpagetype";
1335 #---------- output ----------
1337 sub secret_cookie_val ($) {
1339 $r->_assert_checked();
1340 return defined $r->{AssocSecret} ? $r->{AssocSecret} : '';
1343 sub secret_hidden_val ($) {
1345 $r->_assert_checked();
1346 return defined $r->{AssocSecret} ? $r->hash($r->{AssocSecret}) : '';
1349 sub secret_hidden_html ($) {
1351 return $r->{Cgi}->hidden(-name => $r->{S}{assoc_param_name},
1352 -default => $r->secret_hidden_val());
1355 sub secret_cookie ($) {
1357 my $secret = $r->secret_cookie_val();
1358 return undef if !defined $secret;
1359 #print STDERR "SC\n";
1360 my $cookv = $r->construct_cookie($secret);
1361 #print STDERR "SC=$cookv\n";