3 # This is part of CGI::Auth::Flexible, a perl CGI authentication module.
4 # Copyright (C) 2012 Ian Jackson.
5 # Copyright (C) 2012 Citrix.
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 use warnings FATAL => 'all';
23 package CGI::Auth::Flexible;
28 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
33 %EXPORT_TAGS = ( ); # eg: TAG => [ qw!name1 name2! ],
40 use CGI qw/escapeHTML/;
54 #---------- public utilities ----------
56 sub flatten_params ($) {
59 foreach my $k (keys %$p) {
61 foreach my $v (@{ $p->{$k} }) {
68 #---------- default callbacks ----------
70 sub has_a_param ($$) {
72 foreach my $pn (@{ $r->{S}{$cn} }) {
73 return 1 if $r->_ch('get_param',$pn);
82 foreach my $name ($c->param()) {
83 $p{$name} = [ $c->param($name) ];
88 sub get_cookie_domain ($$$) {
90 my $uri = new URI $r->_ch('get_url');
94 sub login_ok_password ($$) {
96 my $username_params = $r->{S}{username_param_names};
97 my $username = $r->_ch('get_param',$username_params->[0]);
98 my $password = $r->_rp('password_param_name');
99 my $error = $r->_ch('username_password_error', $username, $password);
100 return defined($error) ? (undef,$error) : ($username,undef);
103 sub do_redirect_cgi ($$$$) {
104 my ($c, $r, $new_url, $cookie) = @_;
105 $r->_print($c->header($r->_cgi_header_args($cookie,
106 -status => '303 See other',
107 -location => $new_url)),
108 $r->_ch('gen_start_html',$r->_gt('Redirection')),
109 '<a href="'.escapeHTML($new_url).'">',
110 $r->_gt("If you aren't redirected, click to continue."),
112 $r->_ch('gen_end_html'));
115 sub gen_some_form ($$) {
116 my ($r, $params, $bodyfn) = @_;
117 # Calls $bodyfn->($c,$r) which returns @formbits
121 $pathinfo .= $params->{''}[0] if $params->{''};
122 push @form, ('<form method="POST" action="'.
123 escapeHTML($r->_ch('get_url').$pathinfo).'">');
124 push @form, $bodyfn->($c,$r);
125 foreach my $n (keys %$params) {
127 foreach my $val (@{ $params->{$n} }) {
128 push @form, ('<input type="hidden"'.
129 ' name="'.escapeHTML($n).'"'.
130 ' value="'.escapeHTML($val).'">');
133 push @form, ('</form>');
134 return join "\n", @form;
137 sub gen_plain_login_form ($$) {
138 my ($c,$r, $params) = @_;
139 return $r->gen_some_form($params, sub {
141 push @form, ('<table>');
142 my $sz = 'size="'.$r->{S}{form_entry_size}.'"';
143 foreach my $up (@{ $r->{S}{username_param_names}}) {
144 push @form, ('<tr><td>',$r->_gt(ucfirst $up),'</td>',
145 '<td><input type="text" '.$sz.
146 ' name='.$up.'></td></tr>');
148 push @form, ('<tr><td>'.$r->_gt('Password').'</td>',
149 '<td><input type="password" '.$sz.
150 ' name="'.$r->{S}{password_param_name}.'"></td></tr>');
151 push @form, ('<tr><td colspan="2">',
152 '<input type="submit"'.
153 ' name="'.$r->{S}{dummy_param_name_prefix}.'login"'.
154 ' value="'.$r->_gt('Login').'"></td></tr>',
160 sub gen_postmainpage_form ($$$) {
161 my ($c,$r, $params) = @_;
162 return $r->gen_some_form($params, sub {
164 push @form, ('<input type="submit"',
165 ' name="'.$r->{S}{dummy_param_name_prefix}.'submit"'.
166 ' value="'.$r->_gt('Continue').'">');
171 sub gen_plain_login_link ($$) {
172 my ($c,$r, $params) = @_;
173 my $url = $r->url_with_query_params($params);
174 return ('<a href="'.escapeHTML($url).'">'.
175 $r->_gt('Log in again to continue.').
179 sub gen_srcdump_link_html ($$$$) {
180 my ($c,$r,$anchor,$specval) = @_;
181 my %params = ($r->{S}{srcdump_param_name} => [ $specval ]);
182 return '<a href="'.escapeHTML($r->url_with_query_params(\%params)).'">'.
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_'.lc $&),
257 $dumpdir, $upwards, $outfn);
259 $upwards =~ s#/*[^/]+$##;
261 return $v->_ch('srcdump_novcs', $dumpdir, $item, $outfn);
264 sub srcdump_novcs ($$$$$) {
265 my ($c, $v, $dumpdir, $item, $outfn) = @_;
266 stat $item or die "$item $!";
268 my $script = 'find -type f -perm +004';
269 foreach my $excl (@{ $v->{S}{srcdump_excludes} }) {
270 $script .= " \\! -name '$excl'";
272 $script .= " -print0";
273 return srcdump_dir_cpio($c,$v,$dumpdir,$item,$outfn,'novcs',$script);
275 return srcdump_file($c,$v,$dumpdir,$item,$outfn);
277 die "$item not file or directory";
281 sub srcdump_byvcs_git ($$$$$) {
282 my ($c, $v, $dumpdir, $dir, $outfn) = @_;
283 #print STDERR "BYVCS GIT $dir\n";
284 return srcdump_dir_cpio($c,$v,$dumpdir,$dir,$outfn,'git',"
286 git ls-files -z --others --exclude-from=.gitignore
291 sub srcdump_file ($$$$) {
292 my ($c,$v,$dumpdir,$file,$outfn) = @_;
293 my $outfile = $outfn->("srcdump_file saved $file", "src");
294 copy($file,$outfile) or die "$file $outfile $!";
297 sub srcdump_dir_cpio ($$$$$$$) {
298 my ($c,$v,$dumpdir,$dir,$outfn,$how,$script) = @_;
299 my $outfile = $outfn->("srcdump_dir_cpio $how saved $dir", "tar");
300 #print STDERR "CPIO $dir >$script<\n";
302 defined $pid or die $!;
304 $SIG{__DIE__} = sub {
305 print STDERR "CGI::Auth::Flexible srcdump error: $@\n";
308 open STDOUT, ">", $outfile or die "$outfile $!";
309 chdir $dir or die "chdir $dir: $!";
310 exec '/bin/bash','-ec',"
315 cpio -Hustar -o --quiet -0 -R 1000:1000 || \
316 cpio -Hustar -o --quiet -0
321 $!=0; (waitpid $pid, 0) == $pid or die "$!";
322 die "$dir ($script) $outfile $?" if $?;
325 sub srcdump_dirscan_prepare ($$) {
327 my $dumpdir = $v->_get_path('srcdump');
328 mkdir $dumpdir or $!==&EEXIST or die "mkdir $dumpdir $!";
329 my $lockf = new IO::File "$dumpdir/generate.lock", 'w+'
330 or die "$dumpdir/generate.lock $!";
331 flock $lockf, LOCK_EX or die "$dumpdir/generate.lock $!";
332 my $needlicence = "$dumpdir/licence.tmp";
333 unlink $needlicence or $!==&ENOENT or die "rm $needlicence $!";
334 if (defined $v->{S}{srcdump_licence_path}) {
335 copy($v->{S}{srcdump_licence_path}, $needlicence)
336 or die "$v->{S}{srcdump_licence_path} $!";
337 $needlicence = undef;
339 unlink <"$dumpdir/s.[a-z][a-z][a-z].*">;
340 my @srcfiles = qw(licence.data manifest.txt);
341 my $srcoutcounter = 'aaa';
343 my $reportfh = new IO::File "$dumpdir/manifest.txt", 'w' or die $!;
345 my ($message, $extension) = @_;
346 if (defined $extension) {
347 my $leaf = "s.$srcoutcounter.$extension";
349 push @srcfiles, $leaf;
350 print $reportfh "$leaf: $message\n" or die $!;
351 return "$dumpdir/$leaf";
353 print $reportfh "none: $message\n" or die $!;
358 foreach my $item ($v->_ch('srcdump_listitems')) {
359 if ($item eq '.' && $v->{S}{srcdump_filter_cwd}) {
360 my @bad = grep { !m#^/# } values %INC;
361 die "filtering . from srcdump items and \@INC but already".
362 " included @bad " if @bad;
363 @INC = grep { $_ ne '.' } @INC;
366 if (!lstat "$item") {
367 die "stat $item $!" unless $!==&ENOENT;
368 $outfn->("srcdump_dirscan_prepare stat ENOENT, skipping $item");
372 $item = realpath($item);
373 if (!defined $item) {
374 die "realpath $item $!" unless $!==&ENOENT;
375 $outfn->("srcdump_dirscan_prepare realpath ENOENT,".
379 if (defined $needlicence) {
380 foreach my $try (@{ $v->{S}{srcdump_licence_files} }) {
381 last if copy("$item/$try", $needlicence);
382 $!==&ENOENT or $!==&ENOTDIR or die "copy $item/$try $!";
385 $v->_ch('srcdump_process_item', $dumpdir, $item,
386 $outfn, \$needlicence, \%dirsdone);
389 close $reportfh or die $!;
391 my @cmd = (qw(tar -zvvcf), "$dumpdir/source.tmp",
392 "-C", $dumpdir, qw( --), @srcfiles);
393 my $r = system(@cmd);
395 print STDERR "CGI::Auth::Flexible tar failed ($r $!) @cmd\n";
398 die "licence file not found" unless defined $needlicence;
399 srcdump_install($c,$v, $dumpdir, 'licence', 'text/plain');
400 srcdump_install($c,$v, $dumpdir, 'source', 'application/octet-stream');
401 close $lockf or die $!;
404 sub srcdump_install ($$$$$) {
405 my ($c,$v, $dumpdir, $which, $ctype) = @_;
406 rename "$dumpdir/$which.tmp", "$dumpdir/$which.data"
407 or die "$dumpdir/$which.data $!";
408 my $ctf = new IO::File "$dumpdir/$which.tmp", 'w'
409 or die "$dumpdir/$which.tmp $!";
410 print $ctf $ctype, "\n" or die $!;
411 close $ctf or die $!;
412 rename "$dumpdir/$which.tmp", "$dumpdir/$which.ctype"
413 or die "$dumpdir/$which.ctype $!";
416 #---------- verifier object methods ----------
423 assocdb_dbh => undef, # must have AutoCommit=0, RaiseError=1
424 assocdb_path => 'caf-assocs.db',
425 keys_path => 'caf-keys',
426 srcdump_path => 'caf-srcdump',
427 assocdb_dsn => undef,
429 assocdb_password => '',
430 assocdb_table => 'caf_assocs',
431 random_source => '/dev/urandom',
432 secretbits => 128, # bits
433 hash_algorithm => "SHA-256",
434 login_timeout => 86400, # seconds
435 login_form_timeout => 3600, # seconds
436 key_rollover => 86400, # seconds
437 assoc_param_name => 'caf_assochash',
438 dummy_param_name_prefix => 'caf__',
439 cookie_name => "caf_assocsecret",
440 password_param_name => 'password',
441 srcdump_param_name => 'caf_srcdump',
442 username_param_names => [qw(username)],
443 form_entry_size => 60,
444 logout_param_names => [qw(caf_logout)],
445 loggedout_param_names => [qw(caf_loggedout)],
446 promise_check_mutate => 0,
447 get_param => sub { $_[0]->param($_[2]) },
448 get_params => sub { $_[1]->get_params() },
449 get_path_info => sub { $_[0]->path_info() },
450 get_cookie => sub { $_[0]->cookie($_[1]->{S}{cookie_name}) },
451 get_method => sub { $_[0]->request_method() },
452 check_https => sub { !!$_[0]->https() },
453 get_url => sub { $_[0]->url(); },
454 is_login => sub { defined $_[1]->_rp('password_param_name') },
455 login_ok => \&login_ok_password,
456 username_password_error => sub { die },
457 is_logout => sub { $_[1]->has_a_param('logout_param_names') },
458 is_loggedout => sub { $_[1]->has_a_param('loggedout_param_names') },
459 is_page => sub { return 1 },
460 handle_divert => sub { return 0 },
461 do_redirect => \&do_redirect_cgi, # this hook is allowed to throw
463 get_cookie_domain => \&get_cookie_domain,
465 gen_start_html => sub { $_[0]->start_html($_[2]); },
466 gen_footer_html => \&gen_plain_footer_html,
467 gen_licence_link_html => \&gen_plain_licence_link_html,
468 gen_source_link_html => \&gen_plain_source_link_html,
469 gen_end_html => sub { $_[0]->end_html(); },
470 gen_login_form => \&gen_plain_login_form,
471 gen_login_link => \&gen_plain_login_link,
472 gen_postmainpage_form => \&gen_postmainpage_form,
473 srcdump_dump => \&srcdump_dump,
474 srcdump_prepare => \&srcdump_dirscan_prepare,
475 srcdump_licence_path => undef,
476 srcdump_licence_files => [qw(AGPLv3 CGI/Auth/Flexible/AGPLv3)],
477 srcdump_listitems => sub { (@INC, $ENV{'SCRIPT_FILENAME'}, $0); },
478 srcdump_filter_cwd => 1,
479 srcdump_system_dir => sub {
480 $_[2] =~ m#^/etc/|^/usr/(?!local/)(?!lib/cgi)#;
482 srcdump_process_item => \&srcdump_process_item,
483 srcdump_vcs_dirs => [qw(.git .hg .svn CVS)],
484 srcdump_byvcs_git => \&srcdump_byvcs_git,
485 srcdump_byvcs_hg => \&srcdump_byvcs_hg,
486 srcdump_byvcs_svn => \&srcdump_byvcs_svn,
487 srcdump_byvcs_cvs => \&srcdump_byvcs_cvs,
488 srcdump_novcs => \&srcdump_novcs,
489 srcdump_excludes => [qw(*~ *.bak *.tmp), '#*#'],
490 dump => \&dump_plain,
491 gettext => sub { gettext($_[2]); },
492 print => sub { print $_[2] or die $!; },
493 debug => sub { }, # like print; msgs contain trailing \n
498 while (($k,$v,@_) = @_) {
499 die "unknown setting $k" unless exists $verifier->{S}{$k};
500 $verifier->{S}{$k} = $v;
502 bless $verifier, $class;
503 $verifier->_dbopen();
504 $verifier->_ch('srcdump_prepare');
508 sub _db_setup_do ($$) {
512 $v->_db_transaction(sub {
513 local ($dbh->{PrintError}) = 0;
524 $dbh = $v->{S}{assocdb_dbh};
526 die if $dbh->{AutoCommit};
527 die unless $dbh->{RaiseError};
529 $v->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=".$v->_get_path('assocdb');
530 my $dsn = $v->{S}{assocdb_dsn};
533 $dbh = DBI->connect($dsn, $v->{S}{assocdb_user},
534 $v->{S}{assocdb_password}, {
537 ShowErrorStatement => 1,
540 die "$dsn $! ?" unless $dbh;
544 $v->_db_setup_do("CREATE TABLE $v->{S}{assocdb_table} (".
545 " assochash VARCHAR PRIMARY KEY,".
546 " username VARCHAR NOT NULL,".
547 " last INTEGER NOT NULL".
549 $v->_db_setup_do("CREATE INDEX $v->{S}{assocdb_table}_timeout_index".
550 " ON $v->{S}{assocdb_table}".
562 sub _db_transaction ($$) {
567 #print STDERR "DT entry\n";
569 #print STDERR "DT loop\n";
572 #print STDERR "DT fn ok\n";
575 #print STDERR "DT fn error\n";
576 { local ($@); $dbh->rollback(); }
577 #print STDERR "DT fn throwing\n";
580 #print STDERR "DT fn eval ok\n";
583 #print STDERR "DT commit ok\n";
586 #print STDERR "DT commit eval ok ",Dumper($rv);
589 #print STDERR "DT commit throw?\n";
590 die $@ if !--$retries;
591 #print STDERR "DT loop again\n";
595 #---------- request object methods ----------
598 my ($classbase, $cgi, @extra) = @_;
599 if (!ref $classbase) {
600 $classbase = $classbase->new_verifier(@extra);
606 S => $classbase->{S},
607 Dbh => $classbase->{Dbh},
610 bless $r, ref $classbase;
613 sub _ch ($$@) { # calls an application hook
614 my ($r,$methname, @args) = @_;
615 my $methfunc = $r->{S}{$methname};
616 die "$methname ?" unless $methfunc;
617 return $methfunc->($r->{Cgi}, $r, @args);
622 my $pn = $r->{S}{$pnvb};
623 my $p = scalar $r->_ch('get_param',$pn)
628 $r->_ch('debug',@args);
632 my ($r,$keybase) = @_;
633 my $leaf = $r->{S}{"${keybase}_path"};
634 return $r->_absify_path($leaf);
637 sub _absify_path ($$) {
639 return $leaf if $leaf =~ m,^/,;
640 my $dir = $v->{S}{dir};
641 die "relying on cwd by default ?! set dir" unless defined $dir;
645 sub _gt ($$) { my ($r, $t) = @_; return $r->_ch('gettext',$t); }
646 sub _print ($$) { my ($r, @t) = @_; return $r->_ch('print', join '', @t); }
648 sub construct_cookie ($$$) {
649 my ($r, $cooks) = @_;
650 return undef unless $cooks;
652 my @ca = (-name => $r->{S}{cookie_name},
654 -path => $r->{S}{cookie_path},
655 -domain => $r->_ch('get_cookie_domain'),
656 -expires => '+'.$r->{S}{login_timeout}.'s',
657 -secure => $r->{S}{encrypted_only});
658 my $cookie = $c->cookie(@ca);
659 #print STDERR "CC $r $c $cooks $cookie (@ca).\n";
663 # pages/param-sets are
664 # n normal non-mutating page
665 # r retrieval of information for JS, non-mutating
667 # u update of information by JS, mutating
670 # O "you have just logged out" page load
673 # - no value supplied (represented in code as $cookt='')
674 # n, nN value not in our db
675 # t, tN temporary value (in our db, no logged in user yet)
676 # y, yN value corresponds to logged-in user
677 # and, aggregated conditions:
678 # a, aN anything including -
680 # if N differs the case applies only when the two values differ
681 # (eg, a1 y2 does not apply when the logged-in value is supplied twice)
683 # "stale session" means request originates from a page from a login
684 # session which has been revoked (eg by logout); "cleared session"
685 # means request originates from a browser which has a different (or
688 # Case analysis, cookie mode, app promises re mutate:
689 # cook parm meth form
691 # any - POST nrmuoi bug or attack, fail
692 # any - GET rmuoi bug or attack, fail
693 # any any GET muoi bug or attack, fail
694 # any t any nrmu bug or attack, fail
696 # - - GET O "just logged out" page
697 # (any other) O bug or attack, fail
699 # a1 a2 POST o logout
700 # if a1 is valid, revoke it
701 # if a2 is valid, revoke it
703 # redirect to "just logged out" page
704 # (which contains link to login form)
706 # - t POST i complain about cookies being disabled
707 # (with link to login form)
709 # t1 t1 POST i login (or switch user)
711 # show new login form
713 # upgrade t1 to y1 in our db (setting username)
714 # redirect to GET of remaining params
716 # y1 a2 POST i complain about stale login form
718 # show new login form
720 # (other) POST i complain about stale login form
721 # show new login form
723 # t1 a2 ANY nrmu treat as - a2 ANY
725 # y - GET n cross-site link
728 # y y GET nr fine, show page or send data
729 # y y POST nrmu mutation is OK, do operation
731 # y1 y2 GET nr request from stale page
732 # do not revoke y2 as not RESTful
735 # y1 y2 POST nrmu request from stale page
739 # y n GET n intra-site link from stale page,
740 # treat as cross-site link, show data
742 # y n POST n m intra-site form submission from stale page
743 # show "session interrupted"
744 # with link to main data page
746 # y n GET r intra-site request from stale page
749 # y n POST r u intra-site request from stale page
752 # -/n y2 GET nr intra-site link from cleared session
753 # do not revoke y2 as not RESTful
756 # -/n y2 POST nrmu request from cleared session
758 # treat as -/n n POST
760 # -/n -/n GET n cross-site link but user not logged in
761 # show login form with redirect to orig params
762 # generate fresh cookie
764 # -/n n GET rmu user not logged in
767 # -/n n POST n m user not logged in
770 # -/n n POST r u user not logged in
773 sub _check_divert_core ($) {
776 my $srcdump = $r->_rp('srcdump_param_name');
778 die if $srcdump =~ m/\W/;
779 return ({ Kind => 'SRCDUMP-'.uc $srcdump,
781 CookieSecret => undef,
785 my $cooks = $r->_ch('get_cookie');
787 if ($r->{S}{encrypted_only} && !$r->_ch('check_https')) {
788 return ({ Kind => 'REDIRECT-HTTPS',
789 Message => $r->_gt("Redirecting to secure server..."),
790 CookieSecret => undef,
794 my $meth = $r->_ch('get_method');
795 my $parmh = $r->_rp('assoc_param_name');
796 my $cookh = defined $cooks ? $r->hash($cooks) : undef;
798 my ($cookt,$cooku) = $r->_identify($cookh, $cooks);
799 my $parms = (defined $cooks && defined $parmh && $parmh eq $cookh)
801 my ($parmt) = $r->_identify($parmh, $parms);
803 $r->_debug("_c_d_c cookt=$cookt parmt=$parmt\n");
805 if ($r->_ch('is_logout')) {
808 $r->_db_revoke($cookh);
809 $r->_db_revoke($parmh);
810 return ({ Kind => 'REDIRECT-LOGGEDOUT',
811 Message => $r->_gt("Logging out..."),
815 if ($r->_ch('is_loggedout')) {
816 die unless $meth eq 'GET';
817 die if $cookt eq 'y';
819 return ({ Kind => 'SMALLPAGE-LOGGEDOUT',
820 Message => $r->_gt("You have been logged out."),
824 if ($r->_ch('is_login')) {
827 if (!$cookt && $parmt eq 'n') {
828 return ({ Kind => 'SMALLPAGE-NOCOOKIE',
829 Message => $r->_gt("You do not seem to have cookies".
830 " enabled. You must enable cookies".
831 " as we use them for login."),
832 CookieSecret => $r->_fresh_secret(),
833 Params => $r->chain_params() })
835 if (!$cookt || $cookt eq 'n' || $cookh ne $parmh) {
836 $r->_db_revoke($cookh);
837 return ({ Kind => 'LOGIN-STALE',
838 Message => $r->_gt("Stale session;".
839 " you need to log in again."),
840 CookieSecret => $r->_fresh_secret(),
843 die unless $parmt eq 't' || $parmt eq 'y';
844 my ($username, $login_errormessage) = $r->_ch('login_ok');
845 unless (defined $username && length $username) {
846 $login_errormessage = $r->_gt("Incorrect username/password.")
847 if !$login_errormessage;
848 return ({ Kind => 'LOGIN-BAD',
849 Message => $login_errormessage,
850 CookieSecret => $cooks,
851 Params => $r->chain_params() })
853 $r->_db_record_login_ok($parmh,$username);
854 return ({ Kind => 'REDIRECT-LOGGEDIN',
855 Message => $r->_gt("Logging in..."),
856 CookieSecret => $cooks,
857 Params => $r->chain_params() });
862 die if $parmt eq 't';
864 if ($cookt eq 'y' && $parmt eq 'y' && $cookh ne $parmh) {
865 $r->_db_revoke($parmh) if $meth eq 'POST';
870 die unless !$cookt || $cookt eq 'n';
871 die unless !$parmt || $parmt eq 'n' || $parmt eq 'y';
872 my $news = $r->_fresh_secret();
873 if ($meth eq 'GET') {
874 return ({ Kind => 'LOGIN-INCOMINGLINK',
875 Message => $r->_gt("You need to log in."),
876 CookieSecret => $news,
877 Params => $r->chain_params() });
879 $r->_db_revoke($parmh);
880 return ({ Kind => 'LOGIN-FRESH',
881 Message => $r->_gt("You need to log in."),
882 CookieSecret => $news,
887 if (!$r->{S}{promise_check_mutate}) {
888 if ($meth ne 'POST') {
889 return ({ Kind => 'MAINPAGEONLY',
890 Message => $r->_gt('Entering via cross-site link.'),
891 CookieSecret => $cooks,
893 # NB caller must then ignore params & path!
894 # if this is too hard they can spit out a small form
895 # with a "click to continue"
899 die unless $cookt eq 'y';
900 unless ($r->{S}{promise_check_mutate} && $meth eq 'GET') {
901 die unless $parmt eq 'y';
902 die unless $cookh eq $parmh;
904 $r->{AssocSecret} = $cooks;
905 $r->{UserOK} = $cooku;
906 #print STDERR "C-D-C OK\n";
910 sub chain_params ($) {
912 my %p = %{ $r->_ch('get_params') };
913 foreach my $pncn (keys %{ $r->{S} }) {
915 if ($pncn =~ m/_param_name$/) {
916 my $name = $r->{S}{$pncn};
917 die "$pncn ?" if ref $name;
919 } elsif ($pncn =~ m/_param_names$/) {
920 $names = $r->{S}{$pncn};
924 foreach my $name (@$names) {
928 my $dummy_prefix = $r->{S}{dummy_param_name_prefix};
929 foreach my $name (grep /^$dummy_prefix/, keys %p) {
932 die if exists $p{''};
933 $p{''} = [ $r->_ch('get_path_info') ];
939 # returns ($t,$username)
940 # where $t is one of "t" "y" "n", or "" (for -)
941 # either $s must be undef, or $h eq $r->hash($s)
943 #print STDERR "_identify\n";
944 return '' unless defined $h && length $h;
945 #print STDERR "_identify h=$h s=".(defined $s ? $s : '<undef>')."\n";
949 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
950 " WHERE last < ?", {},
951 time - $r->{S}{login_timeout});
953 my $row = $dbh->selectrow_arrayref("SELECT username, last".
954 " FROM $r->{S}{assocdb_table}".
955 " WHERE assochash = ?", {}, $h);
957 #print STDERR "_identify h=$h s=$s YES @$row\n";
958 my ($nusername, $nlast) = @$row;
959 return ('y', $nusername);
962 # Well, it's not in the database. But maybe it's a hash of a
965 return 'n' unless defined $s;
967 my ($keyt, $signature, $message, $noncet, $nonce) =
968 $s =~ m/^(\d+)\.(\w+)\.((\d+)\.(\w+))$/ or die;
970 return 'n' if time > $noncet + $r->{S}{login_form_timeout};
972 #print STDERR "_identify noncet=$noncet ok\n";
974 my $keys = $r->_open_keys();
975 while (my ($rkeyt, $rkey, $line) = $r->_read_key($keys)) {
976 #print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey\n";
977 last if $rkeyt < $keyt; # too far down in the file
978 my $trysignature = $r->_hmac($rkey, $message);
979 #print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey try=$trysignature\n";
980 return 't' if $trysignature eq $signature;
983 #print STDERR "_identify NO\n";
985 $keys->error and die $!;
989 sub _db_revoke ($$) {
990 # revokes $h if it's valid; no-op if it's not
995 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
996 " WHERE assochash = ?", {}, $h);
999 sub _db_record_login_ok ($$$) {
1000 my ($r,$h,$user) = @_;
1002 my $dbh = $r->{Dbh};
1003 $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
1004 " (assochash, username, last) VALUES (?,?,?)", {},
1008 sub check_divert ($) {
1010 if (exists $r->{Divert}) {
1011 return $r->{Divert};
1013 my $dbh = $r->{Dbh};
1014 $r->{Divert} = $r->_db_transaction(sub { $r->_check_divert_core(); });
1016 $r->_debug(Data::Dumper->Dump([$r->{Divert}],[qw(divert)]));
1017 return $r->{Divert};
1020 sub get_divert ($) {
1022 die "unchecked" unless exists $r->{Divert};
1023 return $r->{Divert};
1026 sub get_username ($) {
1028 my $divert = $r->get_divert();
1029 return undef if $divert;
1030 return $r->{UserOK};
1033 sub url_with_query_params ($$) {
1034 my ($r, $params) = @_;
1035 #print STDERR "PARAMS ",Dumper($params);
1036 my $uri = URI->new($r->_ch('get_url'));
1037 $uri->path($uri->path() . $params->{''}[0]) if $params->{''};
1038 $uri->query_form(flatten_params($params));
1039 return $uri->as_string();
1042 sub _cgi_header_args ($$@) {
1043 my ($r, $cookie, @ha) = @_;
1044 unshift @ha, qw(-type text/html);
1045 push @ha, (-cookie => $cookie) if defined $cookie;
1046 #print STDERR "_cgi_header_args ",join('|',@ha),".\n";
1053 my ($divert) = $r->check_divert();
1054 return 1 if !$divert;
1056 my $handled = $r->_ch('handle_divert',$divert);
1057 return 0 if $handled;
1059 my $kind = $divert->{Kind};
1060 my $cookiesecret = $divert->{CookieSecret};
1061 my $params = $divert->{Params};
1062 my $cookie = $r->construct_cookie($cookiesecret);
1064 if ($kind =~ m/^SRCDUMP-(\w+)$/) {
1065 $r->_ch('srcdump_dump', (lc $1));
1069 if ($kind =~ m/^REDIRECT-/) {
1070 # for redirects, we honour stored NextParams and SetCookie,
1071 # as we would for non-divert
1072 if ($kind eq 'REDIRECT-LOGGEDOUT') {
1073 $params->{$r->{S}{loggedout_param_names}[0]} = [ 1 ];
1074 } elsif ($kind eq 'REDIRECT-LOGOUT') {
1075 $params->{$r->{S}{logout_param_names}[0]} = [ 1 ];
1076 } elsif ($kind =~ m/REDIRECT-(?:LOGGEDIN|HTTPS)/) {
1080 my $new_url = $r->url_with_query_params($params);
1081 if ($kind eq 'REDIRECT-HTTPS') {
1082 my $uri = URI->new($new_url);
1083 die unless $uri->scheme eq 'http';
1084 $uri->scheme('https');
1085 $new_url = $uri->as_string();
1087 $r->_ch('do_redirect',$new_url, $cookie);
1091 if (defined $cookiesecret) {
1092 $params->{$r->{S}{assoc_param_name}} = [ $r->hash($cookiesecret) ];
1096 if ($kind =~ m/^LOGIN-/) {
1097 $title = $r->_gt('Login');
1098 push @body, $divert->{Message};
1099 push @body, $r->_ch('gen_login_form', $params);
1100 } elsif ($kind =~ m/^SMALLPAGE-/) {
1101 $title = $r->_gt('Not logged in');
1102 push @body, $divert->{Message};
1103 push @body, $r->_ch('gen_login_link', $params);
1104 } elsif ($kind =~ m/^MAINPAGEONLY$/) {
1105 $title = $r->_gt('Entering secure site.');
1106 push @body, $divert->{Message};
1107 push @body, $r->_ch('gen_postmainpage_form', $params);
1112 $r->_print($r->{Cgi}->header($r->_cgi_header_args($cookie)),
1113 $r->_ch('gen_start_html',$title),
1115 $r->_ch('gen_footer_html'),
1116 $r->_ch('gen_end_html'))));
1121 my ($r, $bytes) = @_;
1123 my $rsf = $v->{RandomHandle};
1124 my $rsp = $r->{S}{random_source};
1126 $v->{RandomHandle} = $rsf = new IO::File $rsp, '<' or die "$rsp $!";
1127 #print STDERR "RH $rsf\n";
1131 read($rsf,$bin,$bytes) == $bytes or die "$rsp $!";
1132 my $out = unpack "H*", $bin;
1133 #print STDERR "_random out $out\n";
1137 sub _random_key ($) {
1139 #print STDERR "_random_key\n";
1140 my $bytes = ($r->{S}{secretbits} + 7) >> 3;
1141 return $r->_random($bytes);
1144 sub _read_key ($$) {
1145 my ($r, $keys) = @_;
1146 # returns $gen_time_t, $key_value_in_hex, $complete_line
1148 my ($gen, $k) = m/^(\d+) (\S+)$/ or die "$_ ?";
1149 my $age = time - $gen;
1150 next if $age > $r->{S}{key_rollover} &&
1151 $age > $r->{S}{login_form_timeout}*2;
1152 return ($gen, $k, $_);
1157 sub _open_keys ($) {
1159 my $spath = $r->_get_path('keys');
1161 #print STDERR "_open_keys\n";
1162 my $keys = new IO::File $spath, 'r+';
1164 #print STDERR "_open_keys open\n";
1165 stat $keys or die $!; # NB must not disturb stat _
1166 my $size = (stat _)[7];
1167 my $age = time - (stat _)[9];
1168 #print STDERR "_open_keys open size=$size age=$age\n";
1170 if $size && $age <= $r->{S}{key_rollover} / 2;
1171 #print STDERR "_open_keys open bad\n";
1173 # file doesn't exist, or is empty or too old
1175 #print STDERR "_open_keys closed\n";
1176 die "$spath $!" unless $!==&ENOENT;
1177 # doesn't exist, so create it just so we can lock it
1178 $keys = new IO::File $spath, 'a+';
1179 die "$keys $!" unless $keys;
1180 stat $keys or die $!; # NB must not disturb stat _
1181 my $size = (stat _)[7];
1182 #print STDERR "_open_keys created size=$size\n";
1183 next if $size; # oh someone else has done it, reopen and read it
1185 # file now exists is empty or too old, we must try to replace it
1186 my $our_inum = (stat _)[1]; # last use of that stat _
1187 flock $keys, LOCK_EX or die "$spath $!";
1188 stat $spath or die "$spath $!";
1189 my $path_inum = (stat _)[1];
1190 #print STDERR "_open_keys locked our=$our_inum path=$path_inum\n";
1191 next if $our_inum != $path_inum; # someone else has done it
1192 # We now hold the lock!
1193 #print STDERR "_open_keys creating\n";
1194 my $newkeys = new IO::Handle;
1195 sysopen $newkeys, "$spath.new", O_CREAT|O_TRUNC|O_WRONLY, 0600
1196 or die "$spath.new $!";
1197 # we add the new key to the front which means it's always sorted
1198 print $newkeys time, ' ', $r->_random_key(), "\n" or die $!;
1199 while (my ($gen,$key,$line) = $r->_read_key($keys)) {
1200 #print STDERR "_open_keys copy1\n";
1201 print $newkeys, $line or die $!;
1203 $keys->error and die $!;
1204 close $newkeys or die "$spath.new $!";
1205 rename "$spath.new", "$spath" or die "$spath: $!";
1206 #print STDERR "_open_keys installed\n";
1207 # that rename effective unlocks, since it makes the name refer
1208 # to the new file which we haven't locked
1209 # we go round again opening the file at the beginning
1210 # so that our caller gets a fresh handle onto the existing key file
1214 sub _fresh_secret ($) {
1216 #print STDERR "_fresh_secret\n";
1218 my $keys = $r->_open_keys();
1219 my ($keyt, $key) = $r->_read_key($keys);
1220 die unless defined $keyt;
1222 my $nonce = $r->_random_key();
1224 my $message = "$noncet.$nonce";
1226 my $signature = $r->_hmac($key, $message);
1227 my $secret = "$keyt.$signature.$message";
1228 #print STDERR "FRESH $secret\n";
1233 my ($r, $keyhex, $message) = @_;
1234 my $keybin = pack "H*", $keyhex;
1235 my $alg = $r->{S}{hash_algorithm};
1236 #print STDERR "hmac $alg\n";
1237 my $base = new Digest $alg;
1238 #print STDERR "hmac $alg $base\n";
1239 my $digest = new Digest::HMAC $keybin, $base;
1240 #print STDERR "hmac $alg $base $digest\n";
1241 $digest->add($message);
1242 return $digest->hexdigest();
1246 my ($r, $message) = @_;
1247 my $alg = $r->{S}{hash_algorithm};
1248 #print STDERR "hash $alg\n";
1249 my $digest = new Digest $alg;
1250 $digest->add($message);
1251 return $digest->hexdigest();
1254 sub _assert_checked ($) {
1256 die "unchecked" unless exists $r->{Divert};
1261 my $meth = $r->_ch('get_method');
1262 return $meth eq 'POST';
1265 sub _must_be_post ($) {
1267 my $meth = $r->_ch('get_method');
1268 die "mutating non-POST" if $meth ne 'POST';
1271 sub check_mutate ($) {
1273 $r->_assert_checked();
1274 die if $r->{Divert};
1275 $r->_must_be_post();
1280 $r->_assert_checked();
1281 die if $r->{Divert};
1282 return $r->_is_post();
1285 #---------- output ----------
1287 sub secret_cookie_val ($) {
1289 $r->_assert_checked();
1290 return defined $r->{AssocSecret} ? $r->{AssocSecret} : '';
1293 sub secret_hidden_val ($) {
1295 $r->_assert_checked();
1296 return defined $r->{AssocSecret} ? $r->hash($r->{AssocSecret}) : '';
1299 sub secret_hidden_html ($) {
1301 return $r->{Cgi}->hidden(-name => $r->{S}{assoc_param_name},
1302 -default => $r->secret_hidden_val());
1305 sub secret_cookie ($) {
1307 my $secret = $r->secret_cookie_val();
1308 return undef if !defined $secret;
1309 #print STDERR "SC\n";
1310 my $cookv = $r->construct_cookie($secret);
1311 #print STDERR "SC=$cookv\n";
1321 CGI::Auth::Flexible - web authentication optionally using cookies
1325 my $verifier = CGI::Auth::Flexible->new_verifier(setting => value,...);
1326 my $authreq = $verifier->new_request($cgi_request_object);
1328 my $authreq = CGI::Auth::Flexible->new_request($cgi_request_object,
1329 setting => value,...);
1331 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
1333 $authreq->check_ok() or return;
1336 $authreq->check_mutate();
1339 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
1341 my $divert_kind = $authreq->check_divert();
1343 if ($divert_kind eq 'LOGGEDOUT') {
1344 print "goodbye you are now logged out" and quit
1345 } elsif ($divert_kind eq 'NOCOOKIES') {
1346 print "you need cookies" and quit
1352 $authreq->check_mutate();