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! ],
38 use CGI qw/escapeHTML/;
52 #---------- public utilities ----------
54 sub flatten_params ($) {
57 foreach my $k (keys %$p) {
59 foreach my $v (@{ $p->{$k} }) {
66 #---------- default callbacks ----------
68 sub has_a_param ($$) {
70 foreach my $pn (@{ $r->{S}{$cn} }) {
71 return 1 if $r->_ch('get_param',$pn);
79 my $vars = $c->Vars();
81 foreach my $name (keys %$vars) {
82 $p{$name} = [ split "\0", $vars->{$name} ];
87 sub get_cookie_domain ($$$) {
89 my $uri = new URI $r->_ch('get_url');
93 sub login_ok_password ($$) {
95 my $username_params = $r->{S}{username_param_names};
96 my $username = $r->_ch('get_param',$username_params->[0]);
97 my $password = $r->_rp('password_param_name');
98 my $error = $r->_ch('username_password_error', $username, $password);
99 return defined($error) ? (undef,$error) : ($username,undef);
102 sub do_redirect_cgi ($$$$) {
103 my ($c, $r, $new_url, $cookie) = @_;
104 $r->_print($c->header($r->_cgi_header_args($cookie,
105 -status => '303 See other',
106 -location => $new_url)),
107 $r->_ch('gen_start_html',$r->_gt('Redirection')),
108 '<a href="'.escapeHTML($new_url).'">',
109 $r->_gt("If you aren't redirected, click to continue."),
111 $r->_ch('gen_end_html'));
114 sub gen_some_form ($$) {
115 my ($r, $params, $bodyfn) = @_;
116 # Calls $bodyfn->($c,$r) which returns @formbits
120 $pathinfo .= $params->{''}[0] if $params->{''};
121 push @form, ('<form method="POST" action="'.
122 escapeHTML($r->_ch('get_url').$pathinfo).'">');
123 push @form, $bodyfn->($c,$r);
124 foreach my $n (keys %$params) {
126 foreach my $val (@{ $params->{$n} }) {
127 push @form, ('<input type="hidden"'.
128 ' name="'.escapeHTML($n).'"'.
129 ' value="'.escapeHTML($val).'">');
132 push @form, ('</form>');
133 return join "\n", @form;
136 sub gen_plain_login_form ($$) {
137 my ($c,$r, $params) = @_;
138 return $r->gen_some_form($params, sub {
140 push @form, ('<table>');
141 my $sz = 'size="'.$r->{S}{form_entry_size}.'"';
142 foreach my $up (@{ $r->{S}{username_param_names}}) {
143 push @form, ('<tr><td>',$r->_gt(ucfirst $up),'</td>',
144 '<td><input type="text" '.$sz.
145 ' name='.$up.'></td></tr>');
147 push @form, ('<tr><td>'.$r->_gt('Password').'</td>',
148 '<td><input type="password" '.$sz.
149 ' name="'.$r->{S}{password_param_name}.'"></td></tr>');
150 push @form, ('<tr><td colspan="2">',
151 '<input type="submit"'.
152 ' name="'.$r->{S}{dummy_param_name_prefix}.'login"'.
153 ' value="'.$r->_gt('Login').'"></td></tr>',
159 sub gen_postmainpage_form ($$$) {
160 my ($c,$r, $params) = @_;
161 return $r->gen_some_form($params, sub {
163 push @form, ('<input type="submit"',
164 ' name="'.$r->{S}{dummy_param_name_prefix}.'submit"'.
165 ' value="'.$r->_gt('Continue').'">');
170 sub gen_plain_login_link ($$) {
171 my ($c,$r, $params) = @_;
172 my $url = $r->url_with_query_params($params);
173 return ('<a href="'.escapeHTML($url).'">'.
174 $r->_gt('Log in again to continue.').
178 sub gen_srcdump_link_html ($$$$) {
179 my ($c,$r,$anchor,$specval) = @_;
180 my %params = ($r->{S}{srcdump_param_name} => [ $specval ]);
182 escapeHTML($r->url_with_query_params(\%params,'SRCDUMP')).
185 sub gen_plain_licence_link_html ($$) {
187 gen_srcdump_link_html($c,$r, 'GNU Affero GPL', 'licence');
189 sub gen_plain_source_link_html ($$) {
191 gen_srcdump_link_html($c,$r, 'Source available', 'source');
194 sub gen_plain_footer_html ($$) {
196 return ('<hr><address>',
197 ("Powered by Free / Libre / Open Source Software".
198 " according to the ".$r->_ch('gen_licence_link_html')."."),
199 $r->_ch('gen_source_link_html').".",
203 #---------- licence and source code ----------
205 sub srcdump_dump ($$$) {
206 my ($c,$r, $thing) = @_;
207 die if $thing =~ m/\W/ || $thing !~ m/\w/;
208 my $path = $r->_get_path('srcdump');
209 my $ctf = new IO::File "$path/$thing.ctype", 'r'
210 or die "$path/$thing.ctype $!";
212 chomp $ct or die "$path/$thing ?";
213 $ctf->close or die "$path/$thing $!";
214 my $df = new IO::File "$path/$thing.data", 'r'
215 or die "$path/$thing.data $!";
216 $r->_ch('dump', $ct, $df);
219 sub dump_plain ($$$$) {
220 my ($c, $r, $ct, $df) = @_;
221 $r->_print($c->header('-type' => $ct));
224 my $got = read $df, $buffer, 65536;
225 die $! unless defined $got;
231 sub srcdump_process_item ($$$$$$) {
232 my ($c, $v, $dumpdir, $item, $outfn, $needlicence, $dirsdone) = @_;
233 if ($v->_ch('srcdump_system_dir', $item)) {
234 $outfn->("srcdump_process_item: srcdump_system_dir, skipping $item");
240 $upwards =~ s#/+\.$##;
241 last unless $upwards =~ m#[^/]#;
242 foreach my $try (@{ $v->{S}{srcdump_vcs_dirs} }) {
243 #print STDERR "TRY $item $upwards $try\n";
244 if (!stat "$upwards/$try") {
245 $!==&ENOENT or $!==&ENOTDIR or die "check $upwards/$try $!";
248 #print STDERR "VCS $item $upwards $try\n";
249 if ($dirsdone->{$upwards}++) {
250 $outfn->("srcdump_process_item: did $upwards,".
254 #print STDERR "VCS $item $upwards $try GO\n";
255 $try =~ m/\w+/ or die;
256 return $v->_ch('srcdump_byvcs', $dumpdir, $upwards, $outfn, lc $&);
258 $upwards =~ s#/*[^/]+$##;
260 return $v->_ch('srcdump_novcs', $dumpdir, $item, $outfn);
263 sub srcdump_novcs ($$$$$) {
264 my ($c, $v, $dumpdir, $item, $outfn) = @_;
265 stat $item or die "$item $!";
267 my $script = 'find -type f -perm +004';
268 foreach my $excl (@{ $v->{S}{srcdump_excludes} }) {
269 $script .= " \\! -name '$excl'";
271 $script .= " -print0";
272 return srcdump_dir_cpio($c,$v,$dumpdir,$item,$outfn,'novcs',$script);
274 return srcdump_file($c,$v,$dumpdir,$item,$outfn);
276 die "$item not file or directory";
280 sub srcdump_byvcs ($$$$$$) {
281 my ($c, $v, $dumpdir, $dir, $outfn, $vcs) = @_;
282 #print STDERR "BYVCS GIT $dir\n";
283 my $script = $v->{S}{"srcdump_vcsscript"}{$vcs};
284 die "no script for vcs $vcs" unless defined $script;
285 return srcdump_dir_cpio($c,$v,$dumpdir,$dir,$outfn,$vcs,$script);
288 sub srcdump_file ($$$$) {
289 my ($c,$v,$dumpdir,$file,$outfn) = @_;
290 my $outfile = $outfn->("srcdump_file saved $file", "src");
291 copy($file,$outfile) or die "$file $outfile $!";
294 sub srcdump_dir_cpio ($$$$$$$) {
295 my ($c,$v,$dumpdir,$dir,$outfn,$how,$script) = @_;
296 my $outfile = $outfn->("srcdump_dir_cpio $how saved $dir", "tar");
297 #print STDERR "CPIO $dir >$script<\n";
299 defined $pid or die $!;
301 $SIG{__DIE__} = sub {
302 print STDERR "CGI::Auth::Flexible srcdump error: $@\n";
305 open STDOUT, ">", $outfile or die "$outfile $!";
306 chdir $dir or die "chdir $dir: $!";
307 exec '/bin/bash','-ec',"
312 cpio -Hustar -o --quiet -0 -R 1000:1000 || \
313 cpio -Hustar -o --quiet -0
318 $!=0; (waitpid $pid, 0) == $pid or die "$!";
319 die "$dir ($how $script) $outfile $?" if $?;
322 sub srcdump_dirscan_prepare ($$) {
324 my $dumpdir = $v->_get_path('srcdump');
325 mkdir $dumpdir or $!==&EEXIST or die "mkdir $dumpdir $!";
326 my $lockf = new IO::File "$dumpdir/generate.lock", 'w+'
327 or die "$dumpdir/generate.lock $!";
328 flock $lockf, LOCK_EX or die "$dumpdir/generate.lock $!";
329 my $needlicence = "$dumpdir/licence.tmp";
330 unlink $needlicence or $!==&ENOENT or die "rm $needlicence $!";
331 if (defined $v->{S}{srcdump_licence_path}) {
332 copy($v->{S}{srcdump_licence_path}, $needlicence)
333 or die "$v->{S}{srcdump_licence_path} $!";
334 $needlicence = undef;
336 unlink <"$dumpdir/s.[a-z][a-z][a-z].*">;
337 my @srcfiles = qw(licence.data manifest.txt);
338 my $srcoutcounter = 'aaa';
340 my $reportfh = new IO::File "$dumpdir/manifest.txt", 'w' or die $!;
342 my ($message, $extension) = @_;
343 if (defined $extension) {
344 my $leaf = "s.$srcoutcounter.$extension";
346 push @srcfiles, $leaf;
347 print $reportfh "$leaf: $message\n" or die $!;
348 return "$dumpdir/$leaf";
350 print $reportfh "none: $message\n" or die $!;
355 foreach my $item ($v->_ch('srcdump_listitems')) {
356 next unless defined $item;
357 if ($item eq '.' && $v->{S}{srcdump_filter_cwd}) {
358 my @bad = grep { !m#^/# } values %INC;
359 die "filtering . from srcdump items and \@INC but already".
360 " included @bad " if @bad;
361 @INC = grep { $_ ne '.' } @INC;
364 if (!lstat "$item") {
365 die "stat $item $!" unless $!==&ENOENT;
366 $outfn->("srcdump_dirscan_prepare stat ENOENT, skipping $item");
370 $item = realpath($item);
371 if (!defined $item) {
372 die "realpath $item $!" unless $!==&ENOENT;
373 $outfn->("srcdump_dirscan_prepare realpath ENOENT,".
377 if (defined $needlicence) {
378 foreach my $try (@{ $v->{S}{srcdump_licence_files} }) {
379 last if copy("$item/$try", $needlicence);
380 $!==&ENOENT or $!==&ENOTDIR or die "copy $item/$try $!";
383 $v->_ch('srcdump_process_item', $dumpdir, $item,
384 $outfn, \$needlicence, \%dirsdone);
387 close $reportfh or die $!;
388 srcdump_install($c,$v, $dumpdir, 'licence', 'text/plain');
390 my @cmd = (qw(tar -zvvcf), "$dumpdir/source.tmp",
391 "-C", $dumpdir, qw( --), @srcfiles);
392 my $r = system(@cmd);
394 print STDERR "CGI::Auth::Flexible tar failed ($r $!) @cmd\n";
397 die "licence file not found" unless defined $needlicence;
398 srcdump_install($c,$v, $dumpdir, 'source', 'application/octet-stream');
399 close $lockf or die $!;
402 sub srcdump_install ($$$$$) {
403 my ($c,$v, $dumpdir, $which, $ctype) = @_;
404 rename "$dumpdir/$which.tmp", "$dumpdir/$which.data"
405 or die "$dumpdir/$which.data $!";
406 my $ctf = new IO::File "$dumpdir/$which.tmp", 'w'
407 or die "$dumpdir/$which.tmp $!";
408 print $ctf $ctype, "\n" or die $!;
409 close $ctf or die $!;
410 rename "$dumpdir/$which.tmp", "$dumpdir/$which.ctype"
411 or die "$dumpdir/$which.ctype $!";
414 #---------- verifier object methods ----------
421 db_dbh => undef, # must have AutoCommit=0, RaiseError=1
423 keys_path => 'caf-keys',
424 srcdump_path => 'caf-srcdump',
429 random_source => '/dev/urandom',
430 secretbits => 128, # bits
431 hash_algorithm => "SHA-256",
432 login_timeout => 86400, # seconds
433 login_form_timeout => 3600, # seconds
434 key_rollover => 86400, # seconds
435 assoc_param_name => 'caf_assochash',
436 dummy_param_name_prefix => 'caf__',
437 cookie_name => "caf_assocsecret",
438 password_param_name => 'password',
439 srcdump_param_name => 'caf_srcdump',
440 username_param_names => [qw(username)],
441 form_entry_size => 60,
442 logout_param_names => [qw(caf_logout)],
443 loggedout_param_names => [qw(caf_loggedout)],
444 promise_check_mutate => 0,
445 get_param => sub { $_[0]->param($_[2]) },
446 get_params => sub { $_[1]->get_params() },
447 get_path_info => sub { $_[0]->path_info() },
448 get_cookie => sub { $_[0]->cookie($_[1]->{S}{cookie_name}) },
449 get_method => sub { $_[0]->request_method() },
450 is_https => sub { !!$_[0]->https() },
451 get_url => sub { $_[0]->url(); },
452 is_login => sub { defined $_[1]->_rp('password_param_name') },
453 login_ok => \&login_ok_password,
454 username_password_error => sub { die },
455 is_logout => sub { $_[1]->has_a_param('logout_param_names') },
456 is_loggedout => sub { $_[1]->has_a_param('loggedout_param_names') },
457 handle_divert => sub { return 0 },
458 do_redirect => \&do_redirect_cgi, # this hook is allowed to throw
460 get_cookie_domain => \&get_cookie_domain,
462 gen_start_html => sub { $_[0]->start_html($_[2]); },
463 gen_footer_html => \&gen_plain_footer_html,
464 gen_licence_link_html => \&gen_plain_licence_link_html,
465 gen_source_link_html => \&gen_plain_source_link_html,
466 gen_end_html => sub { $_[0]->end_html(); },
467 gen_login_form => \&gen_plain_login_form,
468 gen_login_link => \&gen_plain_login_link,
469 gen_postmainpage_form => \&gen_postmainpage_form,
470 srcdump_dump => \&srcdump_dump,
471 srcdump_prepare => \&srcdump_dirscan_prepare,
472 srcdump_licence_path => undef,
473 srcdump_licence_files => [qw(AGPLv3 CGI/Auth/Flexible/AGPLv3)],
474 srcdump_listitems => sub { (@INC, $ENV{'SCRIPT_FILENAME'}, $0); },
475 srcdump_filter_cwd => 1,
476 srcdump_system_dir => sub {
477 $_[2] =~ m#^/etc/|^/usr/(?!local/)(?!lib/cgi)#;
479 srcdump_process_item => \&srcdump_process_item,
480 srcdump_vcs_dirs => [qw(.git .hg .bzr .svn)],
481 srcdump_vcsscript => {git => "
483 git ls-files -z --others --exclude-from=.gitignore
486 srcdump_byvcs => \&srcdump_byvcs,
487 srcdump_novcs => \&srcdump_novcs,
488 srcdump_excludes => [qw(*~ *.bak *.tmp), '#*#'],
489 dump => \&dump_plain,
490 gettext => sub { gettext($_[2]); },
491 print => sub { print $_[2] or die $!; },
492 debug => sub { }, # like print; msgs contain trailing \n
497 while (($k,$v,@_) = @_) {
498 die "unknown setting $k" unless
499 $k =~ m/^promise_/ or
500 exists $verifier->{S}{$k};
501 $verifier->{S}{$k} = $v;
503 $verifier->{S}{db_setup_stmts} //=
504 ["CREATE TABLE $verifier->{S}{db_prefix}_assocs (".
505 " assochash VARCHAR PRIMARY KEY,".
506 " username VARCHAR NOT NULL,".
507 " last INTEGER NOT NULL".
510 "CREATE INDEX $verifier->{S}{db_prefix}_assocs_timeout_index".
511 " ON $verifier->{S}{db_prefix}_assocs".
514 bless $verifier, $class;
515 $verifier->_dbopen();
516 $verifier->_ch('srcdump_prepare');
520 sub _db_setup_do ($$) {
524 $v->_db_transaction(sub {
525 local ($dbh->{PrintError}) = 0;
536 $dbh = $v->{S}{db_dbh};
538 die if $dbh->{AutoCommit};
539 die unless $dbh->{RaiseError};
541 $v->{S}{db_dsn} ||= "dbi:SQLite:dbname=".$v->_get_path('db');
542 my $dsn = $v->{S}{db_dsn};
545 $dbh = DBI->connect($dsn, $v->{S}{db_user},
546 $v->{S}{db_password}, {
549 ShowErrorStatement => 1,
552 die "$dsn $! ?" unless $dbh;
556 foreach my $stmt (@{ $v->{S}{db_setup_stmts} }) {
557 $v->_db_setup_do($stmt);
569 sub _db_transaction ($$) {
574 #print STDERR "DT entry\n";
576 #print STDERR "DT loop\n";
579 #print STDERR "DT fn ok\n";
582 #print STDERR "DT fn error\n";
583 { local ($@); $dbh->rollback(); }
584 #print STDERR "DT fn throwing\n";
587 #print STDERR "DT fn eval ok\n";
590 #print STDERR "DT commit ok\n";
593 #print STDERR "DT commit eval ok ",Dumper($rv);
596 #print STDERR "DT commit throw?\n";
597 die $@ if !--$retries;
598 #print STDERR "DT loop again\n";
602 #---------- request object methods ----------
605 my ($classbase, $cgi, @extra) = @_;
606 if (!ref $classbase) {
607 $classbase = $classbase->new_verifier(@extra);
613 S => $classbase->{S},
614 Dbh => $classbase->{Dbh},
617 bless $r, ref $classbase;
620 sub _ch ($$@) { # calls an application hook
621 my ($r,$methname, @args) = @_;
622 my $methfunc = $r->{S}{$methname};
623 die "$methname ?" unless $methfunc;
624 return $methfunc->($r->{Cgi}, $r, @args);
629 my $pn = $r->{S}{$pnvb};
630 my $p = scalar $r->_ch('get_param',$pn)
635 $r->_ch('debug',@args);
639 my ($r,$keybase) = @_;
640 my $leaf = $r->{S}{"${keybase}_path"};
641 return $r->_absify_path($leaf);
644 sub _absify_path ($$) {
646 return $leaf if $leaf =~ m,^/,;
647 my $dir = $v->{S}{dir};
648 die "relying on cwd by default ?! set dir" unless defined $dir;
652 sub _gt ($$) { my ($r, $t) = @_; return $r->_ch('gettext',$t); }
653 sub _print ($$) { my ($r, @t) = @_; return $r->_ch('print', join '', @t); }
655 sub construct_cookie ($$$) {
656 my ($r, $cooks) = @_;
657 return undef unless $cooks;
660 -name => $r->{S}{cookie_name},
662 -path => $r->{S}{cookie_path},
663 -domain => $r->_ch('get_cookie_domain'),
664 -expires => '+'.$r->{S}{login_timeout}.'s',
665 -secure => $r->{S}{encrypted_only}
667 my $cookie = $c->cookie(@ca);
668 #print STDERR "CC $r $c $cooks $cookie (@ca).\n";
672 # pages/param-sets are
673 # n normal non-mutating page
674 # r retrieval of information for JS etc., non-mutating
676 # u update of information by JS etc., mutating
679 # O "you have just logged out" page load
682 # - no value supplied (represented in code as $cookt='')
683 # n, nN value not in our db
684 # t, tN temporary value (in our db, no logged in user yet)
685 # y, yN value corresponds to logged-in user
686 # and, aggregated conditions:
687 # a, aN anything including -
689 # if N differs the case applies only when the two values differ
690 # (eg, a1 y2 does not apply when the logged-in value is supplied twice)
692 # "stale session" means request originates from a page from a login
693 # session which has been revoked (eg by logout); "cleared session"
694 # means request originates from a browser which has a different (or
697 # Case analysis, cookie mode, app promises re mutate:
698 # cook parm meth form
700 # any - POST nrmuoi bug or attack, fail
701 # any - GET rmuoi bug or attack, fail
702 # any any GET muoi bug or attack, fail
703 # any t any nrmu bug or attack, fail
705 # - - GET O "just logged out" page
706 # (any other) O bug or attack, fail
708 # a1 a2 POST o logout
709 # if a1 is valid, revoke it
710 # if a2 is valid, revoke it
712 # redirect to "just logged out" page
713 # (which contains link to login form)
715 # - t POST i complain about cookies being disabled
716 # (with link to login form)
718 # t1 t1 POST i login (or switch user)
720 # show new login form
722 # upgrade t1 to y1 in our db (setting username)
723 # redirect to GET of remaining params
725 # y1 a2 POST i complain about stale login form
727 # show new login form
729 # (other) POST i complain about stale login form
730 # show new login form
732 # t1 a2 ANY nrmu treat as - a2 ANY
734 # y - GET n cross-site link
737 # y y GET nr fine, show page or send data
738 # y y POST nrmu mutation is OK, do operation
740 # y1 y2 GET nr request from stale page
741 # do not revoke y2 as not RESTful
744 # y1 y2 POST nrmu request from stale page
748 # y n GET n intra-site link from stale page,
749 # treat as cross-site link, show data
751 # y n POST n m intra-site form submission from stale page
752 # show "session interrupted"
753 # with link to main data page
755 # y n GET r intra-site request from stale page
758 # y n POST r u intra-site request from stale page
761 # -/n y2 GET nr intra-site link from cleared session
762 # do not revoke y2 as not RESTful
765 # -/n y2 POST nrmu request from cleared session
767 # treat as -/n n POST
769 # -/n -/n GET n cross-site link but user not logged in
770 # show login form with redirect to orig params
771 # generate fresh cookie
773 # -/n n GET rmu user not logged in
776 # -/n n POST n m user not logged in
779 # -/n n POST r u user not logged in
782 sub _check_divert_core ($) {
785 my $srcdump = $r->_rp('srcdump_param_name');
787 die if $srcdump =~ m/\W/;
788 return ({ Kind => 'SRCDUMP-'.uc $srcdump,
794 my $cooksraw = $r->_ch('get_cookie');
795 my $cooks = $r->_unblind($cooksraw);
797 if ($r->{S}{encrypted_only} && !$r->_ch('is_https')) {
798 return ({ Kind => 'REDIRECT-HTTPS',
799 Message => $r->_gt("Redirecting to secure server..."),
804 my $meth = $r->_ch('get_method');
805 my $parmhraw = $r->_rp('assoc_param_name');
806 my $parmh = $r->_unblind($parmhraw);
807 my $cookh = defined $cooks ? $r->hash($cooks) : undef;
809 my ($cookt,$cooku) = $r->_identify($cookh, $cooks);
810 my $parms = (defined $cooks && defined $parmh && $parmh eq $cookh)
812 my ($parmt) = $r->_identify($parmh, $parms);
814 $r->_debug("_c_d_c cookt=$cookt parmt=$parmt\n");
816 if ($r->_ch('is_logout')) {
819 $r->_db_revoke($cookh);
820 $r->_db_revoke($parmh);
821 return ({ Kind => 'REDIRECT-LOGGEDOUT',
822 Message => $r->_gt("Logging out..."),
825 $r->{S}{loggedout_param_names}[0] => [ 1 ],
828 if ($r->_ch('is_loggedout')) {
829 die unless $meth eq 'GET';
830 die if $cookt eq 'y';
832 return ({ Kind => 'SMALLPAGE-LOGGEDOUT',
833 Message => $r->_gt("You have been logged out."),
837 if ($r->_ch('is_login')) {
840 if (!$cookt && $parmt eq 'n') {
841 return ({ Kind => 'SMALLPAGE-NOCOOKIE',
842 Message => $r->_gt("You do not seem to have cookies".
843 " enabled. You must enable cookies".
844 " as we use them for login."),
845 _CookieRaw => $r->_fresh_secret(),
846 Params => $r->_chain_params() })
848 if (!$cookt || $cookt eq 'n' || $cookh ne $parmh) {
849 $r->_db_revoke($cookh);
850 return ({ Kind => 'LOGIN-STALE',
851 Message => $r->_gt("Stale session;".
852 " you need to log in again."),
853 _CookieRaw => $r->_fresh_secret(),
856 die unless $parmt eq 't' || $parmt eq 'y';
857 my ($username, $login_errormessage) = $r->_ch('login_ok');
858 unless (defined $username && length $username) {
859 $login_errormessage = $r->_gt("Incorrect username/password.")
860 if !$login_errormessage;
861 return ({ Kind => 'LOGIN-BAD',
862 Message => $login_errormessage,
863 _CookieRaw => $cooks,
864 Params => $r->_chain_params() })
866 $r->_db_record_login_ok($parmh,$username);
867 return ({ Kind => 'REDIRECT-LOGGEDIN',
868 Message => $r->_gt("Logging in..."),
869 _CookieRaw => $cooks,
870 Params => $r->_chain_params() });
875 die if $parmt eq 't';
877 if ($cookt eq 'y' && $parmt eq 'y' && $cookh ne $parmh) {
878 $r->_db_revoke($parmh) if $meth eq 'POST';
883 die unless !$cookt || $cookt eq 'n';
884 die unless !$parmt || $parmt eq 'n' || $parmt eq 'y';
885 my $news = $r->_fresh_secret();
886 if ($meth eq 'GET') {
887 return ({ Kind => 'LOGIN-INCOMINGLINK',
888 Message => $r->_gt("You need to log in."),
890 Params => $r->_chain_params() });
892 $r->_db_revoke($parmh);
893 return ({ Kind => 'LOGIN-FRESH',
894 Message => $r->_gt("You need to log in."),
900 if (!$r->{S}{promise_check_mutate}) {
901 if ($meth ne 'POST') {
902 return ({ Kind => 'MAINPAGEONLY',
903 Message => $r->_gt('Entering via cross-site link.'),
904 _CookieRaw => $cooks,
906 # NB caller must then ignore params & path!
907 # if this is too hard they can spit out a small form
908 # with a "click to continue"
912 die unless $cookt eq 'y';
913 unless ($r->{S}{promise_check_mutate} && $meth eq 'GET') {
914 die unless $parmt eq 'y';
915 die unless $cookh eq $parmh;
917 $r->{ParmT} = $parmt;
918 $r->{AssocRaw} = $cooks;
919 $r->{UserOK} = $cooku;
920 #print STDERR "C-D-C OK\n";
924 sub _chain_params ($) {
925 # =item C<< $authreq->_chain_params() >>
927 # Returns a hash of the "relevant" parameters to this request, in a form
928 # used by C<url_with_query_params>. This is all of the query parameters
929 # which are not related to CGI::Auth::Flexible. The PATH_INFO from the
930 # request is returned as the parameter C<< '' >>.
933 my %p = %{ $r->_ch('get_params') };
934 foreach my $pncn (keys %{ $r->{S} }) {
936 if ($pncn =~ m/_param_name$/) {
937 my $name = $r->{S}{$pncn};
938 die "$pncn ?" if ref $name;
940 } elsif ($pncn =~ m/_param_names$/) {
941 $names = $r->{S}{$pncn};
945 foreach my $name (@$names) {
949 my $dummy_prefix = $r->{S}{dummy_param_name_prefix};
950 foreach my $name (grep /^$dummy_prefix/, keys %p) {
953 die if exists $p{''};
954 $p{''} = [ $r->_ch('get_path_info') ];
960 # returns ($t,$username)
961 # where $t is one of "t" "y" "n", or "" (for -)
962 # either $s must be undef, or $h eq $r->hash($s)
964 #print STDERR "_identify\n";
965 return '' unless defined $h && length $h;
966 #print STDERR "_identify h=$h s=".(defined $s ? $s : '<undef>')."\n";
970 $dbh->do("DELETE FROM $r->{S}{db_prefix}_assocs".
971 " WHERE last < ?", {},
972 time - $r->{S}{login_timeout});
974 my $row = $dbh->selectrow_arrayref("SELECT username, last".
975 " FROM $r->{S}{db_prefix}_assocs".
976 " WHERE assochash = ?", {}, $h);
978 #print STDERR "_identify h=$h s=$s YES @$row\n";
979 my ($nusername, $nlast) = @$row;
980 return ('y', $nusername);
983 # Well, it's not in the database. But maybe it's a hash of a
986 return 'n' unless defined $s;
988 my ($keyt, $signature, $message, $noncet, $nonce) =
989 $s =~ m/^(\d+)\.(\w+)\.((\d+)\.(\w+))$/ or die;
991 return 'n' if time > $noncet + $r->{S}{login_form_timeout};
993 #print STDERR "_identify noncet=$noncet ok\n";
995 my $keys = $r->_open_keys();
996 while (my ($rkeyt, $rkey, $line) = $r->_read_key($keys)) {
997 #print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey\n";
998 last if $rkeyt < $keyt; # too far down in the file
999 my $trysignature = $r->_hmac($rkey, $message);
1000 #print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey try=$trysignature\n";
1001 return 't' if $trysignature eq $signature;
1004 #print STDERR "_identify NO\n";
1006 $keys->error and die $!;
1010 sub _db_revoke ($$) {
1011 # revokes $h if it's valid; no-op if it's not
1014 my $dbh = $r->{Dbh};
1016 $dbh->do("DELETE FROM $r->{S}{db_prefix}_assocs".
1017 " WHERE assochash = ?", {}, $h);
1020 sub _db_record_login_ok ($$$) {
1021 my ($r,$h,$user) = @_;
1023 my $dbh = $r->{Dbh};
1024 $dbh->do("INSERT INTO $r->{S}{db_prefix}_assocs".
1025 " (assochash, username, last) VALUES (?,?,?)", {},
1029 sub check_divert ($) {
1031 if (exists $r->{Divert}) {
1032 return $r->{Divert};
1034 my $dbh = $r->{Dbh};
1035 $r->{Divert} = $r->_db_transaction(sub { $r->_check_divert_core(); });
1038 my $cookraw = $r->{_CookieRaw};
1039 $r->{CookieSecret} = $r->_blind($cookraw);
1041 $r->{Params}{$r->{S}{assoc_param_name}} = [
1042 $r->_blind($r->hash($cookraw))
1046 $r->_debug(Data::Dumper->Dump([$r->{Divert}],[qw(divert)]));
1047 return $r->{Divert};
1050 sub get_divert ($) {
1052 die "unchecked" unless exists $r->{Divert};
1053 return $r->{Divert};
1056 sub get_username ($) {
1058 my $divert = $r->get_divert();
1059 return undef if $divert;
1060 return $r->{UserOK};
1063 sub url_with_query_params ($$;$) {
1064 my ($r, $params, $nonpagetype) = @_;
1065 #print STDERR "PARAMS ",Dumper($params);
1066 my $uri = URI->new($r->_ch('get_url'));
1067 $uri->path($uri->path() . $params->{''}[0]) if $params->{''};
1068 my @flatparams = flatten_params($params);
1069 if (defined $nonpagetype && $r->need_add_hidden('GET',$nonpagetype)) {
1070 push @flatparams, $r->{S}{assoc_param_name}, $r->secret_hidden_val();
1072 $uri->query_form(@flatparams);
1073 return $uri->as_string();
1076 sub _cgi_header_args ($$@) {
1077 my ($r, $cookie, @ha) = @_;
1078 unshift @ha, qw(-type text/html);
1079 push @ha, (-cookie => $cookie) if defined $cookie;
1080 #print STDERR "_cgi_header_args ",join('|',@ha),".\n";
1087 my ($divert) = $r->check_divert();
1088 return 1 if !$divert;
1090 my $handled = $r->_ch('handle_divert',$divert);
1091 return 0 if $handled;
1093 my $kind = $divert->{Kind};
1094 my $cookiesecret = $divert->{CookieSecret};
1095 my $params = $divert->{Params};
1096 my $cookie = $r->construct_cookie($cookiesecret);
1098 if ($kind =~ m/^SRCDUMP-(\w+)$/) {
1099 $r->_ch('srcdump_dump', (lc $1));
1103 if ($kind =~ m/^REDIRECT-/) {
1104 # for redirects, we honour stored Params and Cookie,
1105 # as we would for non-divert
1106 if ($kind eq 'REDIRECT-LOGGEDOUT') {
1107 } elsif ($kind =~ m/REDIRECT-(?:LOGGEDIN|HTTPS)/) {
1111 my $new_url = $r->url_with_query_params($params);
1112 if ($kind eq 'REDIRECT-HTTPS') {
1113 my $uri = URI->new($new_url);
1114 die unless $uri->scheme eq 'http';
1115 $uri->scheme('https');
1116 $new_url = $uri->as_string();
1118 $r->_ch('do_redirect',$new_url, $cookie);
1123 if ($kind =~ m/^LOGIN-/) {
1124 $title = $r->_gt('Login');
1125 push @body, $divert->{Message};
1126 push @body, $r->_ch('gen_login_form', $params);
1127 } elsif ($kind =~ m/^SMALLPAGE-/) {
1128 $title = $r->_gt('Not logged in');
1129 push @body, $divert->{Message};
1130 push @body, $r->_ch('gen_login_link', $params);
1131 } elsif ($kind =~ m/^MAINPAGEONLY$/) {
1132 $title = $r->_gt('Entering secure site.');
1133 push @body, $divert->{Message};
1134 push @body, $r->_ch('gen_postmainpage_form', $params);
1139 $r->_print($r->{Cgi}->header($r->_cgi_header_args($cookie)),
1140 $r->_ch('gen_start_html',$title),
1142 $r->_ch('gen_footer_html'),
1143 $r->_ch('gen_end_html'))));
1148 my ($r, $bytes) = @_;
1150 my $rsf = $v->{RandomHandle};
1151 my $rsp = $r->{S}{random_source};
1153 $v->{RandomHandle} = $rsf = new IO::File $rsp, '<' or die "$rsp $!";
1154 #print STDERR "RH $rsf\n";
1158 read($rsf,$bin,$bytes) == $bytes or die "$rsp $!";
1159 my $out = unpack "H*", $bin;
1160 #print STDERR "_random out $out\n";
1164 sub _blind_len ($$) {
1166 return length($str =~ y/0-9a-f//cdr);
1169 sub _blind_combine ($$$) {
1170 my ($r, $in, $mask) = @_;
1171 my @mask = split //, $mask;
1173 my $m = shift @mask;
1174 sprintf "%x", hex($m) ^ hex($&);
1181 return $in unless $in;
1182 my $l = $r->_blind_len($in);
1183 my $mask = $r->_random(($l+1)>>1);
1184 $mask = substr $mask, 0, $l;
1185 my $blound = $r->_blind_combine($in, $mask);
1186 return "$blound/$mask";
1191 return $in unless $in;
1192 my ($blound,$mask) = ($in =~ m#^(.*)/([0-9a-f]+)$#) or die "$in ?";
1193 my $l = $r->_blind_len($blound);
1194 $l == length($mask) or die "$in ?";
1195 return $r->_blind_combine($blound, $mask);
1198 sub _random_key ($) {
1200 #print STDERR "_random_key\n";
1201 my $bytes = ($r->{S}{secretbits} + 7) >> 3;
1202 return $r->_random($bytes);
1205 sub _read_key ($$) {
1206 my ($r, $keys) = @_;
1207 # returns $gen_time_t, $key_value_in_hex, $complete_line
1209 my ($gen, $k) = m/^(\d+) (\S+)$/ or die "$_ ?";
1210 my $age = time - $gen;
1211 next if $age > $r->{S}{key_rollover} &&
1212 $age > $r->{S}{login_form_timeout}*2;
1213 return ($gen, $k, $_);
1218 sub _open_keys ($) {
1220 my $spath = $r->_get_path('keys');
1222 #print STDERR "_open_keys\n";
1223 my $keys = new IO::File $spath, 'r+';
1225 #print STDERR "_open_keys open\n";
1226 stat $keys or die $!; # NB must not disturb stat _
1227 my $size = (stat _)[7];
1228 my $age = time - (stat _)[9];
1229 #print STDERR "_open_keys open size=$size age=$age\n";
1231 if $size && $age <= $r->{S}{key_rollover} / 2;
1232 #print STDERR "_open_keys open bad\n";
1234 # file doesn't exist, or is empty or too old
1236 #print STDERR "_open_keys closed\n";
1237 die "$spath $!" unless $!==&ENOENT;
1238 # doesn't exist, so create it just so we can lock it
1239 $keys = new IO::File $spath, 'a+';
1240 die "$keys $!" unless $keys;
1241 stat $keys or die $!; # NB must not disturb stat _
1242 my $size = (stat _)[7];
1243 #print STDERR "_open_keys created size=$size\n";
1244 next if $size; # oh someone else has done it, reopen and read it
1246 # file now exists is empty or too old, we must try to replace it
1247 my $our_inum = (stat _)[1]; # last use of that stat _
1248 flock $keys, LOCK_EX or die "$spath $!";
1249 stat $spath or die "$spath $!";
1250 my $path_inum = (stat _)[1];
1251 #print STDERR "_open_keys locked our=$our_inum path=$path_inum\n";
1252 next if $our_inum != $path_inum; # someone else has done it
1253 # We now hold the lock!
1254 #print STDERR "_open_keys creating\n";
1255 my $newkeys = new IO::Handle;
1256 sysopen $newkeys, "$spath.new", O_CREAT|O_TRUNC|O_WRONLY, 0600
1257 or die "$spath.new $!";
1258 # we add the new key to the front which means it's always sorted
1259 print $newkeys time, ' ', $r->_random_key(), "\n" or die $!;
1260 while (my ($gen,$key,$line) = $r->_read_key($keys)) {
1261 #print STDERR "_open_keys copy1\n";
1262 print $newkeys, $line or die $!;
1264 $keys->error and die $!;
1265 close $newkeys or die "$spath.new $!";
1266 rename "$spath.new", "$spath" or die "$spath: $!";
1267 #print STDERR "_open_keys installed\n";
1268 # that rename effective unlocks, since it makes the name refer
1269 # to the new file which we haven't locked
1270 # we go round again opening the file at the beginning
1271 # so that our caller gets a fresh handle onto the existing key file
1275 sub _fresh_secret ($) {
1277 #print STDERR "_fresh_secret\n";
1279 my $keys = $r->_open_keys();
1280 my ($keyt, $key) = $r->_read_key($keys);
1281 die unless defined $keyt;
1283 my $nonce = $r->_random_key();
1285 my $message = "$noncet.$nonce";
1287 my $signature = $r->_hmac($key, $message);
1288 my $secret = "$keyt.$signature.$message";
1289 #print STDERR "FRESH $secret\n";
1294 my ($r, $keyhex, $message) = @_;
1295 my $keybin = pack "H*", $keyhex;
1296 my $alg = $r->{S}{hash_algorithm};
1297 #print STDERR "hmac $alg\n";
1298 my $base = new Digest $alg;
1299 #print STDERR "hmac $alg $base\n";
1300 my $digest = new Digest::HMAC $keybin, $base;
1301 #print STDERR "hmac $alg $base $digest\n";
1302 $digest->add($message);
1303 return $digest->hexdigest();
1307 my ($r, $message) = @_;
1308 my $alg = $r->{S}{hash_algorithm};
1309 #print STDERR "hash $alg\n";
1310 my $digest = new Digest $alg;
1311 $digest->add($message);
1312 return $digest->hexdigest();
1315 sub _assert_checked ($) {
1317 die "unchecked" unless exists $r->{Divert};
1322 my $meth = $r->_ch('get_method');
1323 return $meth eq 'POST';
1326 sub _must_be_post ($) {
1328 my $meth = $r->_ch('get_method');
1329 die "mutating non-POST" if $meth ne 'POST';
1332 sub check_mutate ($) {
1334 $r->_assert_checked();
1335 die if $r->{Divert};
1336 $r->_must_be_post();
1339 our %_resource_get_needs_secret_hidden =
1340 (map { $_ => 0 } qw(PAGE FRAME IFRAME SRCDUMP STYLESHEET FAVICON ROBOTS),
1341 map { $_ => 1 } qw(IMAGE SCRIPT AJAX-XML AJAX-JSON AJAX-OTHER));
1343 sub update_get_need_add_hidden ($$;$) {
1344 my ($r, $reqtype, $value, $force) = @_;
1346 ? ($r->{GetNeedsSecretHidden} ||= { })
1347 : \%_resource_get_needs_secret_hidden;
1348 return if !$force &&
1349 (exists $_resource_get_needs_secret_hidden{$reqtype} ||
1350 exists $hash->{$reqtype});
1351 $hash->{$reqtype} = $value;
1354 sub need_add_hidden ($$) {
1355 my ($r, $method, $reqtype) = @_;
1356 return 1 if $method ne 'GET';
1358 my $ent = $r->{GetNeedsSecretHidden}{$reqtype};
1359 return $ent if defined $ent;
1361 my $ent = $_resource_get_needs_secret_hidden{$reqtype};
1362 return $ent if defined $ent;
1363 die "unsupported nonpage GET type $reqtype";
1366 sub check_nonpage ($$) {
1367 my ($r, $reqtype) = @_;
1368 $r->_assert_checked();
1369 return unless $r->resource_get_needs_secret_hidden($reqtype);
1370 return if $r->{ParmT};
1371 die "missing hidden secret parameter on nonpage request $reqtype";
1374 #---------- output ----------
1376 sub secret_cookie_val ($) {
1378 $r->_assert_checked();
1379 return defined $r->{AssocRaw} ? $r->_blind($r->{AssocRaw}) : '';
1382 sub secret_hidden_val ($) {
1384 $r->_assert_checked();
1385 return defined $r->{AssocRaw} ? $r->_blind($r->hash($r->{AssocRaw})) : '';
1388 sub secret_hidden_html ($) {
1390 return $r->{Cgi}->hidden(-name => $r->{S}{assoc_param_name},
1391 -default => $r->secret_hidden_val());
1394 sub secret_cookie ($) {
1396 my $secret = $r->secret_cookie_val();
1397 return undef if !defined $secret;
1398 #print STDERR "SC\n";
1399 my $cookv = $r->construct_cookie($secret);
1400 #print STDERR "SC=$cookv\n";