3 # This is part of CGI::Auth::Flexible, a perl CGI authentication module.
5 # Copyright (C) 2012,2013,2015 Ian Jackson.
6 # Copyright (C) 2012,2013,2015 Citrix.
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU Affero General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version, with the "CAF Login Exception"
12 # as published by Ian Jackson (version 1, or at your option any
13 # later version) as an Additional Permission.
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU Affero General Public License for more details.
20 # You should have received a copy of the GNU Affero General Public
21 # License and the CAF Login Exception along with this program, in the
22 # file AGPLv3+CAFv1. If not, email Ian Jackson
23 # <ijackson@chiark.greenend.org.uk>.
26 use warnings FATAL => 'all';
28 package CGI::Auth::Flexible;
33 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
38 %EXPORT_TAGS = ( ); # eg: TAG => [ qw!name1 name2! ],
43 use CGI qw/escapeHTML/;
57 #---------- public utilities ----------
59 sub flatten_params ($) {
62 foreach my $k (keys %$p) {
64 foreach my $v (@{ $p->{$k} }) {
71 #---------- default callbacks ----------
73 sub has_a_param ($$) {
75 foreach my $pn (@{ $r->{S}{$cn} }) {
76 return 1 if $r->_ch('get_param',$pn);
84 my $vars = $c->Vars();
86 foreach my $name (keys %$vars) {
87 $p{$name} = [ split "\0", $vars->{$name} ];
92 sub get_cookie_domain ($$$) {
94 my $uri = new URI $r->_ch('get_url');
98 sub login_ok_password ($$) {
100 my $username_params = $r->{S}{username_param_names};
101 my $username = $r->_ch('get_param',$username_params->[0]);
102 my $password = $r->_rp('password_param_name');
103 my $error = $r->_ch('username_password_error', $username, $password);
104 return defined($error) ? (undef,$error) : ($username,undef);
107 sub do_redirect_cgi ($$$$) {
108 my ($c, $r, $new_url, $cookie) = @_;
109 $r->_print($c->header($r->_cgi_header_args($cookie,
110 -status => '303 See other',
111 -location => $new_url)),
112 $r->_ch('gen_start_html',$r->_gt('Redirection')),
113 '<a href="'.escapeHTML($new_url).'">',
114 $r->_gt("If you aren't redirected, click to continue."),
116 $r->_ch('gen_end_html'));
119 sub gen_some_form ($$) {
120 my ($r, $params, $bodyfn) = @_;
121 # Calls $bodyfn->($c,$r) which returns @formbits
125 $pathinfo .= $params->{''}[0] if $params->{''};
126 push @form, ('<form method="POST" action="'.
127 escapeHTML($r->_ch('get_url').$pathinfo).'">');
128 push @form, $bodyfn->($c,$r);
129 foreach my $n (keys %$params) {
131 foreach my $val (@{ $params->{$n} }) {
132 push @form, ('<input type="hidden"'.
133 ' name="'.escapeHTML($n).'"'.
134 ' value="'.escapeHTML($val).'">');
137 push @form, ('</form>');
138 return join "\n", @form;
141 sub gen_plain_login_form ($$) {
142 my ($c,$r, $params) = @_;
143 return $r->gen_some_form($params, sub {
145 push @form, ('<table>');
146 my $sz = 'size="'.$r->{S}{form_entry_size}.'"';
147 foreach my $up (@{ $r->{S}{username_param_names}}) {
148 push @form, ('<tr><td>',$r->_gt(ucfirst $up),'</td>',
149 '<td><input type="text" '.$sz.
150 ' name='.$up.'></td></tr>');
152 push @form, ('<tr><td>'.$r->_gt('Password').'</td>',
153 '<td><input type="password" '.$sz.
154 ' name="'.$r->{S}{password_param_name}.'"></td></tr>');
155 push @form, ('<tr><td colspan="2">',
156 '<input type="submit"'.
157 ' name="'.$r->{S}{dummy_param_name_prefix}.'login"'.
158 ' value="'.$r->_gt('Login').'"></td></tr>',
164 sub gen_postmainpage_form ($$$) {
165 my ($c,$r, $params) = @_;
166 return $r->gen_some_form($params, sub {
168 push @form, ('<input type="submit"',
169 ' name="'.$r->{S}{dummy_param_name_prefix}.'submit"'.
170 ' value="'.$r->_gt('Continue').'">');
175 sub gen_plain_login_link ($$) {
176 my ($c,$r, $params) = @_;
177 my $url = $r->url_with_query_params($params);
178 return ('<a href="'.escapeHTML($url).'">'.
179 $r->_gt('Log in again to continue.').
183 sub gen_srcdump_link_html ($$$$) {
184 my ($c,$r,$anchor,$specval) = @_;
185 my %params = ($r->{S}{srcdump_param_name} => [ $specval ]);
187 escapeHTML($r->url_with_query_params(\%params,'SRCDUMP')).
190 sub gen_plain_licence_link_html ($$) {
192 gen_srcdump_link_html($c,$r, 'GNU Affero GPL with CAF Login Exception',
195 sub gen_plain_source_link_html ($$) {
197 my $msg = 'Source available';
198 $msg .= " to logged-in users" if $r->{S}{srcdump_needlogin};
199 gen_srcdump_link_html($c,$r, $msg, 'source');
202 sub gen_plain_footer_html ($$) {
204 return ('<hr><address>',
205 ("Powered by Free / Libre / Open Source Software".
206 " according to the ".$r->_ch('gen_licence_link_html')."."),
207 $r->_ch('gen_source_link_html').".",
211 #---------- licence and source code ----------
213 sub srcdump_dump ($$$) {
214 my ($c,$r, $thing) = @_;
215 die if $thing =~ m/\W/ || $thing !~ m/\w/;
216 my $path = $r->_get_path('srcdump');
217 my $ctf = new IO::File "$path/$thing.ctype", 'r'
218 or die "$path/$thing.ctype $!";
220 chomp $ct or die "$path/$thing ?";
221 $ctf->close or die "$path/$thing $!";
222 my $df = new IO::File "$path/$thing.data", 'r'
223 or die "$path/$thing.data $!";
224 $r->_ch('dump', $ct, $df);
227 sub dump_plain ($$$$) {
228 my ($c, $r, $ct, $df) = @_;
229 $r->_print($c->header('-type' => $ct));
232 my $got = read $df, $buffer, 65536;
233 die $! unless defined $got;
239 sub srcdump_process_item ($$$$$$) {
240 my ($c, $v, $dumpdir, $item, $outfn, $needlicence, $dirsdone) = @_;
241 if ($v->_ch('srcdump_system_dir', $item)) {
242 $outfn->("srcdump_process_item: srcdump_system_dir, skipping $item");
248 $upwards =~ s#/+\.$##;
249 last unless $upwards =~ m#[^/]#;
250 foreach my $try (@{ $v->{S}{srcdump_vcs_dirs} }) {
251 #print STDERR "TRY $item $upwards $try\n";
252 if (!stat "$upwards/$try") {
253 $!==&ENOENT or $!==&ENOTDIR or die "check $upwards/$try $!";
256 #print STDERR "VCS $item $upwards $try\n";
257 if ($dirsdone->{$upwards}++) {
258 $outfn->("srcdump_process_item: did $upwards,".
262 #print STDERR "VCS $item $upwards $try GO\n";
263 $try =~ m/\w+/ or die;
264 return $v->_ch('srcdump_byvcs', $dumpdir, $upwards, $outfn, lc $&);
266 $upwards =~ s#/*[^/]+$##;
268 return $v->_ch('srcdump_novcs', $dumpdir, $item, $outfn);
271 sub srcdump_novcs ($$$$$) {
272 my ($c, $v, $dumpdir, $item, $outfn) = @_;
273 stat $item or die "$item $!";
275 my $script = 'find -type f -perm +004';
276 foreach my $excl (@{ $v->{S}{srcdump_excludes} }) {
277 $script .= " \\! -name '$excl'";
279 $script .= " -print0";
280 return srcdump_dir_cpio($c,$v,$dumpdir,$item,$outfn,'novcs',$script);
282 return srcdump_file($c,$v,$dumpdir,$item,$outfn);
284 die "$item not file or directory";
288 sub srcdump_byvcs ($$$$$$) {
289 my ($c, $v, $dumpdir, $dir, $outfn, $vcs) = @_;
290 #print STDERR "BYVCS GIT $dir\n";
291 my $script = $v->{S}{"srcdump_vcsscript"}{$vcs};
292 die "no script for vcs $vcs" unless defined $script;
293 return srcdump_dir_cpio($c,$v,$dumpdir,$dir,$outfn,$vcs,$script);
296 sub srcdump_file ($$$$) {
297 my ($c,$v,$dumpdir,$file,$outfn) = @_;
298 my $outfile = $outfn->("srcdump_file saved $file", "src");
299 copy($file,$outfile) or die "$file $outfile $!";
302 sub srcdump_dir_cpio ($$$$$$$) {
303 my ($c,$v,$dumpdir,$dir,$outfn,$how,$script) = @_;
304 my $outfile = $outfn->("srcdump_dir_cpio $how saved $dir", "tar");
305 #print STDERR "CPIO $dir >$script<\n";
307 defined $pid or die $!;
309 $SIG{__DIE__} = sub {
310 print STDERR "CGI::Auth::Flexible srcdump error: $@\n";
313 open STDOUT, ">", $outfile or die "$outfile $!";
314 chdir $dir or die "chdir $dir: $!";
315 exec '/bin/bash','-ec',"
320 cpio -Hustar -o --quiet -0 -R 1000:1000 || \
321 cpio -Hustar -o --quiet -0
326 $!=0; (waitpid $pid, 0) == $pid or die "$!";
327 die "$dir ($how $script) $outfile $?" if $?;
330 sub srcdump_dirscan_prepare ($$) {
332 my $dumpdir = $v->_get_path('srcdump');
333 mkdir $dumpdir or $!==&EEXIST or die "mkdir $dumpdir $!";
334 my $lockf = new IO::File "$dumpdir/generate.lock", 'w+'
335 or die "$dumpdir/generate.lock $!";
336 flock $lockf, LOCK_EX or die "$dumpdir/generate.lock $!";
337 my $needlicence = "$dumpdir/licence.tmp";
338 unlink $needlicence or $!==&ENOENT or die "rm $needlicence $!";
339 if (defined $v->{S}{srcdump_licence_path}) {
340 copy($v->{S}{srcdump_licence_path}, $needlicence)
341 or die "$v->{S}{srcdump_licence_path} $!";
342 $needlicence = undef;
344 unlink <"$dumpdir/s.[a-z][a-z][a-z].*">;
345 my @srcfiles = qw(licence.data manifest.txt);
346 my $srcoutcounter = 'aaa';
348 my $reportfh = new IO::File "$dumpdir/manifest.txt", 'w' or die $!;
350 my ($message, $extension) = @_;
351 if (defined $extension) {
352 my $leaf = "s.$srcoutcounter.$extension";
354 push @srcfiles, $leaf;
355 print $reportfh "$leaf: $message\n" or die $!;
356 return "$dumpdir/$leaf";
358 print $reportfh "none: $message\n" or die $!;
363 foreach my $item ($v->_ch('srcdump_listitems')) {
364 next unless defined $item;
365 if ($item eq '.' && $v->{S}{srcdump_filter_cwd}) {
366 my @bad = grep { !m#^/# } values %INC;
367 die "filtering . from srcdump items and \@INC but already".
368 " included @bad " if @bad;
369 @INC = grep { $_ ne '.' } @INC;
372 if (!lstat "$item") {
373 die "stat $item $!" unless $!==&ENOENT;
374 $outfn->("srcdump_dirscan_prepare stat ENOENT, skipping $item");
378 $item = realpath($item);
379 if (!defined $item) {
380 die "realpath $item $!" unless $!==&ENOENT;
381 $outfn->("srcdump_dirscan_prepare realpath ENOENT,".
385 if (defined $needlicence) {
386 foreach my $try (@{ $v->{S}{srcdump_licence_files} }) {
387 last if copy("$item/$try", $needlicence);
388 $!==&ENOENT or $!==&ENOTDIR or die "copy $item/$try $!";
391 $v->_ch('srcdump_process_item', $dumpdir, $item,
392 $outfn, \$needlicence, \%dirsdone);
395 close $reportfh or die $!;
396 srcdump_install($c,$v, $dumpdir, 'licence', 'text/plain');
398 my @cmd = (qw(sh -ec), 'exec >&2 "$@"', qw(x),
399 qw(tar -zvvcf), "$dumpdir/source.tmp",
400 "-C", $dumpdir, qw( --), @srcfiles);
401 my $r = system(@cmd);
403 print STDERR "CGI::Auth::Flexible tar failed ($r $!) @cmd\n";
406 die "licence file not found" unless defined $needlicence;
407 srcdump_install($c,$v, $dumpdir, 'source', 'application/octet-stream');
408 close $lockf or die $!;
411 sub srcdump_install ($$$$$) {
412 my ($c,$v, $dumpdir, $which, $ctype) = @_;
413 rename "$dumpdir/$which.tmp", "$dumpdir/$which.data"
414 or die "$dumpdir/$which.data $!";
415 my $ctf = new IO::File "$dumpdir/$which.tmp", 'w'
416 or die "$dumpdir/$which.tmp $!";
417 print $ctf $ctype, "\n" or die $!;
418 close $ctf or die $!;
419 rename "$dumpdir/$which.tmp", "$dumpdir/$which.ctype"
420 or die "$dumpdir/$which.ctype $!";
423 #---------- verifier object methods ----------
430 db_dbh => undef, # must have AutoCommit=0, RaiseError=1
432 keys_path => 'caf-keys',
433 srcdump_path => 'caf-srcdump',
438 random_source => '/dev/urandom',
439 secretbits => 128, # bits
440 hash_algorithm => "SHA-256",
441 login_timeout => 86400, # seconds
442 login_form_timeout => 3600, # seconds
443 key_rollover => 86400, # seconds
444 assoc_param_name => 'caf_assochash',
445 dummy_param_name_prefix => 'caf__',
446 cookie_name => "caf_assocsecret",
447 password_param_name => 'password',
448 srcdump_param_name => 'caf_srcdump',
449 username_param_names => [qw(username)],
450 form_entry_size => 60,
451 logout_param_names => [qw(caf_logout)],
452 loggedout_param_names => [qw(caf_loggedout)],
453 promise_check_mutate => 0,
454 get_param => sub { $_[0]->param($_[2]) },
455 get_params => sub { $_[1]->get_params() },
456 get_path_info => sub { $_[0]->path_info() },
457 get_cookie => sub { $_[0]->cookie($_[1]->{S}{cookie_name}) },
458 get_method => sub { $_[0]->request_method() },
459 is_https => sub { !!$_[0]->https() },
460 get_url => sub { $_[0]->url(); },
461 is_login => sub { defined $_[1]->_rp('password_param_name') },
462 login_ok => \&login_ok_password,
463 username_password_error => sub { die },
464 is_logout => sub { $_[1]->has_a_param('logout_param_names') },
465 is_loggedout => sub { $_[1]->has_a_param('loggedout_param_names') },
466 handle_divert => sub { return 0 },
467 do_redirect => \&do_redirect_cgi, # this hook is allowed to throw
469 get_cookie_domain => \&get_cookie_domain,
471 gen_start_html => sub { $_[0]->start_html($_[2]); },
472 gen_footer_html => \&gen_plain_footer_html,
473 gen_licence_link_html => \&gen_plain_licence_link_html,
474 gen_source_link_html => \&gen_plain_source_link_html,
475 gen_end_html => sub { $_[0]->end_html(); },
476 gen_login_form => \&gen_plain_login_form,
477 gen_login_link => \&gen_plain_login_link,
478 gen_postmainpage_form => \&gen_postmainpage_form,
479 srcdump_needlogin => 0,
480 srcdump_dump => \&srcdump_dump,
481 srcdump_prepare => \&srcdump_dirscan_prepare,
482 srcdump_licence_path => undef,
483 srcdump_licence_files => [qw(AGPLv3+CAFv1 CGI/Auth/Flexible/AGPLv3+CAFv1)],
484 srcdump_listitems => sub { (@INC, $ENV{'SCRIPT_FILENAME'}, $0); },
485 srcdump_filter_cwd => 1,
486 srcdump_system_dir => sub {
487 $_[2] =~ m#^/etc/|^/usr/(?!local/)(?!lib/cgi)#;
489 srcdump_process_item => \&srcdump_process_item,
490 srcdump_vcs_dirs => [qw(.git .hg .bzr .svn)],
491 srcdump_vcsscript => {git => "
493 git ls-files -z --others --exclude-from=.gitignore
494 find .git ! -name \\*~ -print0
496 srcdump_byvcs => \&srcdump_byvcs,
497 srcdump_novcs => \&srcdump_novcs,
498 srcdump_excludes => [qw(*~ *.bak *.tmp), '#*#'],
499 dump => \&dump_plain,
500 gettext => sub { gettext($_[2]); },
501 print => sub { print $_[2] or die $!; },
502 debug => sub { }, # like print; msgs contain trailing \n
507 while (($k,$v,@_) = @_) {
508 die "unknown setting $k" unless
509 $k =~ m/^promise_/ or
510 exists $verifier->{S}{$k};
511 $verifier->{S}{$k} = $v;
513 $verifier->{S}{db_setup_stmts} //=
514 ["CREATE TABLE $verifier->{S}{db_prefix}_assocs (".
515 " assochash VARCHAR PRIMARY KEY,".
516 " username VARCHAR NOT NULL,".
517 " last INTEGER NOT NULL".
520 "CREATE INDEX $verifier->{S}{db_prefix}_assocs_timeout_index".
521 " ON $verifier->{S}{db_prefix}_assocs".
524 bless $verifier, $class;
525 $verifier->_dbopen();
526 $verifier->_ch('srcdump_prepare');
530 sub _db_setup_do ($$) {
534 $v->_db_transaction(sub {
535 local ($dbh->{PrintError}) = 0;
546 $dbh = $v->{S}{db_dbh};
548 die if $dbh->{AutoCommit};
549 die unless $dbh->{RaiseError};
551 $v->{S}{db_dsn} ||= "dbi:SQLite:dbname=".$v->_get_path('db');
552 my $dsn = $v->{S}{db_dsn};
555 $dbh = DBI->connect($dsn, $v->{S}{db_user},
556 $v->{S}{db_password}, {
559 ShowErrorStatement => 1,
562 die "$dsn $! ?" unless $dbh;
566 foreach my $stmt (@{ $v->{S}{db_setup_stmts} }) {
567 $v->_db_setup_do($stmt);
579 sub _db_transaction ($$) {
584 #print STDERR "DT entry\n";
586 #print STDERR "DT loop\n";
589 #print STDERR "DT fn ok\n";
592 #print STDERR "DT fn error\n";
593 { local ($@); $dbh->rollback(); }
594 #print STDERR "DT fn throwing\n";
597 #print STDERR "DT fn eval ok\n";
600 #print STDERR "DT commit ok\n";
603 #print STDERR "DT commit eval ok ",Dumper($rv);
606 #print STDERR "DT commit throw?\n";
607 die $@ if !--$retries;
608 #print STDERR "DT loop again\n";
612 #---------- request object methods ----------
615 my ($classbase, $cgi, @extra) = @_;
616 if (!ref $classbase) {
617 $classbase = $classbase->new_verifier(@extra);
623 S => $classbase->{S},
624 Dbh => $classbase->{Dbh},
627 bless $r, ref $classbase;
630 sub _ch ($$@) { # calls an application hook
631 my ($r,$methname, @args) = @_;
632 my $methfunc = $r->{S}{$methname};
633 die "$methname ?" unless $methfunc;
634 return $methfunc->($r->{Cgi}, $r, @args);
639 my $pn = $r->{S}{$pnvb};
640 my $p = scalar $r->_ch('get_param',$pn)
645 $r->_ch('debug',@args);
649 my ($r,$keybase) = @_;
650 my $leaf = $r->{S}{"${keybase}_path"};
651 return $r->_absify_path($leaf);
654 sub _absify_path ($$) {
656 return $leaf if $leaf =~ m,^/,;
657 my $dir = $v->{S}{dir};
658 die "relying on cwd by default ?! set dir" unless defined $dir;
662 sub _gt ($$) { my ($r, $t) = @_; return $r->_ch('gettext',$t); }
663 sub _print ($$) { my ($r, @t) = @_; return $r->_ch('print', join '', @t); }
665 sub construct_cookie ($$$) {
666 my ($r, $cooks) = @_;
667 return undef unless $cooks;
670 -name => $r->{S}{cookie_name},
672 -path => $r->{S}{cookie_path},
673 -domain => $r->_ch('get_cookie_domain'),
674 -expires => '+'.$r->{S}{login_timeout}.'s',
675 -secure => $r->{S}{encrypted_only}
677 my $cookie = $c->cookie(@ca);
678 #print STDERR "CC $r $c $cooks $cookie (@ca).\n";
682 # pages/param-sets are
683 # n normal non-mutating page
684 # r retrieval of information for JS etc., non-mutating
686 # u update of information by JS etc., mutating
689 # O "you have just logged out" page load
692 # - no value supplied (represented in code as $cookt='')
693 # n, nN value not in our db
694 # t, tN temporary value (in our db, no logged in user yet)
695 # y, yN value corresponds to logged-in user
696 # and, aggregated conditions:
697 # a, aN anything including -
699 # if N differs the case applies only when the two values differ
700 # (eg, a1 y2 does not apply when the logged-in value is supplied twice)
702 # "stale session" means request originates from a page from a login
703 # session which has been revoked (eg by logout); "cleared session"
704 # means request originates from a browser which has a different (or
707 # Case analysis, cookie mode, app promises re mutate:
708 # cook parm meth form
710 # any - POST nrmuoi bug or attack, fail
711 # any - GET rmuoi bug or attack, fail
712 # any any GET muoi bug or attack, fail
714 # - - GET O "just logged out" page
715 # (any other) O bug or attack, fail
717 # a1 a2 POST o logout
718 # if a1 is valid, revoke it
719 # if a2 is valid, revoke it
721 # redirect to "just logged out" page
722 # (which contains link to login form)
724 # - t POST i complain about cookies being disabled
725 # (with link to login form)
727 # t1 t1 POST i login (or switch user)
729 # show new login form
731 # upgrade t1 to y1 in our db (setting username)
732 # redirect to GET of remaining params
734 # y1 a2 POST i complain about stale login form
736 # show new login form
738 # (other) POST i complain about stale login form
739 # show new login form
741 # t1 a2 ANY nrmu treat as - a2 ANY
743 # y - GET n cross-site link
746 # y y GET nr fine, show page or send data
747 # y y POST nrmu mutation is OK, do operation
749 # y1 y2 GET nr request from stale page
750 # do not revoke y2 as not RESTful
753 # y1 y2 POST nrmu request from stale page
757 # y nt GET n intra-site link from stale page,
758 # treat as cross-site link, show data
760 # y nt POST n m intra-site form submission from stale page
761 # show "session interrupted"
762 # with link to main data page
764 # y nt GET r intra-site request from stale page
767 # y nt POST r u intra-site request from stale page
770 # -n y2 GET nr intra-site link from cleared session
771 # do not revoke y2 as not RESTful
774 # -n y2 POST nrmu request from cleared session
776 # treat as -/n n POST
778 # -nt -nt GET n cross-site link but user not logged in
779 # show login form with redirect to orig params
780 # generate fresh cookie
782 # -nt nt GET rmu user not logged in
785 # -nt nt POST n m user not logged in
788 # -nt nt POST r u user not logged in
791 sub _check_divert_core ($) {
794 my $srcdump = $r->_rp('srcdump_param_name');
796 die if $srcdump =~ m/\W/;
798 Kind => 'SRCDUMP-'.uc $srcdump,
804 if ($srcdump || !$r->{S}{srcdump_needlogin}) {
808 my $cooksraw = $r->_ch('get_cookie');
809 my $cooks = $r->_unblind($cooksraw);
811 if ($r->{S}{encrypted_only} && !$r->_ch('is_https')) {
812 return ({ Kind => 'REDIRECT-HTTPS',
813 Message => $r->_gt("Redirecting to secure server..."),
818 my $meth = $r->_ch('get_method');
819 my $parmhraw = $r->_rp('assoc_param_name');
820 my $parmh = $r->_unblind($parmhraw);
821 my $cookh = defined $cooks ? $r->hash($cooks) : undef;
823 my ($cookt,$cooku) = $r->_identify($cookh, $cooks);
824 my $parms = (defined $cooks && defined $parmh && $parmh eq $cookh)
826 my ($parmt) = $r->_identify($parmh, $parms);
828 $r->_debug("_c_d_c cookt=$cookt parmt=$parmt\n");
830 if ($r->_ch('is_logout')) {
833 $r->_db_revoke($cookh);
834 $r->_db_revoke($parmh);
835 return ({ Kind => 'REDIRECT-LOGGEDOUT',
836 Message => $r->_gt("Logging out..."),
839 $r->{S}{loggedout_param_names}[0] => [ 1 ],
842 if ($r->_ch('is_loggedout')) {
843 die unless $meth eq 'GET';
844 die if $cookt eq 'y';
846 return ({ Kind => 'SMALLPAGE-LOGGEDOUT',
847 Message => $r->_gt("You have been logged out."),
851 if ($r->_ch('is_login')) {
854 if (!$cookt && $parmt eq 'n') {
855 return ({ Kind => 'SMALLPAGE-NOCOOKIE',
856 Message => $r->_gt("You do not seem to have cookies".
857 " enabled. You must enable cookies".
858 " as we use them for login."),
859 _CookieRaw => $r->_fresh_secret(),
860 Params => $r->chain_params() })
862 if (!$cookt || $cookt eq 'n' || $cookh ne $parmh) {
863 $r->_db_revoke($cookh);
864 return ({ Kind => 'LOGIN-STALE',
865 Message => $r->_gt("Stale session;".
866 " you need to log in again."),
867 _CookieRaw => $r->_fresh_secret(),
870 die unless $parmt eq 't' || $parmt eq 'y';
871 my ($username, $login_errormessage) = $r->_ch('login_ok');
872 unless (defined $username && length $username) {
873 $login_errormessage = $r->_gt("Incorrect username/password.")
874 if !$login_errormessage;
875 return ({ Kind => 'LOGIN-BAD',
876 Message => $login_errormessage,
877 _CookieRaw => $cooks,
878 Params => $r->chain_params() })
880 $r->_db_record_login_ok($parmh,$username);
881 return ({ Kind => 'REDIRECT-LOGGEDIN',
882 Message => $r->_gt("Logging in..."),
883 _CookieRaw => $cooks,
884 Params => $r->chain_params() });
890 if ($cookt eq 'y' && $parmt eq 'y' && $cookh ne $parmh) {
891 $r->_db_revoke($parmh) if $meth eq 'POST';
896 die unless !$cookt || $cookt eq 'n';
897 die unless !$parmt || $parmt eq 't' || $parmt eq 'n' || $parmt eq 'y';
898 my $news = $r->_fresh_secret();
899 if ($meth eq 'GET') {
900 return ({ Kind => 'LOGIN-INCOMINGLINK',
901 Message => $r->_gt("You need to log in."),
903 Params => $r->chain_params() });
905 $r->_db_revoke($parmh);
906 return ({ Kind => 'LOGIN-FRESH',
907 Message => $r->_gt("You need to log in."),
913 if (!$r->{S}{promise_check_mutate}) {
914 if ($meth ne 'POST') {
915 return ({ Kind => 'MAINPAGEONLY',
916 Message => $r->_gt('Entering via cross-site link.'),
917 _CookieRaw => $cooks,
919 # NB caller must then ignore params & path!
920 # if this is too hard they can spit out a small form
921 # with a "click to continue"
925 die unless $cookt eq 'y';
926 unless (($r->{S}{promise_check_mutate} && $meth eq 'GET')
928 if ($parmt eq 't' || $parmt eq 'n') {
929 return ({ Kind => 'STALE',
930 Message => $r->_gt("Login session interrupted."),
931 _CookieRaw => $cooks,
934 die unless $parmt eq 'y';
935 die unless $cookh eq $parmh;
937 $r->_db_update_last($cooku,$parmh);
943 $r->{ParmT} = $parmt;
944 $r->{AssocRaw} = $cooks;
945 $r->{UserOK} = $cooku;
947 #print STDERR "C-D-C OK\n";
951 sub chain_params ($) {
953 my %p = %{ $r->_ch('get_params') };
954 foreach my $pncn (keys %{ $r->{S} }) {
956 if ($pncn =~ m/_param_name$/) {
957 my $name = $r->{S}{$pncn};
958 die "$pncn ?" if ref $name;
960 } elsif ($pncn =~ m/_param_names$/) {
961 $names = $r->{S}{$pncn};
965 foreach my $name (@$names) {
969 my $dummy_prefix = $r->{S}{dummy_param_name_prefix};
970 foreach my $name (grep /^$dummy_prefix/, keys %p) {
973 die if exists $p{''};
974 $p{''} = [ $r->_ch('get_path_info') ];
980 # returns ($t,$username)
981 # where $t is one of "t" "y" "n", or "" (for -)
982 # either $s must be undef, or $h eq $r->hash($s)
984 #print STDERR "_identify\n";
985 return '' unless defined $h && length $h;
986 #print STDERR "_identify h=$h s=".(defined $s ? $s : '<undef>')."\n";
990 $dbh->do("DELETE FROM $r->{S}{db_prefix}_assocs".
991 " WHERE last < ?", {},
992 time - $r->{S}{login_timeout});
994 my $row = $dbh->selectrow_arrayref("SELECT username, last".
995 " FROM $r->{S}{db_prefix}_assocs".
996 " WHERE assochash = ?", {}, $h);
998 #print STDERR "_identify h=$h s=$s YES @$row\n";
999 my ($nusername, $nlast) = @$row;
1000 return ('y', $nusername);
1003 # Well, it's not in the database. But maybe it's a hash of a
1006 return 'n' unless defined $s;
1008 my ($keyt, $signature, $message, $noncet, $nonce) =
1009 $s =~ m/^(\d+)\.(\w+)\.((\d+)\.(\w+))$/ or die;
1011 return 'n' if time > $noncet + $r->{S}{login_form_timeout};
1013 #print STDERR "_identify noncet=$noncet ok\n";
1015 my $keys = $r->_open_keys();
1016 while (my ($rkeyt, $rkey, $line) = $r->_read_key($keys)) {
1017 #print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey\n";
1018 last if $rkeyt < $keyt; # too far down in the file
1019 my $trysignature = $r->_hmac($rkey, $message);
1020 #print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey try=$trysignature\n";
1021 return 't' if $trysignature eq $signature;
1024 #print STDERR "_identify NO\n";
1026 $keys->error and die $!;
1030 sub _db_revoke ($$) {
1031 # revokes $h if it's valid; no-op if it's not
1034 my $dbh = $r->{Dbh};
1036 $dbh->do("DELETE FROM $r->{S}{db_prefix}_assocs".
1037 " WHERE assochash = ?", {}, $h);
1040 sub _db_record_login_ok ($$$) {
1041 my ($r,$h,$user) = @_;
1043 my $dbh = $r->{Dbh};
1044 $dbh->do("INSERT INTO $r->{S}{db_prefix}_assocs".
1045 " (assochash, username, last) VALUES (?,?,?)", {},
1049 sub _db_update_last ($$) {
1050 # revokes $h if it's valid; no-op if it's not
1051 my ($r,$user,$h) = @_;
1052 my $dbh = $r->{Dbh};
1053 $dbh->do("UPDATE $r->{S}{db_prefix}_assocs".
1055 " WHERE username = ? AND assochash = ?", {},
1059 sub check_divert ($) {
1061 if (exists $r->{Divert}) {
1062 return $r->{Divert};
1064 my $dbh = $r->{Dbh};
1065 $r->{Divert} = $r->_db_transaction(sub { $r->_check_divert_core(); });
1068 my $divert = $r->{Divert};
1069 my $cookraw = $divert && $divert->{_CookieRaw};
1071 $divert->{CookieSecret} = $r->_blind($cookraw);
1072 $divert->{Params}{$r->{S}{assoc_param_name}} = [
1073 $r->_blind($r->hash($cookraw))
1077 $r->_debug(Data::Dumper->Dump([$divert],[qw(divert)]));
1081 sub get_divert ($) {
1083 die "unchecked" unless exists $r->{Divert};
1084 return $r->{Divert};
1087 sub get_username ($) {
1089 my $divert = $r->get_divert();
1090 return undef if $divert;
1091 return $r->{UserOK};
1094 sub url_with_query_params ($$;$) {
1095 my ($r, $params, $nonpagetype) = @_;
1096 #print STDERR "PARAMS ",Dumper($params);
1097 my $uri = URI->new($r->_ch('get_url'));
1098 $uri->path($uri->path() . $params->{''}[0]) if $params->{''};
1099 my @flatparams = flatten_params($params);
1100 if (defined $nonpagetype && $r->need_add_hidden('GET',$nonpagetype)) {
1101 push @flatparams, $r->{S}{assoc_param_name}, $r->secret_hidden_val();
1103 $uri->query_form(@flatparams);
1104 return $uri->as_string();
1107 sub _cgi_header_args ($$@) {
1108 my ($r, $cookie, @ha) = @_;
1109 unshift @ha, qw(-type text/html);
1110 push @ha, (-cookie => $cookie) if defined $cookie;
1111 #print STDERR "_cgi_header_args ",join('|',@ha),".\n";
1118 my ($divert) = $r->check_divert();
1119 return 1 if !$divert;
1121 my $handled = $r->_ch('handle_divert',$divert);
1122 return 0 if $handled;
1124 my $kind = $divert->{Kind};
1125 my $cookiesecret = $divert->{CookieSecret};
1126 my $params = $divert->{Params};
1127 my $cookie = $r->construct_cookie($cookiesecret);
1129 if ($kind =~ m/^SRCDUMP-(\w+)$/) {
1130 $r->_ch('srcdump_dump', (lc $1));
1134 if ($kind =~ m/^REDIRECT-/) {
1135 # for redirects, we honour stored Params and Cookie,
1136 # as we would for non-divert
1137 if ($kind eq 'REDIRECT-LOGGEDOUT') {
1138 } elsif ($kind =~ m/REDIRECT-(?:LOGGEDIN|HTTPS)/) {
1142 my $new_url = $r->url_with_query_params($params);
1143 if ($kind eq 'REDIRECT-HTTPS') {
1144 my $uri = URI->new($new_url);
1145 die unless $uri->scheme eq 'http';
1146 $uri->scheme('https');
1147 $new_url = $uri->as_string();
1149 $r->_ch('do_redirect',$new_url, $cookie);
1154 if ($kind =~ m/^LOGIN-/) {
1155 $title = $r->_gt('Login');
1156 push @body, $divert->{Message};
1157 push @body, $r->_ch('gen_login_form', $params);
1158 } elsif ($kind =~ m/^SMALLPAGE-/) {
1159 $title = $r->_gt('Not logged in');
1160 push @body, $divert->{Message};
1161 push @body, $r->_ch('gen_login_link', $params);
1162 } elsif ($kind =~ m/^STALE/) {
1163 $title = $r->_gt('Re-entering secure site.');
1164 push @body, $divert->{Message};
1165 push @body, $r->_ch('gen_postmainpage_form', $params);
1166 } elsif ($kind =~ m/^MAINPAGEONLY$/) {
1167 $title = $r->_gt('Entering secure site.');
1168 push @body, $divert->{Message};
1169 push @body, $r->_ch('gen_postmainpage_form', $params);
1174 $r->_print($r->{Cgi}->header($r->_cgi_header_args($cookie)),
1175 $r->_ch('gen_start_html',$title),
1177 $r->_ch('gen_footer_html'),
1178 $r->_ch('gen_end_html'))));
1183 my ($r, $bytes) = @_;
1185 my $rsf = $v->{RandomHandle};
1186 my $rsp = $r->{S}{random_source};
1188 $v->{RandomHandle} = $rsf = new IO::File $rsp, '<' or die "$rsp $!";
1189 #print STDERR "RH $rsf\n";
1193 read($rsf,$bin,$bytes) == $bytes or die "$rsp $!";
1194 my $out = unpack "H*", $bin;
1195 #print STDERR "_random out $out\n";
1199 sub _blind_len ($$) {
1201 return length($str =~ y/0-9a-f//cdr);
1204 sub _blind_combine ($$$) {
1205 my ($r, $in, $mask) = @_;
1206 my @mask = split //, $mask;
1208 my $m = shift @mask;
1209 sprintf "%x", hex($m) ^ hex($&);
1216 return $in unless $in;
1217 my $l = $r->_blind_len($in);
1218 my $mask = $r->_random(($l+1)>>1);
1219 $mask = substr $mask, 0, $l;
1220 my $blound = $r->_blind_combine($in, $mask);
1221 return "$blound.$mask";
1226 return $in unless $in;
1227 my ($blound,$mask) = ($in =~ m#^(.*)\.([0-9a-f]+)$#) or die "$in ?";
1228 my $l = $r->_blind_len($blound);
1229 $l == length($mask) or die "$in ?";
1230 return $r->_blind_combine($blound, $mask);
1233 sub _random_key ($) {
1235 #print STDERR "_random_key\n";
1236 my $bytes = ($r->{S}{secretbits} + 7) >> 3;
1237 return $r->_random($bytes);
1240 sub _read_key ($$) {
1241 my ($r, $keys) = @_;
1242 # returns $gen_time_t, $key_value_in_hex, $complete_line
1244 my ($gen, $k) = m/^(\d+) (\S+)$/ or die "$_ ?";
1245 my $age = time - $gen;
1246 next if $age > $r->{S}{key_rollover} &&
1247 $age > $r->{S}{login_form_timeout}*2;
1248 return ($gen, $k, $_);
1253 sub _open_keys ($) {
1255 my $spath = $r->_get_path('keys');
1257 #print STDERR "_open_keys\n";
1258 my $keys = new IO::File $spath, 'r+';
1260 #print STDERR "_open_keys open\n";
1261 stat $keys or die $!; # NB must not disturb stat _
1262 my $size = (stat _)[7];
1263 my $age = time - (stat _)[9];
1264 #print STDERR "_open_keys open size=$size age=$age\n";
1266 if $size && $age <= $r->{S}{key_rollover} / 2;
1267 #print STDERR "_open_keys open bad\n";
1269 # file doesn't exist, or is empty or too old
1271 #print STDERR "_open_keys closed\n";
1272 die "$spath $!" unless $!==&ENOENT;
1273 # doesn't exist, so create it just so we can lock it
1274 $keys = new IO::File $spath, 'a+';
1275 die "$keys $!" unless $keys;
1276 stat $keys or die $!; # NB must not disturb stat _
1277 my $size = (stat _)[7];
1278 #print STDERR "_open_keys created size=$size\n";
1279 next if $size; # oh someone else has done it, reopen and read it
1281 # file now exists is empty or too old, we must try to replace it
1282 my $our_inum = (stat _)[1]; # last use of that stat _
1283 flock $keys, LOCK_EX or die "$spath $!";
1284 stat $spath or die "$spath $!";
1285 my $path_inum = (stat _)[1];
1286 #print STDERR "_open_keys locked our=$our_inum path=$path_inum\n";
1287 next if $our_inum != $path_inum; # someone else has done it
1288 # We now hold the lock!
1289 #print STDERR "_open_keys creating\n";
1290 my $newkeys = new IO::Handle;
1291 sysopen $newkeys, "$spath.new", O_CREAT|O_TRUNC|O_WRONLY, 0600
1292 or die "$spath.new $!";
1293 # we add the new key to the front which means it's always sorted
1294 print $newkeys time, ' ', $r->_random_key(), "\n" or die $!;
1295 while (my ($gen,$key,$line) = $r->_read_key($keys)) {
1296 #print STDERR "_open_keys copy1\n";
1297 print $newkeys, $line or die $!;
1299 $keys->error and die $!;
1300 close $newkeys or die "$spath.new $!";
1301 rename "$spath.new", "$spath" or die "$spath: $!";
1302 #print STDERR "_open_keys installed\n";
1303 # that rename effective unlocks, since it makes the name refer
1304 # to the new file which we haven't locked
1305 # we go round again opening the file at the beginning
1306 # so that our caller gets a fresh handle onto the existing key file
1310 sub _fresh_secret ($) {
1312 #print STDERR "_fresh_secret\n";
1314 my $keys = $r->_open_keys();
1315 my ($keyt, $key) = $r->_read_key($keys);
1316 die unless defined $keyt;
1318 my $nonce = $r->_random_key();
1320 my $message = "$noncet.$nonce";
1322 my $signature = $r->_hmac($key, $message);
1323 my $secret = "$keyt.$signature.$message";
1324 #print STDERR "FRESH $secret\n";
1329 my ($r, $keyhex, $message) = @_;
1330 my $keybin = pack "H*", $keyhex;
1331 my $alg = $r->{S}{hash_algorithm};
1332 #print STDERR "hmac $alg\n";
1333 my $base = new Digest $alg;
1334 #print STDERR "hmac $alg $base\n";
1335 my $digest = new Digest::HMAC $keybin, $base;
1336 #print STDERR "hmac $alg $base $digest\n";
1337 $digest->add($message);
1338 return $digest->hexdigest();
1342 my ($r, $message) = @_;
1343 my $alg = $r->{S}{hash_algorithm};
1344 #print STDERR "hash $alg\n";
1345 my $digest = new Digest $alg;
1346 $digest->add($message);
1347 return $digest->hexdigest();
1350 sub _assert_checked ($) {
1352 die "unchecked" unless exists $r->{Divert};
1357 my $meth = $r->_ch('get_method');
1358 return $meth eq 'POST';
1361 sub _must_be_post ($) {
1363 my $meth = $r->_ch('get_method');
1364 die "mutating non-POST" if $meth ne 'POST';
1367 sub check_mutate ($) {
1369 $r->_assert_checked();
1370 die if $r->{Divert};
1371 $r->_must_be_post();
1374 our %_resource_get_needs_secret_hidden =
1375 (map { $_ => 0 } qw(PAGE FRAME IFRAME SRCDUMP STYLESHEET FAVICON ROBOTS),
1376 map { $_ => 1 } qw(IMAGE SCRIPT AJAX-XML AJAX-JSON AJAX-OTHER));
1378 sub update_get_need_add_hidden ($$;$) {
1379 my ($r, $reqtype, $value, $force) = @_;
1381 ? ($r->{GetNeedsSecretHidden} ||= { })
1382 : \%_resource_get_needs_secret_hidden;
1383 return if !$force &&
1384 (exists $_resource_get_needs_secret_hidden{$reqtype} ||
1385 exists $hash->{$reqtype});
1386 $hash->{$reqtype} = $value;
1389 sub need_add_hidden ($$) {
1390 my ($r, $method, $reqtype) = @_;
1391 return 1 if $method ne 'GET';
1393 my $ent = $r->{GetNeedsSecretHidden}{$reqtype};
1394 return $ent if defined $ent;
1396 my $ent = $_resource_get_needs_secret_hidden{$reqtype};
1397 return $ent if defined $ent;
1398 die "unsupported nonpage GET type $reqtype";
1401 sub check_nonpage ($$) {
1402 my ($r, $reqtype) = @_;
1403 $r->_assert_checked();
1404 return unless $r->resource_get_needs_secret_hidden($reqtype);
1405 return if $r->{ParmT} eq 'y';
1406 die "missing hidden secret parameter on nonpage request $reqtype";
1409 #---------- output ----------
1411 sub secret_cookie_val ($) {
1413 $r->_assert_checked();
1414 return defined $r->{AssocRaw} ? $r->_blind($r->{AssocRaw}) : '';
1417 sub secret_hidden_val ($) {
1419 $r->_assert_checked();
1420 return defined $r->{AssocRaw} ? $r->_blind($r->hash($r->{AssocRaw})) : '';
1423 sub secret_hidden_html ($) {
1425 return $r->{Cgi}->hidden(-name => $r->{S}{assoc_param_name},
1426 -default => $r->secret_hidden_val());
1429 sub secret_cookie ($) {
1431 my $secret = $r->secret_cookie_val();
1432 return undef if !defined $secret;
1433 #print STDERR "SC\n";
1434 my $cookv = $r->construct_cookie($secret);
1435 #print STDERR "SC=$cookv\n";