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/;
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 #---------- licence and source code ----------
207 sub srcdump_dump ($$$) {
208 my ($c,$r, $thing) = @_;
209 die if $thing =~ m/\W/ || $thing !~ m/\w/;
210 my $path = $r->_get_path('srcdump');
211 my $ctf = new IO::File "$path/$thing.ctype", 'r'
212 or die "$path/$thing.ctype $!";
214 chomp $ct or die "$path/$thing ?";
215 $ctf->close or die "$path/$thing $!";
216 my $df = new IO::File "$path/$thing.data", 'r'
217 or die "$path/$thing.data $!";
218 $r->_ch('dump', $ct, $df);
221 sub dump_plain ($$$$) {
222 my ($c, $r, $ct, $df) = @_;
223 $r->_print($c->header('-type' => $ct));
226 my $got = read $df, $buffer, 65536;
227 die $! unless defined $got;
233 sub srcdump_process_item ($$$$$$) {
234 my ($c, $v, $dumpdir, $item, $outfn, $needlicence, $dirsdone) = @_;
235 if ($v->_ch('srcdump_system_dir', $item)) {
236 $outfn->("srcdump_process_item: srcdump_system_dir, skipping $item");
242 $upwards =~ s#/+\.$##;
243 last unless $upwards =~ m#[^/]#;
244 foreach my $try (@{ $v->{S}{srcdump_vcs_dirs} }) {
245 #print STDERR "TRY $item $upwards $try\n";
246 if (!stat "$upwards/$try") {
247 $!==&ENOENT or $!==&ENOTDIR or die "check $upwards/$try $!";
250 #print STDERR "VCS $item $upwards $try\n";
251 if ($dirsdone->{$upwards}++) {
252 $outfn->("srcdump_process_item: did $upwards,".
256 #print STDERR "VCS $item $upwards $try GO\n";
257 $try =~ m/\w+/ or die;
258 return $v->_ch('srcdump_byvcs', $dumpdir, $upwards, $outfn, lc $&);
260 $upwards =~ s#/*[^/]+$##;
262 return $v->_ch('srcdump_novcs', $dumpdir, $item, $outfn);
265 sub srcdump_novcs ($$$$$) {
266 my ($c, $v, $dumpdir, $item, $outfn) = @_;
267 stat $item or die "$item $!";
269 my $script = 'find -type f -perm +004';
270 foreach my $excl (@{ $v->{S}{srcdump_excludes} }) {
271 $script .= " \\! -name '$excl'";
273 $script .= " -print0";
274 return srcdump_dir_cpio($c,$v,$dumpdir,$item,$outfn,'novcs',$script);
276 return srcdump_file($c,$v,$dumpdir,$item,$outfn);
278 die "$item not file or directory";
282 sub srcdump_byvcs ($$$$$$) {
283 my ($c, $v, $dumpdir, $dir, $outfn, $vcs) = @_;
284 #print STDERR "BYVCS GIT $dir\n";
285 my $script = $v->{S}{"srcdump_vcsscript"}{$vcs};
286 die "no script for vcs $vcs" unless defined $script;
287 return srcdump_dir_cpio($c,$v,$dumpdir,$dir,$outfn,$vcs,$script);
290 sub srcdump_file ($$$$) {
291 my ($c,$v,$dumpdir,$file,$outfn) = @_;
292 my $outfile = $outfn->("srcdump_file saved $file", "src");
293 copy($file,$outfile) or die "$file $outfile $!";
296 sub srcdump_dir_cpio ($$$$$$$) {
297 my ($c,$v,$dumpdir,$dir,$outfn,$how,$script) = @_;
298 my $outfile = $outfn->("srcdump_dir_cpio $how saved $dir", "tar");
299 #print STDERR "CPIO $dir >$script<\n";
301 defined $pid or die $!;
303 $SIG{__DIE__} = sub {
304 print STDERR "CGI::Auth::Flexible srcdump error: $@\n";
307 open STDOUT, ">", $outfile or die "$outfile $!";
308 chdir $dir or die "chdir $dir: $!";
309 exec '/bin/bash','-ec',"
314 cpio -Hustar -o --quiet -0 -R 1000:1000 || \
315 cpio -Hustar -o --quiet -0
320 $!=0; (waitpid $pid, 0) == $pid or die "$!";
321 die "$dir ($how $script) $outfile $?" if $?;
324 sub srcdump_dirscan_prepare ($$) {
326 my $dumpdir = $v->_get_path('srcdump');
327 mkdir $dumpdir or $!==&EEXIST or die "mkdir $dumpdir $!";
328 my $lockf = new IO::File "$dumpdir/generate.lock", 'w+'
329 or die "$dumpdir/generate.lock $!";
330 flock $lockf, LOCK_EX or die "$dumpdir/generate.lock $!";
331 my $needlicence = "$dumpdir/licence.tmp";
332 unlink $needlicence or $!==&ENOENT or die "rm $needlicence $!";
333 if (defined $v->{S}{srcdump_licence_path}) {
334 copy($v->{S}{srcdump_licence_path}, $needlicence)
335 or die "$v->{S}{srcdump_licence_path} $!";
336 $needlicence = undef;
338 unlink <"$dumpdir/s.[a-z][a-z][a-z].*">;
339 my @srcfiles = qw(licence.data manifest.txt);
340 my $srcoutcounter = 'aaa';
342 my $reportfh = new IO::File "$dumpdir/manifest.txt", 'w' or die $!;
344 my ($message, $extension) = @_;
345 if (defined $extension) {
346 my $leaf = "s.$srcoutcounter.$extension";
348 push @srcfiles, $leaf;
349 print $reportfh "$leaf: $message\n" or die $!;
350 return "$dumpdir/$leaf";
352 print $reportfh "none: $message\n" or die $!;
357 foreach my $item ($v->_ch('srcdump_listitems')) {
358 if ($item eq '.' && $v->{S}{srcdump_filter_cwd}) {
359 my @bad = grep { !m#^/# } values %INC;
360 die "filtering . from srcdump items and \@INC but already".
361 " included @bad " if @bad;
362 @INC = grep { $_ ne '.' } @INC;
365 if (!lstat "$item") {
366 die "stat $item $!" unless $!==&ENOENT;
367 $outfn->("srcdump_dirscan_prepare stat ENOENT, skipping $item");
371 $item = realpath($item);
372 if (!defined $item) {
373 die "realpath $item $!" unless $!==&ENOENT;
374 $outfn->("srcdump_dirscan_prepare realpath ENOENT,".
378 if (defined $needlicence) {
379 foreach my $try (@{ $v->{S}{srcdump_licence_files} }) {
380 last if copy("$item/$try", $needlicence);
381 $!==&ENOENT or $!==&ENOTDIR or die "copy $item/$try $!";
384 $v->_ch('srcdump_process_item', $dumpdir, $item,
385 $outfn, \$needlicence, \%dirsdone);
388 close $reportfh or die $!;
389 srcdump_install($c,$v, $dumpdir, 'licence', 'text/plain');
391 my @cmd = (qw(tar -zvvcf), "$dumpdir/source.tmp",
392 "-C", $dumpdir, qw( --), @srcfiles);
393 my $r = system(@cmd);
395 print STDERR "CGI::Auth::Flexible tar failed ($r $!) @cmd\n";
398 die "licence file not found" unless defined $needlicence;
399 srcdump_install($c,$v, $dumpdir, 'source', 'application/octet-stream');
400 close $lockf or die $!;
403 sub srcdump_install ($$$$$) {
404 my ($c,$v, $dumpdir, $which, $ctype) = @_;
405 rename "$dumpdir/$which.tmp", "$dumpdir/$which.data"
406 or die "$dumpdir/$which.data $!";
407 my $ctf = new IO::File "$dumpdir/$which.tmp", 'w'
408 or die "$dumpdir/$which.tmp $!";
409 print $ctf $ctype, "\n" or die $!;
410 close $ctf or die $!;
411 rename "$dumpdir/$which.tmp", "$dumpdir/$which.ctype"
412 or die "$dumpdir/$which.ctype $!";
415 #---------- verifier object methods ----------
422 assocdb_dbh => undef, # must have AutoCommit=0, RaiseError=1
423 assocdb_path => 'caf-assocs.db',
424 keys_path => 'caf-keys',
425 srcdump_path => 'caf-srcdump',
426 assocdb_dsn => undef,
428 assocdb_password => '',
429 assocdb_table => 'caf_assocs',
430 random_source => '/dev/urandom',
431 secretbits => 128, # bits
432 hash_algorithm => "SHA-256",
433 login_timeout => 86400, # seconds
434 login_form_timeout => 3600, # seconds
435 key_rollover => 86400, # seconds
436 assoc_param_name => 'caf_assochash',
437 dummy_param_name_prefix => 'caf__',
438 cookie_name => "caf_assocsecret",
439 password_param_name => 'password',
440 srcdump_param_name => 'caf_srcdump',
441 username_param_names => [qw(username)],
442 form_entry_size => 60,
443 logout_param_names => [qw(caf_logout)],
444 loggedout_param_names => [qw(caf_loggedout)],
445 promise_check_mutate => 0,
446 get_param => sub { $_[0]->param($_[2]) },
447 get_params => sub { $_[1]->get_params() },
448 get_path_info => sub { $_[0]->path_info() },
449 get_cookie => sub { $_[0]->cookie($_[1]->{S}{cookie_name}) },
450 get_method => sub { $_[0]->request_method() },
451 is_https => sub { !!$_[0]->https() },
452 get_url => sub { $_[0]->url(); },
453 is_login => sub { defined $_[1]->_rp('password_param_name') },
454 login_ok => \&login_ok_password,
455 username_password_error => sub { die },
456 is_logout => sub { $_[1]->has_a_param('logout_param_names') },
457 is_loggedout => sub { $_[1]->has_a_param('loggedout_param_names') },
458 handle_divert => sub { return 0 },
459 do_redirect => \&do_redirect_cgi, # this hook is allowed to throw
461 get_cookie_domain => \&get_cookie_domain,
463 gen_start_html => sub { $_[0]->start_html($_[2]); },
464 gen_footer_html => \&gen_plain_footer_html,
465 gen_licence_link_html => \&gen_plain_licence_link_html,
466 gen_source_link_html => \&gen_plain_source_link_html,
467 gen_end_html => sub { $_[0]->end_html(); },
468 gen_login_form => \&gen_plain_login_form,
469 gen_login_link => \&gen_plain_login_link,
470 gen_postmainpage_form => \&gen_postmainpage_form,
471 srcdump_dump => \&srcdump_dump,
472 srcdump_prepare => \&srcdump_dirscan_prepare,
473 srcdump_licence_path => undef,
474 srcdump_licence_files => [qw(AGPLv3 CGI/Auth/Flexible/AGPLv3)],
475 srcdump_listitems => sub { (@INC, $ENV{'SCRIPT_FILENAME'}, $0); },
476 srcdump_filter_cwd => 1,
477 srcdump_system_dir => sub {
478 $_[2] =~ m#^/etc/|^/usr/(?!local/)(?!lib/cgi)#;
480 srcdump_process_item => \&srcdump_process_item,
481 srcdump_vcs_dirs => [qw(.git .hg .bzr .svn)],
482 srcdump_vcsscript => [git => "
484 git ls-files -z --others --exclude-from=.gitignore
487 srcdump_byvcs => \&srcdump_byvcs,
488 srcdump_novcs => \&srcdump_novcs,
489 srcdump_excludes => [qw(*~ *.bak *.tmp), '#*#'],
490 dump => \&dump_plain,
491 gettext => sub { gettext($_[2]); },
492 print => sub { print $_[2] or die $!; },
493 debug => sub { }, # like print; msgs contain trailing \n
498 while (($k,$v,@_) = @_) {
499 die "unknown setting $k" unless
500 $k =~ m/^promise_/ or
501 exists $verifier->{S}{$k};
502 $verifier->{S}{$k} = $v;
504 bless $verifier, $class;
505 $verifier->_dbopen();
506 $verifier->_ch('srcdump_prepare');
510 sub _db_setup_do ($$) {
514 $v->_db_transaction(sub {
515 local ($dbh->{PrintError}) = 0;
526 $dbh = $v->{S}{assocdb_dbh};
528 die if $dbh->{AutoCommit};
529 die unless $dbh->{RaiseError};
531 $v->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=".$v->_get_path('assocdb');
532 my $dsn = $v->{S}{assocdb_dsn};
535 $dbh = DBI->connect($dsn, $v->{S}{assocdb_user},
536 $v->{S}{assocdb_password}, {
539 ShowErrorStatement => 1,
542 die "$dsn $! ?" unless $dbh;
546 $v->_db_setup_do("CREATE TABLE $v->{S}{assocdb_table} (".
547 " assochash VARCHAR PRIMARY KEY,".
548 " username VARCHAR NOT NULL,".
549 " last INTEGER NOT NULL".
551 $v->_db_setup_do("CREATE INDEX $v->{S}{assocdb_table}_timeout_index".
552 " ON $v->{S}{assocdb_table}".
564 sub _db_transaction ($$) {
569 #print STDERR "DT entry\n";
571 #print STDERR "DT loop\n";
574 #print STDERR "DT fn ok\n";
577 #print STDERR "DT fn error\n";
578 { local ($@); $dbh->rollback(); }
579 #print STDERR "DT fn throwing\n";
582 #print STDERR "DT fn eval ok\n";
585 #print STDERR "DT commit ok\n";
588 #print STDERR "DT commit eval ok ",Dumper($rv);
591 #print STDERR "DT commit throw?\n";
592 die $@ if !--$retries;
593 #print STDERR "DT loop again\n";
597 #---------- request object methods ----------
600 my ($classbase, $cgi, @extra) = @_;
601 if (!ref $classbase) {
602 $classbase = $classbase->new_verifier(@extra);
608 S => $classbase->{S},
609 Dbh => $classbase->{Dbh},
612 bless $r, ref $classbase;
615 sub _ch ($$@) { # calls an application hook
616 my ($r,$methname, @args) = @_;
617 my $methfunc = $r->{S}{$methname};
618 die "$methname ?" unless $methfunc;
619 return $methfunc->($r->{Cgi}, $r, @args);
624 my $pn = $r->{S}{$pnvb};
625 my $p = scalar $r->_ch('get_param',$pn)
630 $r->_ch('debug',@args);
634 my ($r,$keybase) = @_;
635 my $leaf = $r->{S}{"${keybase}_path"};
636 return $r->_absify_path($leaf);
639 sub _absify_path ($$) {
641 return $leaf if $leaf =~ m,^/,;
642 my $dir = $v->{S}{dir};
643 die "relying on cwd by default ?! set dir" unless defined $dir;
647 sub _gt ($$) { my ($r, $t) = @_; return $r->_ch('gettext',$t); }
648 sub _print ($$) { my ($r, @t) = @_; return $r->_ch('print', join '', @t); }
650 sub construct_cookie ($$$) {
651 my ($r, $cooks) = @_;
652 return undef unless $cooks;
654 my @ca = (-name => $r->{S}{cookie_name},
656 -path => $r->{S}{cookie_path},
657 -domain => $r->_ch('get_cookie_domain'),
658 -expires => '+'.$r->{S}{login_timeout}.'s',
659 -secure => $r->{S}{encrypted_only});
660 my $cookie = $c->cookie(@ca);
661 #print STDERR "CC $r $c $cooks $cookie (@ca).\n";
665 # pages/param-sets are
666 # n normal non-mutating page
667 # r retrieval of information for JS etc., non-mutating
669 # u update of information by JS etc., mutating
672 # O "you have just logged out" page load
675 # - no value supplied (represented in code as $cookt='')
676 # n, nN value not in our db
677 # t, tN temporary value (in our db, no logged in user yet)
678 # y, yN value corresponds to logged-in user
679 # and, aggregated conditions:
680 # a, aN anything including -
682 # if N differs the case applies only when the two values differ
683 # (eg, a1 y2 does not apply when the logged-in value is supplied twice)
685 # "stale session" means request originates from a page from a login
686 # session which has been revoked (eg by logout); "cleared session"
687 # means request originates from a browser which has a different (or
690 # Case analysis, cookie mode, app promises re mutate:
691 # cook parm meth form
693 # any - POST nrmuoi bug or attack, fail
694 # any - GET rmuoi bug or attack, fail
695 # any any GET muoi bug or attack, fail
696 # any t any nrmu bug or attack, fail
698 # - - GET O "just logged out" page
699 # (any other) O bug or attack, fail
701 # a1 a2 POST o logout
702 # if a1 is valid, revoke it
703 # if a2 is valid, revoke it
705 # redirect to "just logged out" page
706 # (which contains link to login form)
708 # - t POST i complain about cookies being disabled
709 # (with link to login form)
711 # t1 t1 POST i login (or switch user)
713 # show new login form
715 # upgrade t1 to y1 in our db (setting username)
716 # redirect to GET of remaining params
718 # y1 a2 POST i complain about stale login form
720 # show new login form
722 # (other) POST i complain about stale login form
723 # show new login form
725 # t1 a2 ANY nrmu treat as - a2 ANY
727 # y - GET n cross-site link
730 # y y GET nr fine, show page or send data
731 # y y POST nrmu mutation is OK, do operation
733 # y1 y2 GET nr request from stale page
734 # do not revoke y2 as not RESTful
737 # y1 y2 POST nrmu request from stale page
741 # y n GET n intra-site link from stale page,
742 # treat as cross-site link, show data
744 # y n POST n m intra-site form submission from stale page
745 # show "session interrupted"
746 # with link to main data page
748 # y n GET r intra-site request from stale page
751 # y n POST r u intra-site request from stale page
754 # -/n y2 GET nr intra-site link from cleared session
755 # do not revoke y2 as not RESTful
758 # -/n y2 POST nrmu request from cleared session
760 # treat as -/n n POST
762 # -/n -/n GET n cross-site link but user not logged in
763 # show login form with redirect to orig params
764 # generate fresh cookie
766 # -/n n GET rmu user not logged in
769 # -/n n POST n m user not logged in
772 # -/n n POST r u user not logged in
775 sub _check_divert_core ($) {
778 my $srcdump = $r->_rp('srcdump_param_name');
780 die if $srcdump =~ m/\W/;
781 return ({ Kind => 'SRCDUMP-'.uc $srcdump,
783 CookieSecret => undef,
787 my $cooks = $r->_ch('get_cookie');
789 if ($r->{S}{encrypted_only} && !$r->_ch('is_https')) {
790 return ({ Kind => 'REDIRECT-HTTPS',
791 Message => $r->_gt("Redirecting to secure server..."),
792 CookieSecret => undef,
796 my $meth = $r->_ch('get_method');
797 my $parmh = $r->_rp('assoc_param_name');
798 my $cookh = defined $cooks ? $r->hash($cooks) : undef;
800 my ($cookt,$cooku) = $r->_identify($cookh, $cooks);
801 my $parms = (defined $cooks && defined $parmh && $parmh eq $cookh)
803 my ($parmt) = $r->_identify($parmh, $parms);
805 $r->_debug("_c_d_c cookt=$cookt parmt=$parmt\n");
807 if ($r->_ch('is_logout')) {
810 $r->_db_revoke($cookh);
811 $r->_db_revoke($parmh);
812 return ({ Kind => 'REDIRECT-LOGGEDOUT',
813 Message => $r->_gt("Logging out..."),
817 if ($r->_ch('is_loggedout')) {
818 die unless $meth eq 'GET';
819 die if $cookt eq 'y';
821 return ({ Kind => 'SMALLPAGE-LOGGEDOUT',
822 Message => $r->_gt("You have been logged out."),
826 if ($r->_ch('is_login')) {
829 if (!$cookt && $parmt eq 'n') {
830 return ({ Kind => 'SMALLPAGE-NOCOOKIE',
831 Message => $r->_gt("You do not seem to have cookies".
832 " enabled. You must enable cookies".
833 " as we use them for login."),
834 CookieSecret => $r->_fresh_secret(),
835 Params => $r->_chain_params() })
837 if (!$cookt || $cookt eq 'n' || $cookh ne $parmh) {
838 $r->_db_revoke($cookh);
839 return ({ Kind => 'LOGIN-STALE',
840 Message => $r->_gt("Stale session;".
841 " you need to log in again."),
842 CookieSecret => $r->_fresh_secret(),
845 die unless $parmt eq 't' || $parmt eq 'y';
846 my ($username, $login_errormessage) = $r->_ch('login_ok');
847 unless (defined $username && length $username) {
848 $login_errormessage = $r->_gt("Incorrect username/password.")
849 if !$login_errormessage;
850 return ({ Kind => 'LOGIN-BAD',
851 Message => $login_errormessage,
852 CookieSecret => $cooks,
853 Params => $r->_chain_params() })
855 $r->_db_record_login_ok($parmh,$username);
856 return ({ Kind => 'REDIRECT-LOGGEDIN',
857 Message => $r->_gt("Logging in..."),
858 CookieSecret => $cooks,
859 Params => $r->_chain_params() });
864 die if $parmt eq 't';
866 if ($cookt eq 'y' && $parmt eq 'y' && $cookh ne $parmh) {
867 $r->_db_revoke($parmh) if $meth eq 'POST';
872 die unless !$cookt || $cookt eq 'n';
873 die unless !$parmt || $parmt eq 'n' || $parmt eq 'y';
874 my $news = $r->_fresh_secret();
875 if ($meth eq 'GET') {
876 return ({ Kind => 'LOGIN-INCOMINGLINK',
877 Message => $r->_gt("You need to log in."),
878 CookieSecret => $news,
879 Params => $r->_chain_params() });
881 $r->_db_revoke($parmh);
882 return ({ Kind => 'LOGIN-FRESH',
883 Message => $r->_gt("You need to log in."),
884 CookieSecret => $news,
889 if (!$r->{S}{promise_check_mutate}) {
890 if ($meth ne 'POST') {
891 return ({ Kind => 'MAINPAGEONLY',
892 Message => $r->_gt('Entering via cross-site link.'),
893 CookieSecret => $cooks,
895 # NB caller must then ignore params & path!
896 # if this is too hard they can spit out a small form
897 # with a "click to continue"
901 die unless $cookt eq 'y';
902 unless ($r->{S}{promise_check_mutate} && $meth eq 'GET') {
903 die unless $parmt eq 'y';
904 die unless $cookh eq $parmh;
906 $r->{ParmT} = $parmt;
907 $r->{AssocSecret} = $cooks;
908 $r->{UserOK} = $cooku;
909 #print STDERR "C-D-C OK\n";
913 sub _chain_params ($) {
914 # =item C<< $authreq->_chain_params() >>
916 # Returns a hash of the "relevant" parameters to this request, in a form
917 # used by C<url_with_query_params>. This is all of the query parameters
918 # which are not related to CGI::Auth::Flexible. The PATH_INFO from the
919 # request is returned as the parameter C<< '' >>.
922 my %p = %{ $r->_ch('get_params') };
923 foreach my $pncn (keys %{ $r->{S} }) {
925 if ($pncn =~ m/_param_name$/) {
926 my $name = $r->{S}{$pncn};
927 die "$pncn ?" if ref $name;
929 } elsif ($pncn =~ m/_param_names$/) {
930 $names = $r->{S}{$pncn};
934 foreach my $name (@$names) {
938 my $dummy_prefix = $r->{S}{dummy_param_name_prefix};
939 foreach my $name (grep /^$dummy_prefix/, keys %p) {
942 die if exists $p{''};
943 $p{''} = [ $r->_ch('get_path_info') ];
949 # returns ($t,$username)
950 # where $t is one of "t" "y" "n", or "" (for -)
951 # either $s must be undef, or $h eq $r->hash($s)
953 #print STDERR "_identify\n";
954 return '' unless defined $h && length $h;
955 #print STDERR "_identify h=$h s=".(defined $s ? $s : '<undef>')."\n";
959 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
960 " WHERE last < ?", {},
961 time - $r->{S}{login_timeout});
963 my $row = $dbh->selectrow_arrayref("SELECT username, last".
964 " FROM $r->{S}{assocdb_table}".
965 " WHERE assochash = ?", {}, $h);
967 #print STDERR "_identify h=$h s=$s YES @$row\n";
968 my ($nusername, $nlast) = @$row;
969 return ('y', $nusername);
972 # Well, it's not in the database. But maybe it's a hash of a
975 return 'n' unless defined $s;
977 my ($keyt, $signature, $message, $noncet, $nonce) =
978 $s =~ m/^(\d+)\.(\w+)\.((\d+)\.(\w+))$/ or die;
980 return 'n' if time > $noncet + $r->{S}{login_form_timeout};
982 #print STDERR "_identify noncet=$noncet ok\n";
984 my $keys = $r->_open_keys();
985 while (my ($rkeyt, $rkey, $line) = $r->_read_key($keys)) {
986 #print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey\n";
987 last if $rkeyt < $keyt; # too far down in the file
988 my $trysignature = $r->_hmac($rkey, $message);
989 #print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey try=$trysignature\n";
990 return 't' if $trysignature eq $signature;
993 #print STDERR "_identify NO\n";
995 $keys->error and die $!;
999 sub _db_revoke ($$) {
1000 # revokes $h if it's valid; no-op if it's not
1003 my $dbh = $r->{Dbh};
1005 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
1006 " WHERE assochash = ?", {}, $h);
1009 sub _db_record_login_ok ($$$) {
1010 my ($r,$h,$user) = @_;
1012 my $dbh = $r->{Dbh};
1013 $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
1014 " (assochash, username, last) VALUES (?,?,?)", {},
1018 sub check_divert ($) {
1020 if (exists $r->{Divert}) {
1021 return $r->{Divert};
1023 my $dbh = $r->{Dbh};
1024 $r->{Divert} = $r->_db_transaction(sub { $r->_check_divert_core(); });
1026 $r->_debug(Data::Dumper->Dump([$r->{Divert}],[qw(divert)]));
1027 return $r->{Divert};
1030 sub get_divert ($) {
1032 die "unchecked" unless exists $r->{Divert};
1033 return $r->{Divert};
1036 sub get_username ($) {
1038 my $divert = $r->get_divert();
1039 return undef if $divert;
1040 return $r->{UserOK};
1043 sub url_with_query_params ($$;$) {
1044 my ($r, $params, $nonpagetype) = @_;
1045 #print STDERR "PARAMS ",Dumper($params);
1046 my $uri = URI->new($r->_ch('get_url'));
1047 $uri->path($uri->path() . $params->{''}[0]) if $params->{''};
1048 my @flatparams = flatten_params($params);
1049 if (defined $nonpagetype && $r->need_add_hidden('GET',$nonpagetype)) {
1050 push @flatparams, $r->{S}{assoc_param_name}, $r->secret_hidden_val();
1052 $uri->query_form(@flatparams);
1053 return $uri->as_string();
1056 sub _cgi_header_args ($$@) {
1057 my ($r, $cookie, @ha) = @_;
1058 unshift @ha, qw(-type text/html);
1059 push @ha, (-cookie => $cookie) if defined $cookie;
1060 #print STDERR "_cgi_header_args ",join('|',@ha),".\n";
1067 my ($divert) = $r->check_divert();
1068 return 1 if !$divert;
1070 my $handled = $r->_ch('handle_divert',$divert);
1071 return 0 if $handled;
1073 my $kind = $divert->{Kind};
1074 my $cookiesecret = $divert->{CookieSecret};
1075 my $params = $divert->{Params};
1076 my $cookie = $r->construct_cookie($cookiesecret);
1078 if ($kind =~ m/^SRCDUMP-(\w+)$/) {
1079 $r->_ch('srcdump_dump', (lc $1));
1083 if ($kind =~ m/^REDIRECT-/) {
1084 # for redirects, we honour stored Params and Cookie,
1085 # as we would for non-divert
1086 if ($kind eq 'REDIRECT-LOGGEDOUT') {
1087 $params->{$r->{S}{loggedout_param_names}[0]} = [ 1 ];
1088 } elsif ($kind eq 'REDIRECT-LOGOUT') {
1089 $params->{$r->{S}{logout_param_names}[0]} = [ 1 ];
1090 } elsif ($kind =~ m/REDIRECT-(?:LOGGEDIN|HTTPS)/) {
1094 my $new_url = $r->url_with_query_params($params);
1095 if ($kind eq 'REDIRECT-HTTPS') {
1096 my $uri = URI->new($new_url);
1097 die unless $uri->scheme eq 'http';
1098 $uri->scheme('https');
1099 $new_url = $uri->as_string();
1101 $r->_ch('do_redirect',$new_url, $cookie);
1105 if (defined $cookiesecret) {
1106 $params->{$r->{S}{assoc_param_name}} = [ $r->hash($cookiesecret) ];
1110 if ($kind =~ m/^LOGIN-/) {
1111 $title = $r->_gt('Login');
1112 push @body, $divert->{Message};
1113 push @body, $r->_ch('gen_login_form', $params);
1114 } elsif ($kind =~ m/^SMALLPAGE-/) {
1115 $title = $r->_gt('Not logged in');
1116 push @body, $divert->{Message};
1117 push @body, $r->_ch('gen_login_link', $params);
1118 } elsif ($kind =~ m/^MAINPAGEONLY$/) {
1119 $title = $r->_gt('Entering secure site.');
1120 push @body, $divert->{Message};
1121 push @body, $r->_ch('gen_postmainpage_form', $params);
1126 $r->_print($r->{Cgi}->header($r->_cgi_header_args($cookie)),
1127 $r->_ch('gen_start_html',$title),
1129 $r->_ch('gen_footer_html'),
1130 $r->_ch('gen_end_html'))));
1135 my ($r, $bytes) = @_;
1137 my $rsf = $v->{RandomHandle};
1138 my $rsp = $r->{S}{random_source};
1140 $v->{RandomHandle} = $rsf = new IO::File $rsp, '<' or die "$rsp $!";
1141 #print STDERR "RH $rsf\n";
1145 read($rsf,$bin,$bytes) == $bytes or die "$rsp $!";
1146 my $out = unpack "H*", $bin;
1147 #print STDERR "_random out $out\n";
1151 sub _random_key ($) {
1153 #print STDERR "_random_key\n";
1154 my $bytes = ($r->{S}{secretbits} + 7) >> 3;
1155 return $r->_random($bytes);
1158 sub _read_key ($$) {
1159 my ($r, $keys) = @_;
1160 # returns $gen_time_t, $key_value_in_hex, $complete_line
1162 my ($gen, $k) = m/^(\d+) (\S+)$/ or die "$_ ?";
1163 my $age = time - $gen;
1164 next if $age > $r->{S}{key_rollover} &&
1165 $age > $r->{S}{login_form_timeout}*2;
1166 return ($gen, $k, $_);
1171 sub _open_keys ($) {
1173 my $spath = $r->_get_path('keys');
1175 #print STDERR "_open_keys\n";
1176 my $keys = new IO::File $spath, 'r+';
1178 #print STDERR "_open_keys open\n";
1179 stat $keys or die $!; # NB must not disturb stat _
1180 my $size = (stat _)[7];
1181 my $age = time - (stat _)[9];
1182 #print STDERR "_open_keys open size=$size age=$age\n";
1184 if $size && $age <= $r->{S}{key_rollover} / 2;
1185 #print STDERR "_open_keys open bad\n";
1187 # file doesn't exist, or is empty or too old
1189 #print STDERR "_open_keys closed\n";
1190 die "$spath $!" unless $!==&ENOENT;
1191 # doesn't exist, so create it just so we can lock it
1192 $keys = new IO::File $spath, 'a+';
1193 die "$keys $!" unless $keys;
1194 stat $keys or die $!; # NB must not disturb stat _
1195 my $size = (stat _)[7];
1196 #print STDERR "_open_keys created size=$size\n";
1197 next if $size; # oh someone else has done it, reopen and read it
1199 # file now exists is empty or too old, we must try to replace it
1200 my $our_inum = (stat _)[1]; # last use of that stat _
1201 flock $keys, LOCK_EX or die "$spath $!";
1202 stat $spath or die "$spath $!";
1203 my $path_inum = (stat _)[1];
1204 #print STDERR "_open_keys locked our=$our_inum path=$path_inum\n";
1205 next if $our_inum != $path_inum; # someone else has done it
1206 # We now hold the lock!
1207 #print STDERR "_open_keys creating\n";
1208 my $newkeys = new IO::Handle;
1209 sysopen $newkeys, "$spath.new", O_CREAT|O_TRUNC|O_WRONLY, 0600
1210 or die "$spath.new $!";
1211 # we add the new key to the front which means it's always sorted
1212 print $newkeys time, ' ', $r->_random_key(), "\n" or die $!;
1213 while (my ($gen,$key,$line) = $r->_read_key($keys)) {
1214 #print STDERR "_open_keys copy1\n";
1215 print $newkeys, $line or die $!;
1217 $keys->error and die $!;
1218 close $newkeys or die "$spath.new $!";
1219 rename "$spath.new", "$spath" or die "$spath: $!";
1220 #print STDERR "_open_keys installed\n";
1221 # that rename effective unlocks, since it makes the name refer
1222 # to the new file which we haven't locked
1223 # we go round again opening the file at the beginning
1224 # so that our caller gets a fresh handle onto the existing key file
1228 sub _fresh_secret ($) {
1230 #print STDERR "_fresh_secret\n";
1232 my $keys = $r->_open_keys();
1233 my ($keyt, $key) = $r->_read_key($keys);
1234 die unless defined $keyt;
1236 my $nonce = $r->_random_key();
1238 my $message = "$noncet.$nonce";
1240 my $signature = $r->_hmac($key, $message);
1241 my $secret = "$keyt.$signature.$message";
1242 #print STDERR "FRESH $secret\n";
1247 my ($r, $keyhex, $message) = @_;
1248 my $keybin = pack "H*", $keyhex;
1249 my $alg = $r->{S}{hash_algorithm};
1250 #print STDERR "hmac $alg\n";
1251 my $base = new Digest $alg;
1252 #print STDERR "hmac $alg $base\n";
1253 my $digest = new Digest::HMAC $keybin, $base;
1254 #print STDERR "hmac $alg $base $digest\n";
1255 $digest->add($message);
1256 return $digest->hexdigest();
1260 my ($r, $message) = @_;
1261 my $alg = $r->{S}{hash_algorithm};
1262 #print STDERR "hash $alg\n";
1263 my $digest = new Digest $alg;
1264 $digest->add($message);
1265 return $digest->hexdigest();
1268 sub _assert_checked ($) {
1270 die "unchecked" unless exists $r->{Divert};
1275 my $meth = $r->_ch('get_method');
1276 return $meth eq 'POST';
1279 sub _must_be_post ($) {
1281 my $meth = $r->_ch('get_method');
1282 die "mutating non-POST" if $meth ne 'POST';
1285 sub check_mutate ($) {
1287 $r->_assert_checked();
1288 die if $r->{Divert};
1289 $r->_must_be_post();
1292 our %_resource_get_needs_secret_hidden =
1293 (map { $_ => 0 } qw(PAGE FRAME IFRAME SRCDUMP STYLESHEET FAVICON ROBOTS),
1294 map { $_ => 1 } qw(IMAGE SCRIPT AJAX-XML AJAX-JSON AJAX-OTHER));
1296 sub update_get_need_add_hidden ($$;$) {
1297 my ($r, $reqtype, $value, $force) = @_;
1299 ? ($r->{GetNeedsSecretHidden} ||= { })
1300 : \%_resource_get_needs_secret_hidden;
1301 return if !$force &&
1302 (exists $_resource_get_needs_secret_hidden{$reqtype} ||
1303 exists $hash->{$reqtype});
1304 $hash->{$reqtype} = $value;
1307 sub need_add_hidden ($$) {
1308 my ($r, $method, $reqtype) = @_;
1309 return 1 if $method ne 'GET';
1311 my $ent = $r->{GetNeedsSecretHidden}{$reqtype};
1312 return $ent if defined $ent;
1314 my $ent = $_resource_get_needs_secret_hidden{$reqtype};
1315 return $ent if defined $ent;
1316 die "unsupported nonpage GET type $reqtype";
1319 sub check_nonpage ($$) {
1320 my ($r, $reqtype) = @_;
1321 $r->_assert_checked();
1322 return unless $r->resource_get_needs_secret_hidden($nonpagetype);
1323 return if $r->{ParmT};
1324 die "missing hidden secret parameter on nonpage request $nonpagetype";
1327 #---------- output ----------
1329 sub secret_cookie_val ($) {
1331 $r->_assert_checked();
1332 return defined $r->{AssocSecret} ? $r->{AssocSecret} : '';
1335 sub secret_hidden_val ($) {
1337 $r->_assert_checked();
1338 return defined $r->{AssocSecret} ? $r->hash($r->{AssocSecret}) : '';
1341 sub secret_hidden_html ($) {
1343 return $r->{Cgi}->hidden(-name => $r->{S}{assoc_param_name},
1344 -default => $r->secret_hidden_val());
1347 sub secret_cookie ($) {
1349 my $secret = $r->secret_cookie_val();
1350 return undef if !defined $secret;
1351 #print STDERR "SC\n";
1352 my $cookv = $r->construct_cookie($secret);
1353 #print STDERR "SC=$cookv\n";