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 gen_srcdump_link_html($c,$r, 'Source available', 'source');
200 sub gen_plain_footer_html ($$) {
202 return ('<hr><address>',
203 ("Powered by Free / Libre / Open Source Software".
204 " according to the ".$r->_ch('gen_licence_link_html')."."),
205 $r->_ch('gen_source_link_html').".",
209 #---------- licence and source code ----------
211 sub srcdump_dump ($$$) {
212 my ($c,$r, $thing) = @_;
213 die if $thing =~ m/\W/ || $thing !~ m/\w/;
214 my $path = $r->_get_path('srcdump');
215 my $ctf = new IO::File "$path/$thing.ctype", 'r'
216 or die "$path/$thing.ctype $!";
218 chomp $ct or die "$path/$thing ?";
219 $ctf->close or die "$path/$thing $!";
220 my $df = new IO::File "$path/$thing.data", 'r'
221 or die "$path/$thing.data $!";
222 $r->_ch('dump', $ct, $df);
225 sub dump_plain ($$$$) {
226 my ($c, $r, $ct, $df) = @_;
227 $r->_print($c->header('-type' => $ct));
230 my $got = read $df, $buffer, 65536;
231 die $! unless defined $got;
237 sub srcdump_process_item ($$$$$$) {
238 my ($c, $v, $dumpdir, $item, $outfn, $needlicence, $dirsdone) = @_;
239 if ($v->_ch('srcdump_system_dir', $item)) {
240 $outfn->("srcdump_process_item: srcdump_system_dir, skipping $item");
246 $upwards =~ s#/+\.$##;
247 last unless $upwards =~ m#[^/]#;
248 foreach my $try (@{ $v->{S}{srcdump_vcs_dirs} }) {
249 #print STDERR "TRY $item $upwards $try\n";
250 if (!stat "$upwards/$try") {
251 $!==&ENOENT or $!==&ENOTDIR or die "check $upwards/$try $!";
254 #print STDERR "VCS $item $upwards $try\n";
255 if ($dirsdone->{$upwards}++) {
256 $outfn->("srcdump_process_item: did $upwards,".
260 #print STDERR "VCS $item $upwards $try GO\n";
261 $try =~ m/\w+/ or die;
262 return $v->_ch('srcdump_byvcs', $dumpdir, $upwards, $outfn, lc $&);
264 $upwards =~ s#/*[^/]+$##;
266 return $v->_ch('srcdump_novcs', $dumpdir, $item, $outfn);
269 sub srcdump_novcs ($$$$$) {
270 my ($c, $v, $dumpdir, $item, $outfn) = @_;
271 stat $item or die "$item $!";
273 my $script = 'find -type f -perm +004';
274 foreach my $excl (@{ $v->{S}{srcdump_excludes} }) {
275 $script .= " \\! -name '$excl'";
277 $script .= " -print0";
278 return srcdump_dir_cpio($c,$v,$dumpdir,$item,$outfn,'novcs',$script);
280 return srcdump_file($c,$v,$dumpdir,$item,$outfn);
282 die "$item not file or directory";
286 sub srcdump_byvcs ($$$$$$) {
287 my ($c, $v, $dumpdir, $dir, $outfn, $vcs) = @_;
288 #print STDERR "BYVCS GIT $dir\n";
289 my $script = $v->{S}{"srcdump_vcsscript"}{$vcs};
290 die "no script for vcs $vcs" unless defined $script;
291 return srcdump_dir_cpio($c,$v,$dumpdir,$dir,$outfn,$vcs,$script);
294 sub srcdump_file ($$$$) {
295 my ($c,$v,$dumpdir,$file,$outfn) = @_;
296 my $outfile = $outfn->("srcdump_file saved $file", "src");
297 copy($file,$outfile) or die "$file $outfile $!";
300 sub srcdump_dir_cpio ($$$$$$$) {
301 my ($c,$v,$dumpdir,$dir,$outfn,$how,$script) = @_;
302 my $outfile = $outfn->("srcdump_dir_cpio $how saved $dir", "tar");
303 #print STDERR "CPIO $dir >$script<\n";
305 defined $pid or die $!;
307 $SIG{__DIE__} = sub {
308 print STDERR "CGI::Auth::Flexible srcdump error: $@\n";
311 open STDOUT, ">", $outfile or die "$outfile $!";
312 chdir $dir or die "chdir $dir: $!";
313 exec '/bin/bash','-ec',"
318 cpio -Hustar -o --quiet -0 -R 1000:1000 || \
319 cpio -Hustar -o --quiet -0
324 $!=0; (waitpid $pid, 0) == $pid or die "$!";
325 die "$dir ($how $script) $outfile $?" if $?;
328 sub srcdump_dirscan_prepare ($$) {
330 my $dumpdir = $v->_get_path('srcdump');
331 mkdir $dumpdir or $!==&EEXIST or die "mkdir $dumpdir $!";
332 my $lockf = new IO::File "$dumpdir/generate.lock", 'w+'
333 or die "$dumpdir/generate.lock $!";
334 flock $lockf, LOCK_EX or die "$dumpdir/generate.lock $!";
335 my $needlicence = "$dumpdir/licence.tmp";
336 unlink $needlicence or $!==&ENOENT or die "rm $needlicence $!";
337 if (defined $v->{S}{srcdump_licence_path}) {
338 copy($v->{S}{srcdump_licence_path}, $needlicence)
339 or die "$v->{S}{srcdump_licence_path} $!";
340 $needlicence = undef;
342 unlink <"$dumpdir/s.[a-z][a-z][a-z].*">;
343 my @srcfiles = qw(licence.data manifest.txt);
344 my $srcoutcounter = 'aaa';
346 my $reportfh = new IO::File "$dumpdir/manifest.txt", 'w' or die $!;
348 my ($message, $extension) = @_;
349 if (defined $extension) {
350 my $leaf = "s.$srcoutcounter.$extension";
352 push @srcfiles, $leaf;
353 print $reportfh "$leaf: $message\n" or die $!;
354 return "$dumpdir/$leaf";
356 print $reportfh "none: $message\n" or die $!;
361 foreach my $item ($v->_ch('srcdump_listitems')) {
362 next unless defined $item;
363 if ($item eq '.' && $v->{S}{srcdump_filter_cwd}) {
364 my @bad = grep { !m#^/# } values %INC;
365 die "filtering . from srcdump items and \@INC but already".
366 " included @bad " if @bad;
367 @INC = grep { $_ ne '.' } @INC;
370 if (!lstat "$item") {
371 die "stat $item $!" unless $!==&ENOENT;
372 $outfn->("srcdump_dirscan_prepare stat ENOENT, skipping $item");
376 $item = realpath($item);
377 if (!defined $item) {
378 die "realpath $item $!" unless $!==&ENOENT;
379 $outfn->("srcdump_dirscan_prepare realpath ENOENT,".
383 if (defined $needlicence) {
384 foreach my $try (@{ $v->{S}{srcdump_licence_files} }) {
385 last if copy("$item/$try", $needlicence);
386 $!==&ENOENT or $!==&ENOTDIR or die "copy $item/$try $!";
389 $v->_ch('srcdump_process_item', $dumpdir, $item,
390 $outfn, \$needlicence, \%dirsdone);
393 close $reportfh or die $!;
394 srcdump_install($c,$v, $dumpdir, 'licence', 'text/plain');
396 my @cmd = (qw(sh -ec), 'exec >&2 "$@"', qw(x),
397 qw(tar -zvvcf), "$dumpdir/source.tmp",
398 "-C", $dumpdir, qw( --), @srcfiles);
399 my $r = system(@cmd);
401 print STDERR "CGI::Auth::Flexible tar failed ($r $!) @cmd\n";
404 die "licence file not found" unless defined $needlicence;
405 srcdump_install($c,$v, $dumpdir, 'source', 'application/octet-stream');
406 close $lockf or die $!;
409 sub srcdump_install ($$$$$) {
410 my ($c,$v, $dumpdir, $which, $ctype) = @_;
411 rename "$dumpdir/$which.tmp", "$dumpdir/$which.data"
412 or die "$dumpdir/$which.data $!";
413 my $ctf = new IO::File "$dumpdir/$which.tmp", 'w'
414 or die "$dumpdir/$which.tmp $!";
415 print $ctf $ctype, "\n" or die $!;
416 close $ctf or die $!;
417 rename "$dumpdir/$which.tmp", "$dumpdir/$which.ctype"
418 or die "$dumpdir/$which.ctype $!";
421 #---------- verifier object methods ----------
428 db_dbh => undef, # must have AutoCommit=0, RaiseError=1
430 keys_path => 'caf-keys',
431 srcdump_path => 'caf-srcdump',
436 random_source => '/dev/urandom',
437 secretbits => 128, # bits
438 hash_algorithm => "SHA-256",
439 login_timeout => 86400, # seconds
440 login_form_timeout => 3600, # seconds
441 key_rollover => 86400, # seconds
442 assoc_param_name => 'caf_assochash',
443 dummy_param_name_prefix => 'caf__',
444 cookie_name => "caf_assocsecret",
445 password_param_name => 'password',
446 srcdump_param_name => 'caf_srcdump',
447 username_param_names => [qw(username)],
448 form_entry_size => 60,
449 logout_param_names => [qw(caf_logout)],
450 loggedout_param_names => [qw(caf_loggedout)],
451 promise_check_mutate => 0,
452 get_param => sub { $_[0]->param($_[2]) },
453 get_params => sub { $_[1]->get_params() },
454 get_path_info => sub { $_[0]->path_info() },
455 get_cookie => sub { $_[0]->cookie($_[1]->{S}{cookie_name}) },
456 get_method => sub { $_[0]->request_method() },
457 is_https => sub { !!$_[0]->https() },
458 get_url => sub { $_[0]->url(); },
459 is_login => sub { defined $_[1]->_rp('password_param_name') },
460 login_ok => \&login_ok_password,
461 username_password_error => sub { die },
462 is_logout => sub { $_[1]->has_a_param('logout_param_names') },
463 is_loggedout => sub { $_[1]->has_a_param('loggedout_param_names') },
464 handle_divert => sub { return 0 },
465 do_redirect => \&do_redirect_cgi, # this hook is allowed to throw
467 get_cookie_domain => \&get_cookie_domain,
469 gen_start_html => sub { $_[0]->start_html($_[2]); },
470 gen_footer_html => \&gen_plain_footer_html,
471 gen_licence_link_html => \&gen_plain_licence_link_html,
472 gen_source_link_html => \&gen_plain_source_link_html,
473 gen_end_html => sub { $_[0]->end_html(); },
474 gen_login_form => \&gen_plain_login_form,
475 gen_login_link => \&gen_plain_login_link,
476 gen_postmainpage_form => \&gen_postmainpage_form,
477 srcdump_dump => \&srcdump_dump,
478 srcdump_prepare => \&srcdump_dirscan_prepare,
479 srcdump_licence_path => undef,
480 srcdump_licence_files => [qw(AGPLv3+CAFv1 CGI/Auth/Flexible/AGPLv3+CAFv1)],
481 srcdump_listitems => sub { (@INC, $ENV{'SCRIPT_FILENAME'}, $0); },
482 srcdump_filter_cwd => 1,
483 srcdump_system_dir => sub {
484 $_[2] =~ m#^/etc/|^/usr/(?!local/)(?!lib/cgi)#;
486 srcdump_process_item => \&srcdump_process_item,
487 srcdump_vcs_dirs => [qw(.git .hg .bzr .svn)],
488 srcdump_vcsscript => {git => "
490 git ls-files -z --others --exclude-from=.gitignore
491 find .git ! -name \\*~ -print0
493 srcdump_byvcs => \&srcdump_byvcs,
494 srcdump_novcs => \&srcdump_novcs,
495 srcdump_excludes => [qw(*~ *.bak *.tmp), '#*#'],
496 dump => \&dump_plain,
497 gettext => sub { gettext($_[2]); },
498 print => sub { print $_[2] or die $!; },
499 debug => sub { }, # like print; msgs contain trailing \n
504 while (($k,$v,@_) = @_) {
505 die "unknown setting $k" unless
506 $k =~ m/^promise_/ or
507 exists $verifier->{S}{$k};
508 $verifier->{S}{$k} = $v;
510 $verifier->{S}{db_setup_stmts} //=
511 ["CREATE TABLE $verifier->{S}{db_prefix}_assocs (".
512 " assochash VARCHAR PRIMARY KEY,".
513 " username VARCHAR NOT NULL,".
514 " last INTEGER NOT NULL".
517 "CREATE INDEX $verifier->{S}{db_prefix}_assocs_timeout_index".
518 " ON $verifier->{S}{db_prefix}_assocs".
521 bless $verifier, $class;
522 $verifier->_dbopen();
523 $verifier->_ch('srcdump_prepare');
527 sub _db_setup_do ($$) {
531 $v->_db_transaction(sub {
532 local ($dbh->{PrintError}) = 0;
543 $dbh = $v->{S}{db_dbh};
545 die if $dbh->{AutoCommit};
546 die unless $dbh->{RaiseError};
548 $v->{S}{db_dsn} ||= "dbi:SQLite:dbname=".$v->_get_path('db');
549 my $dsn = $v->{S}{db_dsn};
552 $dbh = DBI->connect($dsn, $v->{S}{db_user},
553 $v->{S}{db_password}, {
556 ShowErrorStatement => 1,
559 die "$dsn $! ?" unless $dbh;
563 foreach my $stmt (@{ $v->{S}{db_setup_stmts} }) {
564 $v->_db_setup_do($stmt);
576 sub _db_transaction ($$) {
581 #print STDERR "DT entry\n";
583 #print STDERR "DT loop\n";
586 #print STDERR "DT fn ok\n";
589 #print STDERR "DT fn error\n";
590 { local ($@); $dbh->rollback(); }
591 #print STDERR "DT fn throwing\n";
594 #print STDERR "DT fn eval ok\n";
597 #print STDERR "DT commit ok\n";
600 #print STDERR "DT commit eval ok ",Dumper($rv);
603 #print STDERR "DT commit throw?\n";
604 die $@ if !--$retries;
605 #print STDERR "DT loop again\n";
609 #---------- request object methods ----------
612 my ($classbase, $cgi, @extra) = @_;
613 if (!ref $classbase) {
614 $classbase = $classbase->new_verifier(@extra);
620 S => $classbase->{S},
621 Dbh => $classbase->{Dbh},
624 bless $r, ref $classbase;
627 sub _ch ($$@) { # calls an application hook
628 my ($r,$methname, @args) = @_;
629 my $methfunc = $r->{S}{$methname};
630 die "$methname ?" unless $methfunc;
631 return $methfunc->($r->{Cgi}, $r, @args);
636 my $pn = $r->{S}{$pnvb};
637 my $p = scalar $r->_ch('get_param',$pn)
642 $r->_ch('debug',@args);
646 my ($r,$keybase) = @_;
647 my $leaf = $r->{S}{"${keybase}_path"};
648 return $r->_absify_path($leaf);
651 sub _absify_path ($$) {
653 return $leaf if $leaf =~ m,^/,;
654 my $dir = $v->{S}{dir};
655 die "relying on cwd by default ?! set dir" unless defined $dir;
659 sub _gt ($$) { my ($r, $t) = @_; return $r->_ch('gettext',$t); }
660 sub _print ($$) { my ($r, @t) = @_; return $r->_ch('print', join '', @t); }
662 sub construct_cookie ($$$) {
663 my ($r, $cooks) = @_;
664 return undef unless $cooks;
667 -name => $r->{S}{cookie_name},
669 -path => $r->{S}{cookie_path},
670 -domain => $r->_ch('get_cookie_domain'),
671 -expires => '+'.$r->{S}{login_timeout}.'s',
672 -secure => $r->{S}{encrypted_only}
674 my $cookie = $c->cookie(@ca);
675 #print STDERR "CC $r $c $cooks $cookie (@ca).\n";
679 # pages/param-sets are
680 # n normal non-mutating page
681 # r retrieval of information for JS etc., non-mutating
683 # u update of information by JS etc., mutating
686 # O "you have just logged out" page load
689 # - no value supplied (represented in code as $cookt='')
690 # n, nN value not in our db
691 # t, tN temporary value (in our db, no logged in user yet)
692 # y, yN value corresponds to logged-in user
693 # and, aggregated conditions:
694 # a, aN anything including -
696 # if N differs the case applies only when the two values differ
697 # (eg, a1 y2 does not apply when the logged-in value is supplied twice)
699 # "stale session" means request originates from a page from a login
700 # session which has been revoked (eg by logout); "cleared session"
701 # means request originates from a browser which has a different (or
704 # Case analysis, cookie mode, app promises re mutate:
705 # cook parm meth form
707 # any - POST nrmuoi bug or attack, fail
708 # any - GET rmuoi bug or attack, fail
709 # any any GET muoi bug or attack, fail
711 # - - GET O "just logged out" page
712 # (any other) O bug or attack, fail
714 # a1 a2 POST o logout
715 # if a1 is valid, revoke it
716 # if a2 is valid, revoke it
718 # redirect to "just logged out" page
719 # (which contains link to login form)
721 # - t POST i complain about cookies being disabled
722 # (with link to login form)
724 # t1 t1 POST i login (or switch user)
726 # show new login form
728 # upgrade t1 to y1 in our db (setting username)
729 # redirect to GET of remaining params
731 # y1 a2 POST i complain about stale login form
733 # show new login form
735 # (other) POST i complain about stale login form
736 # show new login form
738 # t1 a2 ANY nrmu treat as - a2 ANY
740 # y - GET n cross-site link
743 # y y GET nr fine, show page or send data
744 # y y POST nrmu mutation is OK, do operation
746 # y1 y2 GET nr request from stale page
747 # do not revoke y2 as not RESTful
750 # y1 y2 POST nrmu request from stale page
754 # y nt GET n intra-site link from stale page,
755 # treat as cross-site link, show data
757 # y nt POST n m intra-site form submission from stale page
758 # show "session interrupted"
759 # with link to main data page
761 # y nt GET r intra-site request from stale page
764 # y nt POST r u intra-site request from stale page
767 # -n y2 GET nr intra-site link from cleared session
768 # do not revoke y2 as not RESTful
771 # -n y2 POST nrmu request from cleared session
773 # treat as -/n n POST
775 # -nt -nt GET n cross-site link but user not logged in
776 # show login form with redirect to orig params
777 # generate fresh cookie
779 # -nt nt GET rmu user not logged in
782 # -nt nt POST n m user not logged in
785 # -nt nt POST r u user not logged in
788 sub _check_divert_core ($) {
791 my $srcdump = $r->_rp('srcdump_param_name');
793 die if $srcdump =~ m/\W/;
794 return ({ Kind => 'SRCDUMP-'.uc $srcdump,
800 my $cooksraw = $r->_ch('get_cookie');
801 my $cooks = $r->_unblind($cooksraw);
803 if ($r->{S}{encrypted_only} && !$r->_ch('is_https')) {
804 return ({ Kind => 'REDIRECT-HTTPS',
805 Message => $r->_gt("Redirecting to secure server..."),
810 my $meth = $r->_ch('get_method');
811 my $parmhraw = $r->_rp('assoc_param_name');
812 my $parmh = $r->_unblind($parmhraw);
813 my $cookh = defined $cooks ? $r->hash($cooks) : undef;
815 my ($cookt,$cooku) = $r->_identify($cookh, $cooks);
816 my $parms = (defined $cooks && defined $parmh && $parmh eq $cookh)
818 my ($parmt) = $r->_identify($parmh, $parms);
820 $r->_debug("_c_d_c cookt=$cookt parmt=$parmt\n");
822 if ($r->_ch('is_logout')) {
825 $r->_db_revoke($cookh);
826 $r->_db_revoke($parmh);
827 return ({ Kind => 'REDIRECT-LOGGEDOUT',
828 Message => $r->_gt("Logging out..."),
831 $r->{S}{loggedout_param_names}[0] => [ 1 ],
834 if ($r->_ch('is_loggedout')) {
835 die unless $meth eq 'GET';
836 die if $cookt eq 'y';
838 return ({ Kind => 'SMALLPAGE-LOGGEDOUT',
839 Message => $r->_gt("You have been logged out."),
843 if ($r->_ch('is_login')) {
846 if (!$cookt && $parmt eq 'n') {
847 return ({ Kind => 'SMALLPAGE-NOCOOKIE',
848 Message => $r->_gt("You do not seem to have cookies".
849 " enabled. You must enable cookies".
850 " as we use them for login."),
851 _CookieRaw => $r->_fresh_secret(),
852 Params => $r->chain_params() })
854 if (!$cookt || $cookt eq 'n' || $cookh ne $parmh) {
855 $r->_db_revoke($cookh);
856 return ({ Kind => 'LOGIN-STALE',
857 Message => $r->_gt("Stale session;".
858 " you need to log in again."),
859 _CookieRaw => $r->_fresh_secret(),
862 die unless $parmt eq 't' || $parmt eq 'y';
863 my ($username, $login_errormessage) = $r->_ch('login_ok');
864 unless (defined $username && length $username) {
865 $login_errormessage = $r->_gt("Incorrect username/password.")
866 if !$login_errormessage;
867 return ({ Kind => 'LOGIN-BAD',
868 Message => $login_errormessage,
869 _CookieRaw => $cooks,
870 Params => $r->chain_params() })
872 $r->_db_record_login_ok($parmh,$username);
873 return ({ Kind => 'REDIRECT-LOGGEDIN',
874 Message => $r->_gt("Logging in..."),
875 _CookieRaw => $cooks,
876 Params => $r->chain_params() });
882 if ($cookt eq 'y' && $parmt eq 'y' && $cookh ne $parmh) {
883 $r->_db_revoke($parmh) if $meth eq 'POST';
888 die unless !$cookt || $cookt eq 'n';
889 die unless !$parmt || $parmt eq 't' || $parmt eq 'n' || $parmt eq 'y';
890 my $news = $r->_fresh_secret();
891 if ($meth eq 'GET') {
892 return ({ Kind => 'LOGIN-INCOMINGLINK',
893 Message => $r->_gt("You need to log in."),
895 Params => $r->chain_params() });
897 $r->_db_revoke($parmh);
898 return ({ Kind => 'LOGIN-FRESH',
899 Message => $r->_gt("You need to log in."),
905 if (!$r->{S}{promise_check_mutate}) {
906 if ($meth ne 'POST') {
907 return ({ Kind => 'MAINPAGEONLY',
908 Message => $r->_gt('Entering via cross-site link.'),
909 _CookieRaw => $cooks,
911 # NB caller must then ignore params & path!
912 # if this is too hard they can spit out a small form
913 # with a "click to continue"
917 die unless $cookt eq 'y';
918 unless ($r->{S}{promise_check_mutate} && $meth eq 'GET') {
919 if ($parmt eq 't' || $parmt eq 'n') {
920 return ({ Kind => 'STALE',
921 Message => $r->_gt("Login session interrupted."),
922 _CookieRaw => $cooks,
925 die unless $parmt eq 'y';
926 die unless $cookh eq $parmh;
928 $r->_db_update_last($cooku,$parmh);
930 $r->{ParmT} = $parmt;
931 $r->{AssocRaw} = $cooks;
932 $r->{UserOK} = $cooku;
933 #print STDERR "C-D-C OK\n";
937 sub chain_params ($) {
939 my %p = %{ $r->_ch('get_params') };
940 foreach my $pncn (keys %{ $r->{S} }) {
942 if ($pncn =~ m/_param_name$/) {
943 my $name = $r->{S}{$pncn};
944 die "$pncn ?" if ref $name;
946 } elsif ($pncn =~ m/_param_names$/) {
947 $names = $r->{S}{$pncn};
951 foreach my $name (@$names) {
955 my $dummy_prefix = $r->{S}{dummy_param_name_prefix};
956 foreach my $name (grep /^$dummy_prefix/, keys %p) {
959 die if exists $p{''};
960 $p{''} = [ $r->_ch('get_path_info') ];
966 # returns ($t,$username)
967 # where $t is one of "t" "y" "n", or "" (for -)
968 # either $s must be undef, or $h eq $r->hash($s)
970 #print STDERR "_identify\n";
971 return '' unless defined $h && length $h;
972 #print STDERR "_identify h=$h s=".(defined $s ? $s : '<undef>')."\n";
976 $dbh->do("DELETE FROM $r->{S}{db_prefix}_assocs".
977 " WHERE last < ?", {},
978 time - $r->{S}{login_timeout});
980 my $row = $dbh->selectrow_arrayref("SELECT username, last".
981 " FROM $r->{S}{db_prefix}_assocs".
982 " WHERE assochash = ?", {}, $h);
984 #print STDERR "_identify h=$h s=$s YES @$row\n";
985 my ($nusername, $nlast) = @$row;
986 return ('y', $nusername);
989 # Well, it's not in the database. But maybe it's a hash of a
992 return 'n' unless defined $s;
994 my ($keyt, $signature, $message, $noncet, $nonce) =
995 $s =~ m/^(\d+)\.(\w+)\.((\d+)\.(\w+))$/ or die;
997 return 'n' if time > $noncet + $r->{S}{login_form_timeout};
999 #print STDERR "_identify noncet=$noncet ok\n";
1001 my $keys = $r->_open_keys();
1002 while (my ($rkeyt, $rkey, $line) = $r->_read_key($keys)) {
1003 #print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey\n";
1004 last if $rkeyt < $keyt; # too far down in the file
1005 my $trysignature = $r->_hmac($rkey, $message);
1006 #print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey try=$trysignature\n";
1007 return 't' if $trysignature eq $signature;
1010 #print STDERR "_identify NO\n";
1012 $keys->error and die $!;
1016 sub _db_revoke ($$) {
1017 # revokes $h if it's valid; no-op if it's not
1020 my $dbh = $r->{Dbh};
1022 $dbh->do("DELETE FROM $r->{S}{db_prefix}_assocs".
1023 " WHERE assochash = ?", {}, $h);
1026 sub _db_record_login_ok ($$$) {
1027 my ($r,$h,$user) = @_;
1029 my $dbh = $r->{Dbh};
1030 $dbh->do("INSERT INTO $r->{S}{db_prefix}_assocs".
1031 " (assochash, username, last) VALUES (?,?,?)", {},
1035 sub _db_update_last ($$) {
1036 # revokes $h if it's valid; no-op if it's not
1037 my ($r,$user,$h) = @_;
1038 my $dbh = $r->{Dbh};
1039 $dbh->do("UPDATE $r->{S}{db_prefix}_assocs".
1041 " WHERE username = ? AND assochash = ?", {},
1045 sub check_divert ($) {
1047 if (exists $r->{Divert}) {
1048 return $r->{Divert};
1050 my $dbh = $r->{Dbh};
1051 $r->{Divert} = $r->_db_transaction(sub { $r->_check_divert_core(); });
1054 my $divert = $r->{Divert};
1055 my $cookraw = $divert && $divert->{_CookieRaw};
1057 $divert->{CookieSecret} = $r->_blind($cookraw);
1058 $divert->{Params}{$r->{S}{assoc_param_name}} = [
1059 $r->_blind($r->hash($cookraw))
1063 $r->_debug(Data::Dumper->Dump([$divert],[qw(divert)]));
1067 sub get_divert ($) {
1069 die "unchecked" unless exists $r->{Divert};
1070 return $r->{Divert};
1073 sub get_username ($) {
1075 my $divert = $r->get_divert();
1076 return undef if $divert;
1077 return $r->{UserOK};
1080 sub url_with_query_params ($$;$) {
1081 my ($r, $params, $nonpagetype) = @_;
1082 #print STDERR "PARAMS ",Dumper($params);
1083 my $uri = URI->new($r->_ch('get_url'));
1084 $uri->path($uri->path() . $params->{''}[0]) if $params->{''};
1085 my @flatparams = flatten_params($params);
1086 if (defined $nonpagetype && $r->need_add_hidden('GET',$nonpagetype)) {
1087 push @flatparams, $r->{S}{assoc_param_name}, $r->secret_hidden_val();
1089 $uri->query_form(@flatparams);
1090 return $uri->as_string();
1093 sub _cgi_header_args ($$@) {
1094 my ($r, $cookie, @ha) = @_;
1095 unshift @ha, qw(-type text/html);
1096 push @ha, (-cookie => $cookie) if defined $cookie;
1097 #print STDERR "_cgi_header_args ",join('|',@ha),".\n";
1104 my ($divert) = $r->check_divert();
1105 return 1 if !$divert;
1107 my $handled = $r->_ch('handle_divert',$divert);
1108 return 0 if $handled;
1110 my $kind = $divert->{Kind};
1111 my $cookiesecret = $divert->{CookieSecret};
1112 my $params = $divert->{Params};
1113 my $cookie = $r->construct_cookie($cookiesecret);
1115 if ($kind =~ m/^SRCDUMP-(\w+)$/) {
1116 $r->_ch('srcdump_dump', (lc $1));
1120 if ($kind =~ m/^REDIRECT-/) {
1121 # for redirects, we honour stored Params and Cookie,
1122 # as we would for non-divert
1123 if ($kind eq 'REDIRECT-LOGGEDOUT') {
1124 } elsif ($kind =~ m/REDIRECT-(?:LOGGEDIN|HTTPS)/) {
1128 my $new_url = $r->url_with_query_params($params);
1129 if ($kind eq 'REDIRECT-HTTPS') {
1130 my $uri = URI->new($new_url);
1131 die unless $uri->scheme eq 'http';
1132 $uri->scheme('https');
1133 $new_url = $uri->as_string();
1135 $r->_ch('do_redirect',$new_url, $cookie);
1140 if ($kind =~ m/^LOGIN-/) {
1141 $title = $r->_gt('Login');
1142 push @body, $divert->{Message};
1143 push @body, $r->_ch('gen_login_form', $params);
1144 } elsif ($kind =~ m/^SMALLPAGE-/) {
1145 $title = $r->_gt('Not logged in');
1146 push @body, $divert->{Message};
1147 push @body, $r->_ch('gen_login_link', $params);
1148 } elsif ($kind =~ m/^STALE/) {
1149 $title = $r->_gt('Re-entering secure site.');
1150 push @body, $divert->{Message};
1151 push @body, $r->_ch('gen_postmainpage_form', $params);
1152 } elsif ($kind =~ m/^MAINPAGEONLY$/) {
1153 $title = $r->_gt('Entering secure site.');
1154 push @body, $divert->{Message};
1155 push @body, $r->_ch('gen_postmainpage_form', $params);
1160 $r->_print($r->{Cgi}->header($r->_cgi_header_args($cookie)),
1161 $r->_ch('gen_start_html',$title),
1163 $r->_ch('gen_footer_html'),
1164 $r->_ch('gen_end_html'))));
1169 my ($r, $bytes) = @_;
1171 my $rsf = $v->{RandomHandle};
1172 my $rsp = $r->{S}{random_source};
1174 $v->{RandomHandle} = $rsf = new IO::File $rsp, '<' or die "$rsp $!";
1175 #print STDERR "RH $rsf\n";
1179 read($rsf,$bin,$bytes) == $bytes or die "$rsp $!";
1180 my $out = unpack "H*", $bin;
1181 #print STDERR "_random out $out\n";
1185 sub _blind_len ($$) {
1187 return length($str =~ y/0-9a-f//cdr);
1190 sub _blind_combine ($$$) {
1191 my ($r, $in, $mask) = @_;
1192 my @mask = split //, $mask;
1194 my $m = shift @mask;
1195 sprintf "%x", hex($m) ^ hex($&);
1202 return $in unless $in;
1203 my $l = $r->_blind_len($in);
1204 my $mask = $r->_random(($l+1)>>1);
1205 $mask = substr $mask, 0, $l;
1206 my $blound = $r->_blind_combine($in, $mask);
1207 return "$blound.$mask";
1212 return $in unless $in;
1213 my ($blound,$mask) = ($in =~ m#^(.*)\.([0-9a-f]+)$#) or die "$in ?";
1214 my $l = $r->_blind_len($blound);
1215 $l == length($mask) or die "$in ?";
1216 return $r->_blind_combine($blound, $mask);
1219 sub _random_key ($) {
1221 #print STDERR "_random_key\n";
1222 my $bytes = ($r->{S}{secretbits} + 7) >> 3;
1223 return $r->_random($bytes);
1226 sub _read_key ($$) {
1227 my ($r, $keys) = @_;
1228 # returns $gen_time_t, $key_value_in_hex, $complete_line
1230 my ($gen, $k) = m/^(\d+) (\S+)$/ or die "$_ ?";
1231 my $age = time - $gen;
1232 next if $age > $r->{S}{key_rollover} &&
1233 $age > $r->{S}{login_form_timeout}*2;
1234 return ($gen, $k, $_);
1239 sub _open_keys ($) {
1241 my $spath = $r->_get_path('keys');
1243 #print STDERR "_open_keys\n";
1244 my $keys = new IO::File $spath, 'r+';
1246 #print STDERR "_open_keys open\n";
1247 stat $keys or die $!; # NB must not disturb stat _
1248 my $size = (stat _)[7];
1249 my $age = time - (stat _)[9];
1250 #print STDERR "_open_keys open size=$size age=$age\n";
1252 if $size && $age <= $r->{S}{key_rollover} / 2;
1253 #print STDERR "_open_keys open bad\n";
1255 # file doesn't exist, or is empty or too old
1257 #print STDERR "_open_keys closed\n";
1258 die "$spath $!" unless $!==&ENOENT;
1259 # doesn't exist, so create it just so we can lock it
1260 $keys = new IO::File $spath, 'a+';
1261 die "$keys $!" unless $keys;
1262 stat $keys or die $!; # NB must not disturb stat _
1263 my $size = (stat _)[7];
1264 #print STDERR "_open_keys created size=$size\n";
1265 next if $size; # oh someone else has done it, reopen and read it
1267 # file now exists is empty or too old, we must try to replace it
1268 my $our_inum = (stat _)[1]; # last use of that stat _
1269 flock $keys, LOCK_EX or die "$spath $!";
1270 stat $spath or die "$spath $!";
1271 my $path_inum = (stat _)[1];
1272 #print STDERR "_open_keys locked our=$our_inum path=$path_inum\n";
1273 next if $our_inum != $path_inum; # someone else has done it
1274 # We now hold the lock!
1275 #print STDERR "_open_keys creating\n";
1276 my $newkeys = new IO::Handle;
1277 sysopen $newkeys, "$spath.new", O_CREAT|O_TRUNC|O_WRONLY, 0600
1278 or die "$spath.new $!";
1279 # we add the new key to the front which means it's always sorted
1280 print $newkeys time, ' ', $r->_random_key(), "\n" or die $!;
1281 while (my ($gen,$key,$line) = $r->_read_key($keys)) {
1282 #print STDERR "_open_keys copy1\n";
1283 print $newkeys, $line or die $!;
1285 $keys->error and die $!;
1286 close $newkeys or die "$spath.new $!";
1287 rename "$spath.new", "$spath" or die "$spath: $!";
1288 #print STDERR "_open_keys installed\n";
1289 # that rename effective unlocks, since it makes the name refer
1290 # to the new file which we haven't locked
1291 # we go round again opening the file at the beginning
1292 # so that our caller gets a fresh handle onto the existing key file
1296 sub _fresh_secret ($) {
1298 #print STDERR "_fresh_secret\n";
1300 my $keys = $r->_open_keys();
1301 my ($keyt, $key) = $r->_read_key($keys);
1302 die unless defined $keyt;
1304 my $nonce = $r->_random_key();
1306 my $message = "$noncet.$nonce";
1308 my $signature = $r->_hmac($key, $message);
1309 my $secret = "$keyt.$signature.$message";
1310 #print STDERR "FRESH $secret\n";
1315 my ($r, $keyhex, $message) = @_;
1316 my $keybin = pack "H*", $keyhex;
1317 my $alg = $r->{S}{hash_algorithm};
1318 #print STDERR "hmac $alg\n";
1319 my $base = new Digest $alg;
1320 #print STDERR "hmac $alg $base\n";
1321 my $digest = new Digest::HMAC $keybin, $base;
1322 #print STDERR "hmac $alg $base $digest\n";
1323 $digest->add($message);
1324 return $digest->hexdigest();
1328 my ($r, $message) = @_;
1329 my $alg = $r->{S}{hash_algorithm};
1330 #print STDERR "hash $alg\n";
1331 my $digest = new Digest $alg;
1332 $digest->add($message);
1333 return $digest->hexdigest();
1336 sub _assert_checked ($) {
1338 die "unchecked" unless exists $r->{Divert};
1343 my $meth = $r->_ch('get_method');
1344 return $meth eq 'POST';
1347 sub _must_be_post ($) {
1349 my $meth = $r->_ch('get_method');
1350 die "mutating non-POST" if $meth ne 'POST';
1353 sub check_mutate ($) {
1355 $r->_assert_checked();
1356 die if $r->{Divert};
1357 $r->_must_be_post();
1360 our %_resource_get_needs_secret_hidden =
1361 (map { $_ => 0 } qw(PAGE FRAME IFRAME SRCDUMP STYLESHEET FAVICON ROBOTS),
1362 map { $_ => 1 } qw(IMAGE SCRIPT AJAX-XML AJAX-JSON AJAX-OTHER));
1364 sub update_get_need_add_hidden ($$;$) {
1365 my ($r, $reqtype, $value, $force) = @_;
1367 ? ($r->{GetNeedsSecretHidden} ||= { })
1368 : \%_resource_get_needs_secret_hidden;
1369 return if !$force &&
1370 (exists $_resource_get_needs_secret_hidden{$reqtype} ||
1371 exists $hash->{$reqtype});
1372 $hash->{$reqtype} = $value;
1375 sub need_add_hidden ($$) {
1376 my ($r, $method, $reqtype) = @_;
1377 return 1 if $method ne 'GET';
1379 my $ent = $r->{GetNeedsSecretHidden}{$reqtype};
1380 return $ent if defined $ent;
1382 my $ent = $_resource_get_needs_secret_hidden{$reqtype};
1383 return $ent if defined $ent;
1384 die "unsupported nonpage GET type $reqtype";
1387 sub check_nonpage ($$) {
1388 my ($r, $reqtype) = @_;
1389 $r->_assert_checked();
1390 return unless $r->resource_get_needs_secret_hidden($reqtype);
1391 return if $r->{ParmT} eq 'y';
1392 die "missing hidden secret parameter on nonpage request $reqtype";
1395 #---------- output ----------
1397 sub secret_cookie_val ($) {
1399 $r->_assert_checked();
1400 return defined $r->{AssocRaw} ? $r->_blind($r->{AssocRaw}) : '';
1403 sub secret_hidden_val ($) {
1405 $r->_assert_checked();
1406 return defined $r->{AssocRaw} ? $r->_blind($r->hash($r->{AssocRaw})) : '';
1409 sub secret_hidden_html ($) {
1411 return $r->{Cgi}->hidden(-name => $r->{S}{assoc_param_name},
1412 -default => $r->secret_hidden_val());
1415 sub secret_cookie ($) {
1417 my $secret = $r->secret_cookie_val();
1418 return undef if !defined $secret;
1419 #print STDERR "SC\n";
1420 my $cookv = $r->construct_cookie($secret);
1421 #print STDERR "SC=$cookv\n";