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/;
53 #---------- public utilities ----------
55 sub flatten_params ($) {
58 foreach my $k (keys %$p) {
60 foreach my $v (@{ $p->{$k} }) {
67 #---------- default callbacks ----------
69 sub has_a_param ($$) {
71 foreach my $pn (@{ $r->{S}{$cn} }) {
72 return 1 if $r->_ch('get_param',$pn);
81 foreach my $name ($c->param()) {
82 $p{$name} = [ $c->param($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 ]);
181 return '<a href="'.escapeHTML($r->url_with_query_params(\%params)).'">'.
184 sub gen_plain_licence_link_html ($$) {
186 gen_srcdump_link_html($c,$r, 'GNU Affero GPL', 'licence');
188 sub gen_plain_source_link_html ($$) {
190 gen_srcdump_link_html($c,$r, 'Source available', 'source');
193 sub gen_plain_footer_html ($$) {
195 return ('<hr><address>',
196 ("Powered by Free / Libre / Open Source Software".
197 " according to the ".$r->_ch('gen_licence_link_html')."."),
198 $r->_ch('gen_source_link_html').".",
202 #---------- licence and source code ----------
204 sub srcdump_dump ($$$) {
205 my ($c,$r, $thing) = @_;
206 die if $thing =~ m/\W/ || $thing !~ m/\w/;
207 my $path = $r->_get_path('srcdump');
208 my $ctf = new IO::File "$path/$thing.ctype", 'r'
209 or die "$path/$thing.ctype $!";
211 chomp $ct or die "$path/$thing ?";
212 $ctf->close or die "$path/$thing $!";
213 my $df = new IO::File "$path/$thing.data", 'r'
214 or die "$path/$thing.data $!";
215 $r->_ch('dump', $ct, $df);
218 sub dump_plain ($$$$) {
219 my ($c, $r, $ct, $df) = @_;
220 $r->_print($c->header('-type' => $ct));
223 my $got = read $df, $buffer, 65536;
224 die $! unless defined $got;
230 sub srcdump_process_item ($$$$$$) {
231 my ($c, $v, $dumpdir, $item, $outfn, $needlicence, $dirsdone) = @_;
232 if ($v->_ch('srcdump_system_dir', $item)) {
233 $outfn->("srcdump_process_item: srcdump_system_dir, skipping $item");
239 last unless $upwards =~ m#[^/]#;
240 foreach my $try (@{ $v->{S}{srcdump_vcs_dirs} }) {
241 #print STDERR "TRY $item $upwards $try\n";
242 if (!stat "$upwards/$try") {
243 $!==&ENOENT or $!==&ENOTDIR or die "check $upwards/$try $!";
246 #print STDERR "VCS $item $upwards $try\n";
247 return if $dirsdone->{$upwards}++;
248 #print STDERR "VCS $item $upwards $try GO\n";
249 $try =~ m/\w+/ or die;
250 return $v->_ch(('srcdump_byvcs_'.lc $&),
251 $dumpdir, $upwards, $outfn);
253 $upwards =~ s#/*[^/]+##;
255 return $v->_ch('srcdump_novcs', $dumpdir, $item, $outfn);
258 sub srcdump_novcs ($$$$$) {
259 my ($c, $v, $dumpdir, $item, $outfn) = @_;
260 stat $item or die "$item $!";
262 my $script = 'find -type f -perm +004';
263 foreach my $excl (@{ $v->{S}{srcdump_excludes} }) {
264 $script .= " \\! -name '$excl'";
266 $script .= " -print0";
267 return srcdump_dir_cpio($c,$v,$dumpdir,$item,$outfn,$script);
269 return srcdump_file($c,$v,$dumpdir,$item,$outfn);
271 die "$item not file or directory";
275 sub srcdump_byvcs_git ($$$$$) {
276 my ($c, $v, $dumpdir, $dir, $outfn) = @_;
277 #print STDERR "BYVCS GIT $dir\n";
278 return srcdump_dir_cpio($c,$v,$dumpdir,$dir,$outfn,"
280 git ls-files -z --others --exclude-from=.gitignore
285 sub srcdump_file ($$$$) {
286 my ($c,$v,$dumpdir,$file,$outfn) = @_;
287 my $outfile = $outfn->("srcdump_file saved $file", "src");
288 copy($file,$outfile) or die "$file $outfile $!";
291 sub srcdump_dir_cpio ($$$$$) {
292 my ($c,$v,$dumpdir,$dir,$outfn,$script) = @_;
293 my $outfile = $outfn->("srcdump_dir_cpio saved $dir", "tar");
294 #print STDERR "CPIO $dir >$script<\n";
296 defined $pid or die $!;
298 $SIG{__DIE__} = sub {
299 print STDERR "CGI::Auth::Flexible srcdump error: $@\n";
302 open STDOUT, ">", $outfile or die "$outfile $!";
303 chdir $dir or die "chdir $dir: $!";
304 exec '/bin/bash','-ec',"
309 cpio -Hustar -o --quiet -0 -R 1000:1000 || \
310 cpio -Hustar -o --quiet -0
315 $!=0; (waitpid $pid, 0) == $pid or die "$!";
316 die "$dir ($script) $outfile $?" if $?;
319 sub srcdump_dirscan_prepare ($$) {
321 my $dumpdir = $v->_get_path('srcdump');
322 mkdir $dumpdir or $!==&EEXIST or die "mkdir $dumpdir $!";
323 my $lockf = new IO::File "$dumpdir/generate.lock", 'w+'
324 or die "$dumpdir/generate.lock $!";
325 flock $lockf, LOCK_EX or die "$dumpdir/generate.lock $!";
326 my $needlicence = "$dumpdir/licence.tmp";
327 unlink $needlicence or $!==&ENOENT or die "rm $needlicence $!";
328 if (defined $v->{S}{srcdump_licence_path}) {
329 copy($v->{S}{srcdump_licence_path}, $needlicence)
330 or die "$v->{S}{srcdump_licence_path} $!";
331 $needlicence = undef;
333 unlink <"$dumpdir/s.[a-z][a-z][a-z].*">;
334 my @srcfiles = qw(licence.data manifest.txt);
335 my $srcoutcounter = 'aaa';
337 my $reportfh = new IO::File "$dumpdir/manifest.txt", 'w' or die $!;
339 my ($message, $extension) = @_;
340 if (defined $extension) {
341 my $leaf = "s.$srcoutcounter.$extension";
343 push @srcfiles, $leaf;
344 print $reportfh "$leaf: $message\n" or die $!;
345 return "$dumpdir/$leaf";
347 print $reportfh "none: $message\n" or die $!;
352 foreach my $item ($v->_ch('srcdump_listitems')) {
353 if ($item eq '.' && $v->{S}{srcdump_filter_cwd}) {
354 my @bad = grep { !m#^/# } values %INC;
355 die "filtering . from srcdump items and \@INC but already".
356 " included @bad " if @bad;
357 @INC = grep { $_ ne '.' } @INC;
360 if (!lstat "$item") {
361 die "stat $item $!" unless $!==&ENOENT;
362 $outfn->("srcdump_dirscan_prepare stat ENOENT: skipping $item");
366 $item = realpath($item);
367 if (!defined $item) {
368 die "realpath $item $!" unless $!==&ENOENT;
369 $outfn->("srcdump_dirscan_prepare realpath ENOENT:".
373 if (defined $needlicence) {
374 foreach my $try (@{ $v->{S}{srcdump_licence_files} }) {
375 last if copy("$item/$try", $needlicence);
376 $!==&ENOENT or $!==&ENOTDIR or die "copy $item/$try $!";
379 $v->_ch('srcdump_process_item', $dumpdir, $item,
380 $outfn, \$needlicence, \%dirsdone);
383 close $reportfh or die $!;
385 my @cmd = (qw(tar -zvvcf), "$dumpdir/source.tmp",
386 "-C", $dumpdir, qw( --), @srcfiles);
387 my $r = system(@cmd);
389 print STDERR "CGI::Auth::Flexible tar failed ($r $!) @cmd\n";
392 die "licence file not found" unless defined $needlicence;
393 srcdump_install($c,$v, $dumpdir, 'licence', 'text/plain');
394 srcdump_install($c,$v, $dumpdir, 'source', 'application/octet-stream');
395 close $lockf or die $!;
398 sub srcdump_install ($$$$$) {
399 my ($c,$v, $dumpdir, $which, $ctype) = @_;
400 rename "$dumpdir/$which.tmp", "$dumpdir/$which.data"
401 or die "$dumpdir/$which.data $!";
402 my $ctf = new IO::File "$dumpdir/$which.tmp", 'w'
403 or die "$dumpdir/$which.tmp $!";
404 print $ctf $ctype, "\n" or die $!;
405 close $ctf or die $!;
406 rename "$dumpdir/$which.tmp", "$dumpdir/$which.ctype"
407 or die "$dumpdir/$which.ctype $!";
410 #---------- verifier object methods ----------
417 assocdb_dbh => undef, # must have AutoCommit=0, RaiseError=1
418 assocdb_path => 'caf-assocs.db',
419 keys_path => 'caf-keys',
420 srcdump_path => 'caf-srcdump',
421 assocdb_dsn => undef,
423 assocdb_password => '',
424 assocdb_table => 'caf_assocs',
425 random_source => '/dev/urandom',
426 secretbits => 128, # bits
427 hash_algorithm => "SHA-256",
428 login_timeout => 86400, # seconds
429 login_form_timeout => 3600, # seconds
430 key_rollover => 86400, # seconds
431 assoc_param_name => 'caf_assochash',
432 dummy_param_name_prefix => 'caf__',
433 cookie_name => "caf_assocsecret",
434 password_param_name => 'password',
435 srcdump_param_name => 'caf_srcdump',
436 username_param_names => [qw(username)],
437 form_entry_size => 60,
438 logout_param_names => [qw(caf_logout)],
439 loggedout_param_names => [qw(caf_loggedout)],
440 promise_check_mutate => 0,
441 get_param => sub { $_[0]->param($_[2]) },
442 get_params => sub { $_[1]->get_params() },
443 get_path_info => sub { $_[0]->path_info() },
444 get_cookie => sub { $_[0]->cookie($_[1]->{S}{cookie_name}) },
445 get_method => sub { $_[0]->request_method() },
446 check_https => sub { !!$_[0]->https() },
447 get_url => sub { $_[0]->url(); },
448 is_login => sub { defined $_[1]->_rp('password_param_name') },
449 login_ok => \&login_ok_password,
450 username_password_error => sub { die },
451 is_logout => sub { $_[1]->has_a_param('logout_param_names') },
452 is_loggedout => sub { $_[1]->has_a_param('loggedout_param_names') },
453 is_page => sub { return 1 },
454 handle_divert => sub { return 0 },
455 do_redirect => \&do_redirect_cgi, # this hook is allowed to throw
457 get_cookie_domain => \&get_cookie_domain,
459 gen_start_html => sub { $_[0]->start_html($_[2]); },
460 gen_footer_html => \&gen_plain_footer_html,
461 gen_licence_link_html => \&gen_plain_licence_link_html,
462 gen_source_link_html => \&gen_plain_source_link_html,
463 gen_end_html => sub { $_[0]->end_html(); },
464 gen_login_form => \&gen_plain_login_form,
465 gen_login_link => \&gen_plain_login_link,
466 gen_postmainpage_form => \&gen_postmainpage_form,
467 srcdump_dump => \&srcdump_dump,
468 srcdump_prepare => \&srcdump_dirscan_prepare,
469 srcdump_licence_path => undef,
470 srcdump_licence_files => [qw(AGPLv3 CGI/Auth/Flexible/AGPLv3)],
471 srcdump_listitems => sub { (@INC, $ENV{'SCRIPT_FILENAME'}, $0); },
472 srcdump_filter_cwd => 1,
473 srcdump_system_dir => sub {
474 $_[2] =~ m#^/etc/|^/usr/(?!local/)(?!lib/cgi)#;
476 srcdump_process_item => \&srcdump_process_item,
477 srcdump_vcs_dirs => [qw(.git .hg .svn CVS)],
478 srcdump_byvcs_git => \&srcdump_byvcs_git,
479 srcdump_byvcs_hg => \&srcdump_byvcs_hg,
480 srcdump_byvcs_svn => \&srcdump_byvcs_svn,
481 srcdump_byvcs_cvs => \&srcdump_byvcs_cvs,
482 srcdump_novcs => \&srcdump_novcs,
483 srcdump_excludes => [qw(*~ *.bak *.tmp), '#*#'],
484 dump => \&dump_plain,
485 gettext => sub { gettext($_[2]); },
486 print => sub { print $_[2] or die $!; },
487 debug => sub { }, # like print; msgs contain trailing \n
492 while (($k,$v,@_) = @_) {
493 die "unknown setting $k" unless exists $verifier->{S}{$k};
494 $verifier->{S}{$k} = $v;
496 bless $verifier, $class;
497 $verifier->_dbopen();
498 $verifier->_ch('srcdump_prepare');
502 sub _db_setup_do ($$) {
506 $v->_db_transaction(sub {
507 local ($dbh->{PrintError}) = 0;
518 $dbh = $v->{S}{assocdb_dbh};
520 die if $dbh->{AutoCommit};
521 die unless $dbh->{RaiseError};
523 $v->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=".$v->_get_path('assocdb');
524 my $dsn = $v->{S}{assocdb_dsn};
527 $dbh = DBI->connect($dsn, $v->{S}{assocdb_user},
528 $v->{S}{assocdb_password}, {
531 ShowErrorStatement => 1,
534 die "$dsn $! ?" unless $dbh;
538 $v->_db_setup_do("CREATE TABLE $v->{S}{assocdb_table} (".
539 " assochash VARCHAR PRIMARY KEY,".
540 " username VARCHAR NOT NULL,".
541 " last INTEGER NOT NULL".
543 $v->_db_setup_do("CREATE INDEX $v->{S}{assocdb_table}_timeout_index".
544 " ON $v->{S}{assocdb_table}".
556 sub _db_transaction ($$) {
561 #print STDERR "DT entry\n";
563 #print STDERR "DT loop\n";
566 #print STDERR "DT fn ok\n";
569 #print STDERR "DT fn error\n";
570 { local ($@); $dbh->rollback(); }
571 #print STDERR "DT fn throwing\n";
574 #print STDERR "DT fn eval ok\n";
577 #print STDERR "DT commit ok\n";
580 #print STDERR "DT commit eval ok ",Dumper($rv);
583 #print STDERR "DT commit throw?\n";
584 die $@ if !--$retries;
585 #print STDERR "DT loop again\n";
589 #---------- request object methods ----------
592 my ($classbase, $cgi, @extra) = @_;
593 if (!ref $classbase) {
594 $classbase = $classbase->new_verifier(@extra);
600 S => $classbase->{S},
601 Dbh => $classbase->{Dbh},
604 bless $r, ref $classbase;
607 sub _ch ($$@) { # calls an application hook
608 my ($r,$methname, @args) = @_;
609 my $methfunc = $r->{S}{$methname};
610 die "$methname ?" unless $methfunc;
611 return $methfunc->($r->{Cgi}, $r, @args);
616 my $pn = $r->{S}{$pnvb};
617 my $p = scalar $r->_ch('get_param',$pn)
622 $r->_ch('debug',@args);
626 my ($r,$keybase) = @_;
627 my $leaf = $r->{S}{"${keybase}_path"};
628 return $r->_absify_path($leaf);
631 sub _absify_path ($$) {
633 return $leaf if $leaf =~ m,^/,;
634 my $dir = $v->{S}{dir};
635 die "relying on cwd by default ?! set dir" unless defined $dir;
639 sub _gt ($$) { my ($r, $t) = @_; return $r->_ch('gettext',$t); }
640 sub _print ($$) { my ($r, @t) = @_; return $r->_ch('print', join '', @t); }
642 sub construct_cookie ($$$) {
643 my ($r, $cooks) = @_;
644 return undef unless $cooks;
646 my @ca = (-name => $r->{S}{cookie_name},
648 -path => $r->{S}{cookie_path},
649 -domain => $r->_ch('get_cookie_domain'),
650 -expires => '+'.$r->{S}{login_timeout}.'s',
651 -secure => $r->{S}{encrypted_only});
652 my $cookie = $c->cookie(@ca);
653 #print STDERR "CC $r $c $cooks $cookie (@ca).\n";
657 # pages/param-sets are
658 # n normal non-mutating page
659 # r retrieval of information for JS, non-mutating
661 # u update of information by JS, mutating
664 # O "you have just logged out" page load
667 # - no value supplied (represented in code as $cookt='')
668 # n, nN value not in our db
669 # t, tN temporary value (in our db, no logged in user yet)
670 # y, yN value corresponds to logged-in user
671 # and, aggregated conditions:
672 # a, aN anything including -
674 # if N differs the case applies only when the two values differ
675 # (eg, a1 y2 does not apply when the logged-in value is supplied twice)
677 # "stale session" means request originates from a page from a login
678 # session which has been revoked (eg by logout); "cleared session"
679 # means request originates from a browser which has a different (or
682 # Case analysis, cookie mode, app promises re mutate:
683 # cook parm meth form
685 # any - POST nrmuoi bug or attack, fail
686 # any - GET rmuoi bug or attack, fail
687 # any any GET muoi bug or attack, fail
688 # any t any nrmu bug or attack, fail
690 # - - GET O "just logged out" page
691 # (any other) O bug or attack, fail
693 # a1 a2 POST o logout
694 # if a1 is valid, revoke it
695 # if a2 is valid, revoke it
697 # redirect to "just logged out" page
698 # (which contains link to login form)
700 # - t POST i complain about cookies being disabled
701 # (with link to login form)
703 # t1 t1 POST i login (or switch user)
705 # show new login form
707 # upgrade t1 to y1 in our db (setting username)
708 # redirect to GET of remaining params
710 # y1 a2 POST i complain about stale login form
712 # show new login form
714 # (other) POST i complain about stale login form
715 # show new login form
717 # t1 a2 ANY nrmu treat as - a2 ANY
719 # y - GET n cross-site link
722 # y y GET nr fine, show page or send data
723 # y y POST nrmu mutation is OK, do operation
725 # y1 y2 GET nr request from stale page
726 # do not revoke y2 as not RESTful
729 # y1 y2 POST nrmu request from stale page
733 # y n GET n intra-site link from stale page,
734 # treat as cross-site link, show data
736 # y n POST n m intra-site form submission from stale page
737 # show "session interrupted"
738 # with link to main data page
740 # y n GET r intra-site request from stale page
743 # y n POST r u intra-site request from stale page
746 # -/n y2 GET nr intra-site link from cleared session
747 # do not revoke y2 as not RESTful
750 # -/n y2 POST nrmu request from cleared session
752 # treat as -/n n POST
754 # -/n -/n GET n cross-site link but user not logged in
755 # show login form with redirect to orig params
756 # generate fresh cookie
758 # -/n n GET rmu user not logged in
761 # -/n n POST n m user not logged in
764 # -/n n POST r u user not logged in
767 sub _check_divert_core ($) {
770 my $srcdump = $r->_rp('srcdump_param_name');
772 die if $srcdump =~ m/\W/;
773 return ({ Kind => 'SRCDUMP-'.uc $srcdump,
775 CookieSecret => undef,
779 my $cooks = $r->_ch('get_cookie');
781 if ($r->{S}{encrypted_only} && !$r->_ch('check_https')) {
782 return ({ Kind => 'REDIRECT-HTTPS',
783 Message => $r->_gt("Redirecting to secure server..."),
784 CookieSecret => undef,
788 my $meth = $r->_ch('get_method');
789 my $parmh = $r->_rp('assoc_param_name');
790 my $cookh = defined $cooks ? $r->hash($cooks) : undef;
792 my ($cookt,$cooku) = $r->_identify($cookh, $cooks);
793 my $parms = (defined $cooks && defined $parmh && $parmh eq $cookh)
795 my ($parmt) = $r->_identify($parmh, $parms);
797 $r->_debug("_c_d_c cookt=$cookt parmt=$parmt\n");
799 if ($r->_ch('is_logout')) {
802 $r->_db_revoke($cookh);
803 $r->_db_revoke($parmh);
804 return ({ Kind => 'REDIRECT-LOGGEDOUT',
805 Message => $r->_gt("Logging out..."),
809 if ($r->_ch('is_loggedout')) {
810 die unless $meth eq 'GET';
811 die if $cookt eq 'y';
813 return ({ Kind => 'SMALLPAGE-LOGGEDOUT',
814 Message => $r->_gt("You have been logged out."),
818 if ($r->_ch('is_login')) {
821 if (!$cookt && $parmt eq 'n') {
822 return ({ Kind => 'SMALLPAGE-NOCOOKIE',
823 Message => $r->_gt("You do not seem to have cookies".
824 " enabled. You must enable cookies".
825 " as we use them for login."),
826 CookieSecret => $r->_fresh_secret(),
827 Params => $r->chain_params() })
829 if (!$cookt || $cookt eq 'n' || $cookh ne $parmh) {
830 $r->_db_revoke($cookh);
831 return ({ Kind => 'LOGIN-STALE',
832 Message => $r->_gt("Stale session;".
833 " you need to log in again."),
834 CookieSecret => $r->_fresh_secret(),
837 die unless $parmt eq 't' || $parmt eq 'y';
838 my ($username, $login_errormessage) = $r->_ch('login_ok');
839 unless (defined $username && length $username) {
840 $login_errormessage = $r->_gt("Incorrect username/password.")
841 if !$login_errormessage;
842 return ({ Kind => 'LOGIN-BAD',
843 Message => $login_errormessage,
844 CookieSecret => $cooks,
845 Params => $r->chain_params() })
847 $r->_db_record_login_ok($parmh,$username);
848 return ({ Kind => 'REDIRECT-LOGGEDIN',
849 Message => $r->_gt("Logging in..."),
850 CookieSecret => $cooks,
851 Params => $r->chain_params() });
856 die if $parmt eq 't';
858 if ($cookt eq 'y' && $parmt eq 'y' && $cookh ne $parmh) {
859 $r->_db_revoke($parmh) if $meth eq 'POST';
864 die unless !$cookt || $cookt eq 'n';
865 die unless !$parmt || $parmt eq 'n' || $parmt eq 'y';
866 my $news = $r->_fresh_secret();
867 if ($meth eq 'GET') {
868 return ({ Kind => 'LOGIN-INCOMINGLINK',
869 Message => $r->_gt("You need to log in."),
870 CookieSecret => $news,
871 Params => $r->chain_params() });
873 $r->_db_revoke($parmh);
874 return ({ Kind => 'LOGIN-FRESH',
875 Message => $r->_gt("You need to log in."),
876 CookieSecret => $news,
881 if (!$r->{S}{promise_check_mutate}) {
882 if ($meth ne 'POST') {
883 return ({ Kind => 'MAINPAGEONLY',
884 Message => $r->_gt('Entering via cross-site link.'),
885 CookieSecret => $cooks,
887 # NB caller must then ignore params & path!
888 # if this is too hard they can spit out a small form
889 # with a "click to continue"
893 die unless $cookt eq 'y';
894 unless ($r->{S}{promise_check_mutate} && $meth eq 'GET') {
895 die unless $parmt eq 'y';
896 die unless $cookh eq $parmh;
898 $r->{AssocSecret} = $cooks;
899 $r->{UserOK} = $cooku;
900 #print STDERR "C-D-C OK\n";
904 sub chain_params ($) {
906 my %p = %{ $r->_ch('get_params') };
907 foreach my $pncn (keys %{ $r->{S} }) {
909 if ($pncn =~ m/_param_name$/) {
910 my $name = $r->{S}{$pncn};
911 die "$pncn ?" if ref $name;
913 } elsif ($pncn =~ m/_param_names$/) {
914 $names = $r->{S}{$pncn};
918 foreach my $name (@$names) {
922 my $dummy_prefix = $r->{S}{dummy_param_name_prefix};
923 foreach my $name (grep /^$dummy_prefix/, keys %p) {
926 die if exists $p{''};
927 $p{''} = [ $r->_ch('get_path_info') ];
933 # returns ($t,$username)
934 # where $t is one of "t" "y" "n", or "" (for -)
935 # either $s must be undef, or $h eq $r->hash($s)
937 #print STDERR "_identify\n";
938 return '' unless defined $h && length $h;
939 #print STDERR "_identify h=$h s=".(defined $s ? $s : '<undef>')."\n";
943 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
944 " WHERE last < ?", {},
945 time - $r->{S}{login_timeout});
947 my $row = $dbh->selectrow_arrayref("SELECT username, last".
948 " FROM $r->{S}{assocdb_table}".
949 " WHERE assochash = ?", {}, $h);
951 #print STDERR "_identify h=$h s=$s YES @$row\n";
952 my ($nusername, $nlast) = @$row;
953 return ('y', $nusername);
956 # Well, it's not in the database. But maybe it's a hash of a
959 return 'n' unless defined $s;
961 my ($keyt, $signature, $message, $noncet, $nonce) =
962 $s =~ m/^(\d+)\.(\w+)\.((\d+)\.(\w+))$/ or die;
964 return 'n' if time > $noncet + $r->{S}{login_form_timeout};
966 #print STDERR "_identify noncet=$noncet ok\n";
968 my $keys = $r->_open_keys();
969 while (my ($rkeyt, $rkey, $line) = $r->_read_key($keys)) {
970 #print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey\n";
971 last if $rkeyt < $keyt; # too far down in the file
972 my $trysignature = $r->_hmac($rkey, $message);
973 #print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey try=$trysignature\n";
974 return 't' if $trysignature eq $signature;
977 #print STDERR "_identify NO\n";
979 $keys->error and die $!;
983 sub _db_revoke ($$) {
984 # revokes $h if it's valid; no-op if it's not
989 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
990 " WHERE assochash = ?", {}, $h);
993 sub _db_record_login_ok ($$$) {
994 my ($r,$h,$user) = @_;
997 $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
998 " (assochash, username, last) VALUES (?,?,?)", {},
1002 sub check_divert ($) {
1004 if (exists $r->{Divert}) {
1005 return $r->{Divert};
1007 my $dbh = $r->{Dbh};
1008 $r->{Divert} = $r->_db_transaction(sub { $r->_check_divert_core(); });
1010 $r->_debug(Data::Dumper->Dump([$r->{Divert}],[qw(divert)]));
1011 return $r->{Divert};
1014 sub get_divert ($) {
1016 die "unchecked" unless exists $r->{Divert};
1017 return $r->{Divert};
1020 sub get_username ($) {
1022 my $divert = $r->get_divert();
1023 return undef if $divert;
1024 return $r->{UserOK};
1027 sub url_with_query_params ($$) {
1028 my ($r, $params) = @_;
1029 #print STDERR "PARAMS ",Dumper($params);
1030 my $uri = URI->new($r->_ch('get_url'));
1031 $uri->path($uri->path() . $params->{''}[0]) if $params->{''};
1032 $uri->query_form(flatten_params($params));
1033 return $uri->as_string();
1036 sub _cgi_header_args ($$@) {
1037 my ($r, $cookie, @ha) = @_;
1038 unshift @ha, qw(-type text/html);
1039 push @ha, (-cookie => $cookie) if defined $cookie;
1040 #print STDERR "_cgi_header_args ",join('|',@ha),".\n";
1047 my ($divert) = $r->check_divert();
1048 return 1 if !$divert;
1050 my $handled = $r->_ch('handle_divert',$divert);
1051 return 0 if $handled;
1053 my $kind = $divert->{Kind};
1054 my $cookiesecret = $divert->{CookieSecret};
1055 my $params = $divert->{Params};
1056 my $cookie = $r->construct_cookie($cookiesecret);
1058 if ($kind =~ m/^SRCDUMP-(\w+)$/) {
1059 $r->_ch('srcdump_dump', (lc $1));
1063 if ($kind =~ m/^REDIRECT-/) {
1064 # for redirects, we honour stored NextParams and SetCookie,
1065 # as we would for non-divert
1066 if ($kind eq 'REDIRECT-LOGGEDOUT') {
1067 $params->{$r->{S}{loggedout_param_names}[0]} = [ 1 ];
1068 } elsif ($kind eq 'REDIRECT-LOGOUT') {
1069 $params->{$r->{S}{logout_param_names}[0]} = [ 1 ];
1070 } elsif ($kind =~ m/REDIRECT-(?:LOGGEDIN|HTTPS)/) {
1074 my $new_url = $r->url_with_query_params($params);
1075 if ($kind eq 'REDIRECT-HTTPS') {
1076 my $uri = URI->new($new_url);
1077 die unless $uri->scheme eq 'http';
1078 $uri->scheme('https');
1079 $new_url = $uri->as_string();
1081 $r->_ch('do_redirect',$new_url, $cookie);
1085 if (defined $cookiesecret) {
1086 $params->{$r->{S}{assoc_param_name}} = [ $r->hash($cookiesecret) ];
1090 if ($kind =~ m/^LOGIN-/) {
1091 $title = $r->_gt('Login');
1092 push @body, $divert->{Message};
1093 push @body, $r->_ch('gen_login_form', $params);
1094 } elsif ($kind =~ m/^SMALLPAGE-/) {
1095 $title = $r->_gt('Not logged in');
1096 push @body, $divert->{Message};
1097 push @body, $r->_ch('gen_login_link', $params);
1098 } elsif ($kind =~ m/^MAINPAGEONLY$/) {
1099 $title = $r->_gt('Entering secure site.');
1100 push @body, $divert->{Message};
1101 push @body, $r->_ch('gen_postmainpage_form', $params);
1106 $r->_print($r->{Cgi}->header($r->_cgi_header_args($cookie)),
1107 $r->_ch('gen_start_html',$title),
1109 $r->_ch('gen_footer_html'),
1110 $r->_ch('gen_end_html'))));
1115 my ($r, $bytes) = @_;
1117 my $rsf = $v->{RandomHandle};
1118 my $rsp = $r->{S}{random_source};
1120 $v->{RandomHandle} = $rsf = new IO::File $rsp, '<' or die "$rsp $!";
1121 #print STDERR "RH $rsf\n";
1125 read($rsf,$bin,$bytes) == $bytes or die "$rsp $!";
1126 my $out = unpack "H*", $bin;
1127 #print STDERR "_random out $out\n";
1131 sub _random_key ($) {
1133 #print STDERR "_random_key\n";
1134 my $bytes = ($r->{S}{secretbits} + 7) >> 3;
1135 return $r->_random($bytes);
1138 sub _read_key ($$) {
1139 my ($r, $keys) = @_;
1140 # returns $gen_time_t, $key_value_in_hex, $complete_line
1142 my ($gen, $k) = m/^(\d+) (\S+)$/ or die "$_ ?";
1143 my $age = time - $gen;
1144 next if $age > $r->{S}{key_rollover} &&
1145 $age > $r->{S}{login_form_timeout}*2;
1146 return ($gen, $k, $_);
1151 sub _open_keys ($) {
1153 my $spath = $r->_get_path('keys');
1155 #print STDERR "_open_keys\n";
1156 my $keys = new IO::File $spath, 'r+';
1158 #print STDERR "_open_keys open\n";
1159 stat $keys or die $!; # NB must not disturb stat _
1160 my $size = (stat _)[7];
1161 my $age = time - (stat _)[9];
1162 #print STDERR "_open_keys open size=$size age=$age\n";
1164 if $size && $age <= $r->{S}{key_rollover} / 2;
1165 #print STDERR "_open_keys open bad\n";
1167 # file doesn't exist, or is empty or too old
1169 #print STDERR "_open_keys closed\n";
1170 die "$spath $!" unless $!==&ENOENT;
1171 # doesn't exist, so create it just so we can lock it
1172 $keys = new IO::File $spath, 'a+';
1173 die "$keys $!" unless $keys;
1174 stat $keys or die $!; # NB must not disturb stat _
1175 my $size = (stat _)[7];
1176 #print STDERR "_open_keys created size=$size\n";
1177 next if $size; # oh someone else has done it, reopen and read it
1179 # file now exists is empty or too old, we must try to replace it
1180 my $our_inum = (stat _)[1]; # last use of that stat _
1181 flock $keys, LOCK_EX or die "$spath $!";
1182 stat $spath or die "$spath $!";
1183 my $path_inum = (stat _)[1];
1184 #print STDERR "_open_keys locked our=$our_inum path=$path_inum\n";
1185 next if $our_inum != $path_inum; # someone else has done it
1186 # We now hold the lock!
1187 #print STDERR "_open_keys creating\n";
1188 my $newkeys = new IO::Handle;
1189 sysopen $newkeys, "$spath.new", O_CREAT|O_TRUNC|O_WRONLY, 0600
1190 or die "$spath.new $!";
1191 # we add the new key to the front which means it's always sorted
1192 print $newkeys time, ' ', $r->_random_key(), "\n" or die $!;
1193 while (my ($gen,$key,$line) = $r->_read_key($keys)) {
1194 #print STDERR "_open_keys copy1\n";
1195 print $newkeys, $line or die $!;
1197 $keys->error and die $!;
1198 close $newkeys or die "$spath.new $!";
1199 rename "$spath.new", "$spath" or die "$spath: $!";
1200 #print STDERR "_open_keys installed\n";
1201 # that rename effective unlocks, since it makes the name refer
1202 # to the new file which we haven't locked
1203 # we go round again opening the file at the beginning
1204 # so that our caller gets a fresh handle onto the existing key file
1208 sub _fresh_secret ($) {
1210 #print STDERR "_fresh_secret\n";
1212 my $keys = $r->_open_keys();
1213 my ($keyt, $key) = $r->_read_key($keys);
1214 die unless defined $keyt;
1216 my $nonce = $r->_random_key();
1218 my $message = "$noncet.$nonce";
1220 my $signature = $r->_hmac($key, $message);
1221 my $secret = "$keyt.$signature.$message";
1222 #print STDERR "FRESH $secret\n";
1227 my ($r, $keyhex, $message) = @_;
1228 my $keybin = pack "H*", $keyhex;
1229 my $alg = $r->{S}{hash_algorithm};
1230 #print STDERR "hmac $alg\n";
1231 my $base = new Digest $alg;
1232 #print STDERR "hmac $alg $base\n";
1233 my $digest = new Digest::HMAC $keybin, $base;
1234 #print STDERR "hmac $alg $base $digest\n";
1235 $digest->add($message);
1236 return $digest->hexdigest();
1240 my ($r, $message) = @_;
1241 my $alg = $r->{S}{hash_algorithm};
1242 #print STDERR "hash $alg\n";
1243 my $digest = new Digest $alg;
1244 $digest->add($message);
1245 return $digest->hexdigest();
1248 sub _assert_checked ($) {
1250 die "unchecked" unless exists $r->{Divert};
1255 my $meth = $r->_ch('get_method');
1256 return $meth eq 'POST';
1259 sub _must_be_post ($) {
1261 my $meth = $r->_ch('get_method');
1262 die "mutating non-POST" if $meth ne 'POST';
1265 sub check_mutate ($) {
1267 $r->_assert_checked();
1268 die if $r->{Divert};
1269 $r->_must_be_post();
1274 $r->_assert_checked();
1275 die if $r->{Divert};
1276 return $r->_is_post();
1279 #---------- output ----------
1281 sub secret_cookie_val ($) {
1283 $r->_assert_checked();
1284 return defined $r->{AssocSecret} ? $r->{AssocSecret} : '';
1287 sub secret_hidden_val ($) {
1289 $r->_assert_checked();
1290 return defined $r->{AssocSecret} ? $r->hash($r->{AssocSecret}) : '';
1293 sub secret_hidden_html ($) {
1295 return $r->{Cgi}->hidden(-name => $r->{S}{assoc_param_name},
1296 -default => $r->secret_hidden_val());
1299 sub secret_cookie ($) {
1301 my $secret = $r->secret_cookie_val();
1302 return undef if !defined $secret;
1303 #print STDERR "SC\n";
1304 my $cookv = $r->construct_cookie($secret);
1305 #print STDERR "SC=$cookv\n";
1315 CGI::Auth::Flexible - web authentication optionally using cookies
1319 my $verifier = CGI::Auth::Flexible->new_verifier(setting => value,...);
1320 my $authreq = $verifier->new_request($cgi_request_object);
1322 my $authreq = CGI::Auth::Flexible->new_request($cgi_request_object,
1323 setting => value,...);
1325 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
1327 $authreq->check_ok() or return;
1330 $authreq->check_mutate();
1333 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
1335 my $divert_kind = $authreq->check_divert();
1337 if ($divert_kind eq 'LOGGEDOUT') {
1338 print "goodbye you are now logged out" and quit
1339 } elsif ($divert_kind eq 'NOCOOKIES') {
1340 print "you need cookies" and quit
1346 $authreq->check_mutate();