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/;
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);
80 foreach my $name ($c->param()) {
81 $p{$name} = [ $c->param($name) ];
86 sub get_cookie_domain ($$$) {
88 my $uri = new URI $r->_ch('get_url');
92 sub login_ok_password ($$) {
94 my $username_params = $r->{S}{username_param_names};
95 my $username = $r->_ch('get_param',$username_params->[0]);
96 my $password = $r->_rp('password_param_name');
97 my $error = $r->_ch('username_password_error', $username, $password);
98 return defined($error) ? (undef,$error) : ($username,undef);
101 sub do_redirect_cgi ($$$$) {
102 my ($c, $r, $new_url, $cookie) = @_;
103 $r->_print($c->header($r->_cgi_header_args($cookie,
104 -status => '303 See other',
105 -location => $new_url)),
106 $r->_ch('gen_start_html',$r->_gt('Redirection')),
107 '<a href="'.escapeHTML($new_url).'">',
108 $r->_gt("If you aren't redirected, click to continue."),
110 $r->_ch('gen_end_html'));
113 sub gen_some_form ($$) {
114 my ($r, $params, $bodyfn) = @_;
115 # Calls $bodyfn->($c,$r) which returns @formbits
119 $pathinfo .= $params->{''}[0] if $params->{''};
120 push @form, ('<form method="POST" action="'.
121 escapeHTML($r->_ch('get_url').$pathinfo).'">');
122 push @form, $bodyfn->($c,$r);
123 foreach my $n (keys %$params) {
125 foreach my $val (@{ $params->{$n} }) {
126 push @form, ('<input type="hidden"'.
127 ' name="'.escapeHTML($n).'"'.
128 ' value="'.escapeHTML($val).'">');
131 push @form, ('</form>');
132 return join "\n", @form;
135 sub gen_plain_login_form ($$) {
136 my ($c,$r, $params) = @_;
137 return $r->gen_some_form($params, sub {
139 push @form, ('<table>');
140 my $sz = 'size="'.$r->{S}{form_entry_size}.'"';
141 foreach my $up (@{ $r->{S}{username_param_names}}) {
142 push @form, ('<tr><td>',$r->_gt(ucfirst $up),'</td>',
143 '<td><input type="text" '.$sz.
144 ' name='.$up.'></td></tr>');
146 push @form, ('<tr><td>'.$r->_gt('Password').'</td>',
147 '<td><input type="password" '.$sz.
148 ' name="'.$r->{S}{password_param_name}.'"></td></tr>');
149 push @form, ('<tr><td colspan="2">',
150 '<input type="submit"'.
151 ' name="'.$r->{S}{dummy_param_name_prefix}.'login"'.
152 ' value="'.$r->_gt('Login').'"></td></tr>',
158 sub gen_postmainpage_form ($$$) {
159 my ($c,$r, $params) = @_;
160 return $r->gen_some_form($params, sub {
162 push @form, ('<input type="submit"',
163 ' name="'.$r->{S}{dummy_param_name_prefix}.'submit"'.
164 ' value="'.$r->_gt('Continue').'">');
169 sub gen_plain_login_link ($$) {
170 my ($c,$r, $params) = @_;
171 my $url = $r->url_with_query_params($params);
172 return ('<a href="'.escapeHTML($url).'">'.
173 $r->_gt('Log in again to continue.').
177 sub gen_srcdump_link_html ($$$$) {
178 my ($c,$r,$anchor,$specval) = @_;
179 my %params = ($r->{S}{srcdump_param_name} => [ $specval ]);
180 return '<a href="'.escapeHTML($r->url_with_query_params(\%params)).'">'.
183 sub gen_plain_licence_link_html ($$) {
185 gen_srcdump_link_html($c,$r, 'GNU Affero GPL', 'licence');
187 sub gen_plain_source_link_html ($$) {
189 gen_srcdump_link_html($c,$r, 'Source available', 'source');
192 sub gen_plain_footer_html ($$) {
194 return ('<hr><address>',
195 ("Powered by Free / Libre / Open Source Software".
196 " according to the ".$r->_ch('gen_licence_link_html')."."),
197 $r->_ch('gen_source_link_html').".",
201 #---------- licence and source code ----------
203 sub srcdump_dump ($$$) {
204 my ($c,$r, $thing) = @_;
205 die if $thing =~ m/\W/ || $thing !~ m/\w/;
206 my $path = $r->_get_path('srcdump');
207 my $ctf = new IO::File "$path/$thing.ctype", 'r'
208 or die "$path/$thing.ctype $!";
210 chomp $ct or die "$path/$thing ?";
211 $ctf->close or die "$path/$thing $!";
212 my $df = new IO::File "$path/$thing.data", 'r'
213 or die "$path/$thing.data $!";
214 $r->_ch('dump', $ct, $df);
217 sub dump_plain ($$$$) {
218 my ($c, $r, $ct, $df) = @_;
219 $r->_print($c->header('-type' => $ct));
222 my $got = read $df, $buffer, 65536;
223 die $! unless defined $got;
229 sub srcdump_process_dir ($$$$$$) {
230 my ($c, $v, $dumpdir, $incdir, $tarballcounter,
231 $needlicence, $dirsdone) = @_;
232 return () if $v->_ch('srcdump_system_dir', $incdir);
233 my $upwards = $incdir;
236 last unless $upwards =~ m#[^/]#;
237 foreach my $try (@{ $v->{S}{srcdump_vcs_dirs} }) {
238 #print STDERR "TRY $incdir $upwards $try\n";
239 if (!stat "$upwards/$try") {
240 $!==&ENOENT or die "check $upwards/$try $!";
243 #print STDERR "VCS $incdir $upwards $try\n";
244 return if $dirsdone->{$upwards}++;
245 #print STDERR "VCS $incdir $upwards $try GO\n";
246 $try =~ m/\w+/ or die;
247 return $v->_ch(('srcdump_byvcs_'.lc $&),
248 $dumpdir, $upwards, $tarballcounter);
250 $upwards =~ s#/*[^/]+##;
252 return $v->_ch('srcdump_novcs', $dumpdir, $incdir, $tarballcounter);
255 sub srcdump_novcs ($$$$$) {
256 my ($c, $v, $dumpdir, $dir, $tarballcounter) = @_;
257 my $script = 'find -type f -perm +004';
258 foreach my $excl (@{ $v->{S}{srcdump_excludes} }) {
259 $script .= " \\! -name '$excl'";
261 $script .= " -print0";
262 return srcdump_dir_cpio($c,$v,$dumpdir,$dir,$tarballcounter,$script);
265 sub srcdump_byvcs_git ($$$$$) {
266 my ($c, $v, $dumpdir, $dir, $tarballcounter) = @_;
267 #print STDERR "BYVCS GIT $dir\n";
268 return srcdump_dir_cpio($c,$v,$dumpdir,$dir,$tarballcounter,"
270 git ls-files -z --others --exclude-from=.gitignore
275 sub srcdump_dir_cpio ($$$$$) {
276 my ($c,$v,$dumpdir,$dir,$tarballcounter,$script) = @_;
277 my $outfile = "$dumpdir/$$tarballcounter.tar";
278 #print STDERR "CPIO $dir >$script<\n";
280 defined $pid or die $!;
282 $SIG{__DIE__} = sub {
283 print STDERR "CGI::Auth::Flexible srcdump error: $@\n";
286 open STDOUT, ">", $outfile or die "$outfile $!";
287 chdir $dir or die "chdir $dir: $!";
288 exec '/bin/bash','-ec',"
293 cpio -Hustar -o --quiet -0 -R 1000:1000 || \
294 cpio -Hustar -o --quiet -0
299 $!=0; (waitpid $pid, 0) == $pid or die "$!";
300 die "$dir ($script) $outfile $?" if $?;
302 "CGI::Auth::Flexible srcdump_dir_cpio saved $dir into $outfile\n"
308 sub srcdump_dirscan_prepare ($$) {
310 my $dumpdir = $v->_get_path('srcdump');
311 mkdir $dumpdir or $!==&EEXIST or die "mkdir $dumpdir $!";
312 my $lockf = new IO::File "$dumpdir/generate.lock", 'w+'
313 or die "$dumpdir/generate.lock $!";
314 flock $lockf, LOCK_EX or die "$dumpdir/generate.lock $!";
315 my $needlicence = "$dumpdir/licence.tmp";
316 unlink $needlicence or $!==&ENOENT or die "rm $needlicence $!";
317 if (defined $v->{S}{srcdump_licence_path}) {
318 copy($v->{S}{srcdump_licence_path}, $needlicence)
319 or die "$v->{S}{srcdump_licence_path} $!";
320 $needlicence = undef;
322 unlink <"$dumpdir/[a-z][a-z][a-z].tar">;
323 my $srctarballcounter = 'aaa';
325 my @srcfiles = ("$dumpdir/licence.data");
326 foreach my $incdir ($v->_ch('srcdump_includedirs')) {
327 if ($incdir eq '.' && $v->{S}{srcdump_filter_cwd}) {
328 my @bad = grep { !m#^/# } values %INC;
329 die "filtering . from srcdump dirs and \@INC but already".
330 " included @bad " if @bad;
331 @INC = grep { $_ ne '.' } @INC;
334 if (!stat "$incdir/.") {
336 die "stat $incdir $!";
338 if (defined $needlicence) {
339 foreach my $try (@{ $v->{S}{srcdump_licence_files} }) {
340 last if copy("$incdir/$try", $needlicence);
341 $!==&ENOENT or die "copy $incdir/$try $!";
344 push @srcfiles, $v->_ch('srcdump_process_dir', $dumpdir, $incdir,
345 \$srctarballcounter, \$needlicence, \%dirsdone);
346 $dirsdone{$incdir}++;
349 my $r = system qw(tar -zvvc -f), "$dumpdir/source.tmp", '--', @srcfiles;
350 die "tar $r $!" if $r;
351 die "licence file not found" unless defined $needlicence;
352 srcdump_install($c,$v, $dumpdir, 'licence', 'text/plain');
353 srcdump_install($c,$v, $dumpdir, 'source', 'application/octet-stream');
354 close $lockf or die $!;
357 sub srcdump_install ($$$$$) {
358 my ($c,$v, $dumpdir, $which, $ctype) = @_;
359 rename "$dumpdir/$which.tmp", "$dumpdir/$which.data"
360 or die "$dumpdir/$which.data $!";
361 my $ctf = new IO::File "$dumpdir/$which.tmp", 'w'
362 or die "$dumpdir/$which.tmp $!";
363 print $ctf $ctype, "\n" or die $!;
364 close $ctf or die $!;
365 rename "$dumpdir/$which.tmp", "$dumpdir/$which.ctype"
366 or die "$dumpdir/$which.ctype $!";
369 #---------- verifier object methods ----------
376 assocdb_dbh => undef, # must have AutoCommit=0, RaiseError=1
377 assocdb_path => 'caf-assocs.db',
378 keys_path => 'caf-keys',
379 srcdump_path => 'caf-srcdump',
380 assocdb_dsn => undef,
382 assocdb_password => '',
383 assocdb_table => 'caf_assocs',
384 random_source => '/dev/urandom',
385 secretbits => 128, # bits
386 hash_algorithm => "SHA-256",
387 login_timeout => 86400, # seconds
388 login_form_timeout => 3600, # seconds
389 key_rollover => 86400, # seconds
390 assoc_param_name => 'caf_assochash',
391 dummy_param_name_prefix => 'caf__',
392 cookie_name => "caf_assocsecret",
393 password_param_name => 'password',
394 srcdump_param_name => 'caf_srcdump',
395 username_param_names => [qw(username)],
396 form_entry_size => 60,
397 logout_param_names => [qw(caf_logout)],
398 loggedout_param_names => [qw(caf_loggedout)],
399 promise_check_mutate => 0,
400 get_param => sub { $_[0]->param($_[2]) },
401 get_params => sub { $_[1]->get_params() },
402 get_path_info => sub { $_[0]->path_info() },
403 get_cookie => sub { $_[0]->cookie($_[1]->{S}{cookie_name}) },
404 get_method => sub { $_[0]->request_method() },
405 check_https => sub { !!$_[0]->https() },
406 get_url => sub { $_[0]->url(); },
407 is_login => sub { defined $_[1]->_rp('password_param_name') },
408 login_ok => \&login_ok_password,
409 username_password_error => sub { die },
410 is_logout => sub { $_[1]->has_a_param('logout_param_names') },
411 is_loggedout => sub { $_[1]->has_a_param('loggedout_param_names') },
412 is_page => sub { return 1 },
413 handle_divert => sub { return 0 },
414 do_redirect => \&do_redirect_cgi, # this hook is allowed to throw
416 get_cookie_domain => \&get_cookie_domain,
418 gen_start_html => sub { $_[0]->start_html($_[2]); },
419 gen_footer_html => \&gen_plain_footer_html,
420 gen_licence_link_html => \&gen_plain_licence_link_html,
421 gen_source_link_html => \&gen_plain_source_link_html,
422 gen_end_html => sub { $_[0]->end_html(); },
423 gen_login_form => \&gen_plain_login_form,
424 gen_login_link => \&gen_plain_login_link,
425 gen_postmainpage_form => \&gen_postmainpage_form,
426 srcdump_dump => \&srcdump_dump,
427 srcdump_prepare => \&srcdump_dirscan_prepare,
428 srcdump_licence_path => undef,
429 srcdump_licence_files => [qw(AGPLv3 CGI/Auth/Flexible/AGPLv3)],
430 srcdump_includedirs => sub { return @INC; },
431 srcdump_filter_cwd => 1,
432 srcdump_system_dir => sub { $_[2] =~ m#^/etc/|^/usr/(?!local/)#; },
433 srcdump_process_dir => \&srcdump_process_dir,
434 srcdump_vcs_dirs => [qw(.git .hg .svn CVS)],
435 srcdump_byvcs_git => \&srcdump_byvcs_git,
436 srcdump_byvcs_hg => \&srcdump_byvcs_hg,
437 srcdump_byvcs_svn => \&srcdump_byvcs_svn,
438 srcdump_byvcs_cvs => \&srcdump_byvcs_cvs,
439 srcdump_novcs => \&srcdump_novcs,
440 srcdump_excludes => [qw(*~ *.bak *.tmp), '#*#'],
441 dump => \&dump_plain,
442 gettext => sub { gettext($_[2]); },
443 print => sub { print $_[2] or die $!; },
444 debug => sub { }, # like print; msgs contain trailing \n
449 while (($k,$v,@_) = @_) {
450 die "unknown setting $k" unless exists $verifier->{S}{$k};
451 $verifier->{S}{$k} = $v;
453 bless $verifier, $class;
454 $verifier->_dbopen();
455 $verifier->_ch('srcdump_prepare');
459 sub _db_setup_do ($$) {
463 $v->_db_transaction(sub {
464 local ($dbh->{PrintError}) = 0;
475 $dbh = $v->{S}{assocdb_dbh};
477 die if $dbh->{AutoCommit};
478 die unless $dbh->{RaiseError};
480 $v->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=".$v->_get_path('assocdb');
481 my $dsn = $v->{S}{assocdb_dsn};
484 $dbh = DBI->connect($dsn, $v->{S}{assocdb_user},
485 $v->{S}{assocdb_password}, {
488 ShowErrorStatement => 1,
491 die "$dsn $! ?" unless $dbh;
495 $v->_db_setup_do("CREATE TABLE $v->{S}{assocdb_table} (".
496 " assochash VARCHAR PRIMARY KEY,".
497 " username VARCHAR NOT NULL,".
498 " last INTEGER NOT NULL".
500 $v->_db_setup_do("CREATE INDEX $v->{S}{assocdb_table}_timeout_index".
501 " ON $v->{S}{assocdb_table}".
513 sub _db_transaction ($$) {
518 #print STDERR "DT entry\n";
520 #print STDERR "DT loop\n";
523 #print STDERR "DT fn ok\n";
526 #print STDERR "DT fn error\n";
527 { local ($@); $dbh->rollback(); }
528 #print STDERR "DT fn throwing\n";
531 #print STDERR "DT fn eval ok\n";
534 #print STDERR "DT commit ok\n";
537 #print STDERR "DT commit eval ok ",Dumper($rv);
540 #print STDERR "DT commit throw?\n";
541 die $@ if !--$retries;
542 #print STDERR "DT loop again\n";
546 #---------- request object methods ----------
549 my ($classbase, $cgi, @extra) = @_;
550 if (!ref $classbase) {
551 $classbase = $classbase->new_verifier(@extra);
557 S => $classbase->{S},
558 Dbh => $classbase->{Dbh},
561 bless $r, ref $classbase;
564 sub _ch ($$@) { # calls an application hook
565 my ($r,$methname, @args) = @_;
566 my $methfunc = $r->{S}{$methname};
567 die "$methname ?" unless $methfunc;
568 return $methfunc->($r->{Cgi}, $r, @args);
573 my $pn = $r->{S}{$pnvb};
574 my $p = scalar $r->_ch('get_param',$pn)
579 $r->_ch('debug',@args);
583 my ($r,$keybase) = @_;
584 my $leaf = $r->{S}{"${keybase}_path"};
585 return $r->_absify_path($leaf);
588 sub _absify_path ($$) {
590 return $leaf if $leaf =~ m,^/,;
591 my $dir = $v->{S}{dir};
592 die "relying on cwd by default ?! set dir" unless defined $dir;
596 sub _gt ($$) { my ($r, $t) = @_; return $r->_ch('gettext',$t); }
597 sub _print ($$) { my ($r, @t) = @_; return $r->_ch('print', join '', @t); }
599 sub construct_cookie ($$$) {
600 my ($r, $cooks) = @_;
601 return undef unless $cooks;
603 my @ca = (-name => $r->{S}{cookie_name},
605 -path => $r->{S}{cookie_path},
606 -domain => $r->_ch('get_cookie_domain'),
607 -expires => '+'.$r->{S}{login_timeout}.'s',
608 -secure => $r->{S}{encrypted_only});
609 my $cookie = $c->cookie(@ca);
610 #print STDERR "CC $r $c $cooks $cookie (@ca).\n";
614 # pages/param-sets are
615 # n normal non-mutating page
616 # r retrieval of information for JS, non-mutating
618 # u update of information by JS, mutating
621 # O "you have just logged out" page load
624 # - no value supplied (represented in code as $cookt='')
625 # n, nN value not in our db
626 # t, tN temporary value (in our db, no logged in user yet)
627 # y, yN value corresponds to logged-in user
628 # and, aggregated conditions:
629 # a, aN anything including -
631 # if N differs the case applies only when the two values differ
632 # (eg, a1 y2 does not apply when the logged-in value is supplied twice)
634 # "stale session" means request originates from a page from a login
635 # session which has been revoked (eg by logout); "cleared session"
636 # means request originates from a browser which has a different (or
639 # Case analysis, cookie mode, app promises re mutate:
640 # cook parm meth form
642 # any - POST nrmuoi bug or attack, fail
643 # any - GET rmuoi bug or attack, fail
644 # any any GET muoi bug or attack, fail
645 # any t any nrmu bug or attack, fail
647 # - - GET O "just logged out" page
648 # (any other) O bug or attack, fail
650 # a1 a2 POST o logout
651 # if a1 is valid, revoke it
652 # if a2 is valid, revoke it
654 # redirect to "just logged out" page
655 # (which contains link to login form)
657 # - t POST i complain about cookies being disabled
658 # (with link to login form)
660 # t1 t1 POST i login (or switch user)
662 # show new login form
664 # upgrade t1 to y1 in our db (setting username)
665 # redirect to GET of remaining params
667 # y1 a2 POST i complain about stale login form
669 # show new login form
671 # (other) POST i complain about stale login form
672 # show new login form
674 # t1 a2 ANY nrmu treat as - a2 ANY
676 # y - GET n cross-site link
679 # y y GET nr fine, show page or send data
680 # y y POST nrmu mutation is OK, do operation
682 # y1 y2 GET nr request from stale page
683 # do not revoke y2 as not RESTful
686 # y1 y2 POST nrmu request from stale page
690 # y n GET n intra-site link from stale page,
691 # treat as cross-site link, show data
693 # y n POST n m intra-site form submission from stale page
694 # show "session interrupted"
695 # with link to main data page
697 # y n GET r intra-site request from stale page
700 # y n POST r u intra-site request from stale page
703 # -/n y2 GET nr intra-site link from cleared session
704 # do not revoke y2 as not RESTful
707 # -/n y2 POST nrmu request from cleared session
709 # treat as -/n n POST
711 # -/n -/n GET n cross-site link but user not logged in
712 # show login form with redirect to orig params
713 # generate fresh cookie
715 # -/n n GET rmu user not logged in
718 # -/n n POST n m user not logged in
721 # -/n n POST r u user not logged in
724 sub _check_divert_core ($) {
727 my $srcdump = $r->_rp('srcdump_param_name');
729 die if $srcdump =~ m/\W/;
730 return ({ Kind => 'SRCDUMP-'.uc $srcdump,
732 CookieSecret => undef,
736 my $cooks = $r->_ch('get_cookie');
738 if ($r->{S}{encrypted_only} && !$r->_ch('check_https')) {
739 return ({ Kind => 'REDIRECT-HTTPS',
740 Message => $r->_gt("Redirecting to secure server..."),
741 CookieSecret => undef,
745 my $meth = $r->_ch('get_method');
746 my $parmh = $r->_rp('assoc_param_name');
747 my $cookh = defined $cooks ? $r->hash($cooks) : undef;
749 my ($cookt,$cooku) = $r->_identify($cookh, $cooks);
750 my $parms = (defined $cooks && defined $parmh && $parmh eq $cookh)
752 my ($parmt) = $r->_identify($parmh, $parms);
754 $r->_debug("_c_d_c cookt=$cookt parmt=$parmt\n");
756 if ($r->_ch('is_logout')) {
759 $r->_db_revoke($cookh);
760 $r->_db_revoke($parmh);
761 return ({ Kind => 'REDIRECT-LOGGEDOUT',
762 Message => $r->_gt("Logging out..."),
766 if ($r->_ch('is_loggedout')) {
767 die unless $meth eq 'GET';
768 die if $cookt eq 'y';
770 return ({ Kind => 'SMALLPAGE-LOGGEDOUT',
771 Message => $r->_gt("You have been logged out."),
775 if ($r->_ch('is_login')) {
778 if (!$cookt && $parmt eq 'n') {
779 return ({ Kind => 'SMALLPAGE-NOCOOKIE',
780 Message => $r->_gt("You do not seem to have cookies".
781 " enabled. You must enable cookies".
782 " as we use them for login."),
783 CookieSecret => $r->_fresh_secret(),
784 Params => $r->chain_params() })
786 if (!$cookt || $cookt eq 'n' || $cookh ne $parmh) {
787 $r->_db_revoke($cookh);
788 return ({ Kind => 'LOGIN-STALE',
789 Message => $r->_gt("Stale session;".
790 " you need to log in again."),
791 CookieSecret => $r->_fresh_secret(),
794 die unless $parmt eq 't' || $parmt eq 'y';
795 my ($username, $login_errormessage) = $r->_ch('login_ok');
796 unless (defined $username && length $username) {
797 $login_errormessage = $r->_gt("Incorrect username/password.")
798 if !$login_errormessage;
799 return ({ Kind => 'LOGIN-BAD',
800 Message => $login_errormessage,
801 CookieSecret => $cooks,
802 Params => $r->chain_params() })
804 $r->_db_record_login_ok($parmh,$username);
805 return ({ Kind => 'REDIRECT-LOGGEDIN',
806 Message => $r->_gt("Logging in..."),
807 CookieSecret => $cooks,
808 Params => $r->chain_params() });
813 die if $parmt eq 't';
815 if ($cookt eq 'y' && $parmt eq 'y' && $cookh ne $parmh) {
816 $r->_db_revoke($parmh) if $meth eq 'POST';
821 die unless !$cookt || $cookt eq 'n';
822 die unless !$parmt || $parmt eq 'n' || $parmt eq 'y';
823 my $news = $r->_fresh_secret();
824 if ($meth eq 'GET') {
825 return ({ Kind => 'LOGIN-INCOMINGLINK',
826 Message => $r->_gt("You need to log in."),
827 CookieSecret => $news,
828 Params => $r->chain_params() });
830 $r->_db_revoke($parmh);
831 return ({ Kind => 'LOGIN-FRESH',
832 Message => $r->_gt("You need to log in."),
833 CookieSecret => $news,
838 if (!$r->{S}{promise_check_mutate}) {
839 if ($meth ne 'POST') {
840 return ({ Kind => 'MAINPAGEONLY',
841 Message => $r->_gt('Entering via cross-site link.'),
842 CookieSecret => $cooks,
844 # NB caller must then ignore params & path!
845 # if this is too hard they can spit out a small form
846 # with a "click to continue"
850 die unless $cookt eq 'y';
851 unless ($r->{S}{promise_check_mutate} && $meth eq 'GET') {
852 die unless $parmt eq 'y';
853 die unless $cookh eq $parmh;
855 $r->{AssocSecret} = $cooks;
856 $r->{UserOK} = $cooku;
857 #print STDERR "C-D-C OK\n";
861 sub chain_params ($) {
863 my %p = %{ $r->_ch('get_params') };
864 foreach my $pncn (keys %{ $r->{S} }) {
866 if ($pncn =~ m/_param_name$/) {
867 my $name = $r->{S}{$pncn};
868 die "$pncn ?" if ref $name;
870 } elsif ($pncn =~ m/_param_names$/) {
871 $names = $r->{S}{$pncn};
875 foreach my $name (@$names) {
879 my $dummy_prefix = $r->{S}{dummy_param_name_prefix};
880 foreach my $name (grep /^$dummy_prefix/, keys %p) {
883 die if exists $p{''};
884 $p{''} = [ $r->_ch('get_path_info') ];
890 # returns ($t,$username)
891 # where $t is one of "t" "y" "n", or "" (for -)
892 # either $s must be undef, or $h eq $r->hash($s)
894 #print STDERR "_identify\n";
895 return '' unless defined $h && length $h;
896 #print STDERR "_identify h=$h s=".(defined $s ? $s : '<undef>')."\n";
900 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
901 " WHERE last < ?", {},
902 time - $r->{S}{login_timeout});
904 my $row = $dbh->selectrow_arrayref("SELECT username, last".
905 " FROM $r->{S}{assocdb_table}".
906 " WHERE assochash = ?", {}, $h);
908 #print STDERR "_identify h=$h s=$s YES @$row\n";
909 my ($nusername, $nlast) = @$row;
910 return ('y', $nusername);
913 # Well, it's not in the database. But maybe it's a hash of a
916 return 'n' unless defined $s;
918 my ($keyt, $signature, $message, $noncet, $nonce) =
919 $s =~ m/^(\d+)\.(\w+)\.((\d+)\.(\w+))$/ or die;
921 return 'n' if time > $noncet + $r->{S}{login_form_timeout};
923 #print STDERR "_identify noncet=$noncet ok\n";
925 my $keys = $r->_open_keys();
926 while (my ($rkeyt, $rkey, $line) = $r->_read_key($keys)) {
927 #print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey\n";
928 last if $rkeyt < $keyt; # too far down in the file
929 my $trysignature = $r->_hmac($rkey, $message);
930 #print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey try=$trysignature\n";
931 return 't' if $trysignature eq $signature;
934 #print STDERR "_identify NO\n";
936 $keys->error and die $!;
940 sub _db_revoke ($$) {
941 # revokes $h if it's valid; no-op if it's not
946 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
947 " WHERE assochash = ?", {}, $h);
950 sub _db_record_login_ok ($$$) {
951 my ($r,$h,$user) = @_;
954 $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
955 " (assochash, username, last) VALUES (?,?,?)", {},
959 sub check_divert ($) {
961 if (exists $r->{Divert}) {
965 $r->{Divert} = $r->_db_transaction(sub { $r->_check_divert_core(); });
967 $r->_debug(Data::Dumper->Dump([$r->{Divert}],[qw(divert)]));
973 die "unchecked" unless exists $r->{Divert};
977 sub get_username ($) {
979 my $divert = $r->get_divert();
980 return undef if $divert;
984 sub url_with_query_params ($$) {
985 my ($r, $params) = @_;
986 #print STDERR "PARAMS ",Dumper($params);
987 my $uri = URI->new($r->_ch('get_url'));
988 $uri->path($uri->path() . $params->{''}[0]) if $params->{''};
989 $uri->query_form(flatten_params($params));
990 return $uri->as_string();
993 sub _cgi_header_args ($$@) {
994 my ($r, $cookie, @ha) = @_;
995 unshift @ha, qw(-type text/html);
996 push @ha, (-cookie => $cookie) if defined $cookie;
997 #print STDERR "_cgi_header_args ",join('|',@ha),".\n";
1004 my ($divert) = $r->check_divert();
1005 return 1 if !$divert;
1007 my $handled = $r->_ch('handle_divert',$divert);
1008 return 0 if $handled;
1010 my $kind = $divert->{Kind};
1011 my $cookiesecret = $divert->{CookieSecret};
1012 my $params = $divert->{Params};
1013 my $cookie = $r->construct_cookie($cookiesecret);
1015 if ($kind =~ m/^SRCDUMP-(\w+)$/) {
1016 $r->_ch('srcdump_dump', (lc $1));
1020 if ($kind =~ m/^REDIRECT-/) {
1021 # for redirects, we honour stored NextParams and SetCookie,
1022 # as we would for non-divert
1023 if ($kind eq 'REDIRECT-LOGGEDOUT') {
1024 $params->{$r->{S}{loggedout_param_names}[0]} = [ 1 ];
1025 } elsif ($kind eq 'REDIRECT-LOGOUT') {
1026 $params->{$r->{S}{logout_param_names}[0]} = [ 1 ];
1027 } elsif ($kind =~ m/REDIRECT-(?:LOGGEDIN|HTTPS)/) {
1031 my $new_url = $r->url_with_query_params($params);
1032 if ($kind eq 'REDIRECT-HTTPS') {
1033 my $uri = URI->new($new_url);
1034 die unless $uri->scheme eq 'http';
1035 $uri->scheme('https');
1036 $new_url = $uri->as_string();
1038 $r->_ch('do_redirect',$new_url, $cookie);
1042 if (defined $cookiesecret) {
1043 $params->{$r->{S}{assoc_param_name}} = [ $r->hash($cookiesecret) ];
1047 if ($kind =~ m/^LOGIN-/) {
1048 $title = $r->_gt('Login');
1049 push @body, $divert->{Message};
1050 push @body, $r->_ch('gen_login_form', $params);
1051 } elsif ($kind =~ m/^SMALLPAGE-/) {
1052 $title = $r->_gt('Not logged in');
1053 push @body, $divert->{Message};
1054 push @body, $r->_ch('gen_login_link', $params);
1055 } elsif ($kind =~ m/^MAINPAGEONLY$/) {
1056 $title = $r->_gt('Entering secure site.');
1057 push @body, $divert->{Message};
1058 push @body, $r->_ch('gen_postmainpage_form', $params);
1063 $r->_print($r->{Cgi}->header($r->_cgi_header_args($cookie)),
1064 $r->_ch('gen_start_html',$title),
1066 $r->_ch('gen_footer_html'),
1067 $r->_ch('gen_end_html'))));
1072 my ($r, $bytes) = @_;
1074 my $rsf = $v->{RandomHandle};
1075 my $rsp = $r->{S}{random_source};
1077 $v->{RandomHandle} = $rsf = new IO::File $rsp, '<' or die "$rsp $!";
1078 #print STDERR "RH $rsf\n";
1082 read($rsf,$bin,$bytes) == $bytes or die "$rsp $!";
1083 my $out = unpack "H*", $bin;
1084 #print STDERR "_random out $out\n";
1088 sub _random_key ($) {
1090 #print STDERR "_random_key\n";
1091 my $bytes = ($r->{S}{secretbits} + 7) >> 3;
1092 return $r->_random($bytes);
1095 sub _read_key ($$) {
1096 my ($r, $keys) = @_;
1097 # returns $gen_time_t, $key_value_in_hex, $complete_line
1099 my ($gen, $k) = m/^(\d+) (\S+)$/ or die "$_ ?";
1100 my $age = time - $gen;
1101 next if $age > $r->{S}{key_rollover} &&
1102 $age > $r->{S}{login_form_timeout}*2;
1103 return ($gen, $k, $_);
1108 sub _open_keys ($) {
1110 my $spath = $r->_get_path('keys');
1112 #print STDERR "_open_keys\n";
1113 my $keys = new IO::File $spath, 'r+';
1115 #print STDERR "_open_keys open\n";
1116 stat $keys or die $!; # NB must not disturb stat _
1117 my $size = (stat _)[7];
1118 my $age = time - (stat _)[9];
1119 #print STDERR "_open_keys open size=$size age=$age\n";
1121 if $size && $age <= $r->{S}{key_rollover} / 2;
1122 #print STDERR "_open_keys open bad\n";
1124 # file doesn't exist, or is empty or too old
1126 #print STDERR "_open_keys closed\n";
1127 die "$spath $!" unless $!==&ENOENT;
1128 # doesn't exist, so create it just so we can lock it
1129 $keys = new IO::File $spath, 'a+';
1130 die "$keys $!" unless $keys;
1131 stat $keys or die $!; # NB must not disturb stat _
1132 my $size = (stat _)[7];
1133 #print STDERR "_open_keys created size=$size\n";
1134 next if $size; # oh someone else has done it, reopen and read it
1136 # file now exists is empty or too old, we must try to replace it
1137 my $our_inum = (stat _)[1]; # last use of that stat _
1138 flock $keys, LOCK_EX or die "$spath $!";
1139 stat $spath or die "$spath $!";
1140 my $path_inum = (stat _)[1];
1141 #print STDERR "_open_keys locked our=$our_inum path=$path_inum\n";
1142 next if $our_inum != $path_inum; # someone else has done it
1143 # We now hold the lock!
1144 #print STDERR "_open_keys creating\n";
1145 my $newkeys = new IO::Handle;
1146 sysopen $newkeys, "$spath.new", O_CREAT|O_TRUNC|O_WRONLY, 0600
1147 or die "$spath.new $!";
1148 # we add the new key to the front which means it's always sorted
1149 print $newkeys time, ' ', $r->_random_key(), "\n" or die $!;
1150 while (my ($gen,$key,$line) = $r->_read_key($keys)) {
1151 #print STDERR "_open_keys copy1\n";
1152 print $newkeys, $line or die $!;
1154 $keys->error and die $!;
1155 close $newkeys or die "$spath.new $!";
1156 rename "$spath.new", "$spath" or die "$spath: $!";
1157 #print STDERR "_open_keys installed\n";
1158 # that rename effective unlocks, since it makes the name refer
1159 # to the new file which we haven't locked
1160 # we go round again opening the file at the beginning
1161 # so that our caller gets a fresh handle onto the existing key file
1165 sub _fresh_secret ($) {
1167 #print STDERR "_fresh_secret\n";
1169 my $keys = $r->_open_keys();
1170 my ($keyt, $key) = $r->_read_key($keys);
1171 die unless defined $keyt;
1173 my $nonce = $r->_random_key();
1175 my $message = "$noncet.$nonce";
1177 my $signature = $r->_hmac($key, $message);
1178 my $secret = "$keyt.$signature.$message";
1179 #print STDERR "FRESH $secret\n";
1184 my ($r, $keyhex, $message) = @_;
1185 my $keybin = pack "H*", $keyhex;
1186 my $alg = $r->{S}{hash_algorithm};
1187 #print STDERR "hmac $alg\n";
1188 my $base = new Digest $alg;
1189 #print STDERR "hmac $alg $base\n";
1190 my $digest = new Digest::HMAC $keybin, $base;
1191 #print STDERR "hmac $alg $base $digest\n";
1192 $digest->add($message);
1193 return $digest->hexdigest();
1197 my ($r, $message) = @_;
1198 my $alg = $r->{S}{hash_algorithm};
1199 #print STDERR "hash $alg\n";
1200 my $digest = new Digest $alg;
1201 $digest->add($message);
1202 return $digest->hexdigest();
1205 sub _assert_checked ($) {
1207 die "unchecked" unless exists $r->{Divert};
1212 my $meth = $r->_ch('get_method');
1213 return $meth eq 'POST';
1216 sub _must_be_post ($) {
1218 my $meth = $r->_ch('get_method');
1219 die "mutating non-POST" if $meth ne 'POST';
1222 sub check_mutate ($) {
1224 $r->_assert_checked();
1225 die if $r->{Divert};
1226 $r->_must_be_post();
1231 $r->_assert_checked();
1232 die if $r->{Divert};
1233 return $r->_is_post();
1236 #---------- output ----------
1238 sub secret_cookie_val ($) {
1240 $r->_assert_checked();
1241 return defined $r->{AssocSecret} ? $r->{AssocSecret} : '';
1244 sub secret_hidden_val ($) {
1246 $r->_assert_checked();
1247 return defined $r->{AssocSecret} ? $r->hash($r->{AssocSecret}) : '';
1250 sub secret_hidden_html ($) {
1252 return $r->{Cgi}->hidden(-name => $r->{S}{assoc_param_name},
1253 -default => $r->secret_hidden_val());
1256 sub secret_cookie ($) {
1258 my $secret = $r->secret_cookie_val();
1259 return undef if !defined $secret;
1260 #print STDERR "SC\n";
1261 my $cookv = $r->construct_cookie($secret);
1262 #print STDERR "SC=$cookv\n";
1272 CGI::Auth::Flexible - web authentication optionally using cookies
1276 my $verifier = CGI::Auth::Flexible->new_verifier(setting => value,...);
1277 my $authreq = $verifier->new_request($cgi_request_object);
1279 my $authreq = CGI::Auth::Flexible->new_request($cgi_request_object,
1280 setting => value,...);
1282 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
1284 $authreq->check_ok() or return;
1287 $authreq->check_mutate();
1290 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
1292 my $divert_kind = $authreq->check_divert();
1294 if ($divert_kind eq 'LOGGEDOUT') {
1295 print "goodbye you are now logged out" and quit
1296 } elsif ($divert_kind eq 'NOCOOKIES') {
1297 print "you need cookies" and quit
1303 $authreq->check_mutate();