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 if (!stat "$upwards/$try") {
239 $!==&ENOENT or die "check $upwards/$try $!";
242 $try =~ m/\w+/ or die;
243 return if $dirsdone->{$upwards}++;
244 return $v->_ch(('srcdump_byvcs_'.lc $try),
245 $dumpdir, $upwards, $tarballcounter);
247 $upwards =~ s#/*[^/]+##;
249 return $v->_ch('srcdump_novcs', $dumpdir, $incdir, $tarballcounter);
252 sub srcdump_novcs ($$$$$) {
253 my ($c, $v, $dumpdir, $dir, $tarballcounter) = @_;
254 my $script = 'find -type f -perm +004';
255 foreach my $excl (@{ $v->{S}{srcdump_excludes} }) {
256 $script .= " \\! -name '$excl'";
258 $script .= " -print0";
259 return srcdump_dir_cpio($c,$v,$dumpdir,$dir,$tarballcounter,$script);
262 sub srcdump_byvcs_git ($$$$$) {
263 my ($c, $v, $dumpdir, $dir, $tarballcounter) = @_;
264 return srcdump_dir_cpio($c,$v,$dumpdir,$dir,$tarballcounter,"
266 git-ls-files -z --others --exclude-from=.gitignore;
271 sub srcdump_dir_cpio ($$$$$) {
272 my ($c,$v,$dumpdir,$dir,$tarballcounter,$script) = @_;
273 my $outfile = "$dumpdir/$$tarballcounter.tar";
275 defined $pid or die $!;
277 open STDOUT, ">", $outfile or die "$outfile $!";
278 chdir $dir or die "chdir $dir: $!";
279 exec '/bin/bash','-ec','',"
284 cpio -Hustar -o --quiet -0 -R 1000:1000 || \
285 cpio -Hustar -o --quiet -0
290 $!=0; (waitpid $pid, 0) == $pid or die "$!";
291 die "$dir ($script) $outfile $?" if $?;
293 "CGI::Auth::Flexible srcdump_dir_cpio saved $dir into $outfile\n"
299 sub srcdump_dirscan_prepare ($$) {
301 my $dumpdir = $v->_get_path('srcdump');
302 mkdir $dumpdir or $!==&EEXIST or die "mkdir $dumpdir $!";
303 my $lockf = new IO::File "$dumpdir/generate.lock", 'w+'
304 or die "$dumpdir/generate.lock $!";
305 flock $lockf, LOCK_EX or die "$dumpdir/generate.lock $!";
306 my $needlicence = "$dumpdir/licence.tmp";
307 unlink $needlicence or $!==&ENOENT or die "rm $needlicence $!";
308 if (defined $v->{S}{srcdump_licence_path}) {
309 copy($v->{S}{srcdump_licence_path}, $needlicence)
310 or die "$v->{S}{srcdump_licence_path} $!";
311 $needlicence = undef;
313 my $srctarballcounter = 'aaa';
315 my @srcfiles = ("$dumpdir/licence.data");
316 foreach my $incdir ($v->_ch('srcdump_includedirs')) {
317 if (defined $needlicence) {
318 foreach my $try (@{ $v->{S}{srcdump_licence_files} }) {
319 last if copy("$incdir/$try", $needlicence);
320 $!==&ENOENT or die "copy $incdir/$try $!";
323 push @srcfiles, $v->_ch('srcdump_process_dir', $dumpdir, $incdir,
324 \$srctarballcounter, \$needlicence, \%dirsdone);
325 $dirsdone{$incdir}++;
328 my $r = system qw(tar -zvvc -f), "$dumpdir/source.tmp", '--', @srcfiles;
329 die "tar $r $!" if $r;
330 die "licence file not found" unless defined $needlicence;
331 srcdump_install($c,$v, $dumpdir, 'licence', 'text/plain');
332 srcdump_install($c,$v, $dumpdir, 'source', 'application/octet-stream');
333 close $lockf or die $!;
336 sub srcdump_install ($$$$$) {
337 my ($c,$v, $dumpdir, $which, $ctype) = @_;
338 rename "$dumpdir/$which.tmp", "$dumpdir/$which.data"
339 or die "$dumpdir/$which.data $!";
340 my $ctf = new IO::File "$dumpdir/$which.tmp", 'w'
341 or die "$dumpdir/$which.tmp $!";
342 print $ctf $ctype, "\n" or die $!;
343 close $ctf or die $!;
344 rename "$dumpdir/$which.tmp", "$dumpdir/$which.ctype"
345 or die "$dumpdir/$which.ctype $!";
348 #---------- verifier object methods ----------
355 assocdb_dbh => undef, # must have AutoCommit=0, RaiseError=1
356 assocdb_path => 'caf-assocs.db',
357 keys_path => 'caf-keys',
358 srcdump_path => 'caf-srcdump',
359 assocdb_dsn => undef,
361 assocdb_password => '',
362 assocdb_table => 'caf_assocs',
363 random_source => '/dev/urandom',
364 secretbits => 128, # bits
365 hash_algorithm => "SHA-256",
366 login_timeout => 86400, # seconds
367 login_form_timeout => 3600, # seconds
368 key_rollover => 86400, # seconds
369 assoc_param_name => 'caf_assochash',
370 dummy_param_name_prefix => 'caf__',
371 cookie_name => "caf_assocsecret",
372 password_param_name => 'password',
373 srcdump_param_name => 'caf_srcdump',
374 username_param_names => [qw(username)],
375 form_entry_size => 60,
376 logout_param_names => [qw(caf_logout)],
377 loggedout_param_names => [qw(caf_loggedout)],
378 promise_check_mutate => 0,
379 get_param => sub { $_[0]->param($_[2]) },
380 get_params => sub { $_[1]->get_params() },
381 get_path_info => sub { $_[0]->path_info() },
382 get_cookie => sub { $_[0]->cookie($_[1]->{S}{cookie_name}) },
383 get_method => sub { $_[0]->request_method() },
384 check_https => sub { !!$_[0]->https() },
385 get_url => sub { $_[0]->url(); },
386 is_login => sub { defined $_[1]->_rp('password_param_name') },
387 login_ok => \&login_ok_password,
388 username_password_error => sub { die },
389 is_logout => sub { $_[1]->has_a_param('logout_param_names') },
390 is_loggedout => sub { $_[1]->has_a_param('loggedout_param_names') },
391 is_page => sub { return 1 },
392 handle_divert => sub { return 0 },
393 do_redirect => \&do_redirect_cgi, # this hook is allowed to throw
395 get_cookie_domain => \&get_cookie_domain,
397 gen_start_html => sub { $_[0]->start_html($_[2]); },
398 gen_footer_html => \&gen_plain_footer_html,
399 gen_licence_link_html => \&gen_plain_licence_link_html,
400 gen_source_link_html => \&gen_plain_source_link_html,
401 gen_end_html => sub { $_[0]->end_html(); },
402 gen_login_form => \&gen_plain_login_form,
403 gen_login_link => \&gen_plain_login_link,
404 gen_postmainpage_form => \&gen_postmainpage_form,
405 srcdump_dump => \&srcdump_dump,
406 srcdump_prepare => \&srcdump_dirscan_prepare,
407 srcdump_licence_path => undef,
408 srcdump_licence_files => [qw(AGPLv3 CGI/Auth/Flexible/AGPLv3)],
409 srcdump_includedirs => sub { return @INC; },
410 srcdump_system_dir => sub { $_[2] =~ m#^/etc/|^/usr/(?!local/)#; },
411 srcdump_process_dir => \&srcdump_process_dir,
412 srcdump_vcs_dirs => [qw(.git .hg .svn CVS)],
413 srcdump_byvcs_git => \&srcdump_byvcs_git,
414 srcdump_byvcs_hg => \&srcdump_byvcs_hg,
415 srcdump_byvcs_svn => \&srcdump_byvcs_svn,
416 srcdump_byvcs_cvs => \&srcdump_byvcs_cvs,
417 srcdump_novcs => \&srcdump_novcs,
418 srcdump_excludes => [qw(*~ *.bak *.tmp), '#*#'],
419 dump => \&dump_plain,
420 gettext => sub { gettext($_[2]); },
421 print => sub { print $_[2] or die $!; },
422 debug => sub { }, # like print; msgs contain trailing \n
427 while (($k,$v,@_) = @_) {
428 die "unknown setting $k" unless exists $verifier->{S}{$k};
429 $verifier->{S}{$k} = $v;
431 bless $verifier, $class;
432 $verifier->_dbopen();
433 $verifier->_ch('srcdump_prepare');
437 sub _db_setup_do ($$) {
441 $v->_db_transaction(sub {
442 local ($dbh->{PrintError}) = 0;
453 $dbh = $v->{S}{assocdb_dbh};
455 die if $dbh->{AutoCommit};
456 die unless $dbh->{RaiseError};
458 $v->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=".$v->_get_path('assocdb');
459 my $dsn = $v->{S}{assocdb_dsn};
462 $dbh = DBI->connect($dsn, $v->{S}{assocdb_user},
463 $v->{S}{assocdb_password}, {
466 ShowErrorStatement => 1,
469 die "$dsn $! ?" unless $dbh;
473 $v->_db_setup_do("CREATE TABLE $v->{S}{assocdb_table} (".
474 " assochash VARCHAR PRIMARY KEY,".
475 " username VARCHAR NOT NULL,".
476 " last INTEGER NOT NULL".
478 $v->_db_setup_do("CREATE INDEX $v->{S}{assocdb_table}_timeout_index".
479 " ON $v->{S}{assocdb_table}".
491 sub _db_transaction ($$) {
496 #print STDERR "DT entry\n";
498 #print STDERR "DT loop\n";
501 #print STDERR "DT fn ok\n";
504 #print STDERR "DT fn error\n";
505 { local ($@); $dbh->rollback(); }
506 #print STDERR "DT fn throwing\n";
509 #print STDERR "DT fn eval ok\n";
512 #print STDERR "DT commit ok\n";
515 #print STDERR "DT commit eval ok ",Dumper($rv);
518 #print STDERR "DT commit throw?\n";
519 die $@ if !--$retries;
520 #print STDERR "DT loop again\n";
524 #---------- request object methods ----------
527 my ($classbase, $cgi, @extra) = @_;
528 if (!ref $classbase) {
529 $classbase = $classbase->new_verifier(@extra);
535 S => $classbase->{S},
536 Dbh => $classbase->{Dbh},
539 bless $r, ref $classbase;
542 sub _ch ($$@) { # calls an application hook
543 my ($r,$methname, @args) = @_;
544 my $methfunc = $r->{S}{$methname};
545 die "$methname ?" unless $methfunc;
546 return $methfunc->($r->{Cgi}, $r, @args);
551 my $pn = $r->{S}{$pnvb};
552 my $p = scalar $r->_ch('get_param',$pn)
557 $r->_ch('debug',@args);
561 my ($r,$keybase) = @_;
562 my $leaf = $r->{S}{"${keybase}_path"};
563 return $r->_absify_path($leaf);
566 sub _absify_path ($$) {
568 return $leaf if $leaf =~ m,^/,;
569 my $dir = $v->{S}{dir};
570 die "relying on cwd by default ?! set dir" unless defined $dir;
574 sub _gt ($$) { my ($r, $t) = @_; return $r->_ch('gettext',$t); }
575 sub _print ($$) { my ($r, @t) = @_; return $r->_ch('print', join '', @t); }
577 sub construct_cookie ($$$) {
578 my ($r, $cooks) = @_;
579 return undef unless $cooks;
581 my @ca = (-name => $r->{S}{cookie_name},
583 -path => $r->{S}{cookie_path},
584 -domain => $r->_ch('get_cookie_domain'),
585 -expires => '+'.$r->{S}{login_timeout}.'s',
586 -secure => $r->{S}{encrypted_only});
587 my $cookie = $c->cookie(@ca);
588 #print STDERR "CC $r $c $cooks $cookie (@ca).\n";
592 # pages/param-sets are
593 # n normal non-mutating page
594 # r retrieval of information for JS, non-mutating
596 # u update of information by JS, mutating
599 # O "you have just logged out" page load
602 # - no value supplied (represented in code as $cookt='')
603 # n, nN value not in our db
604 # t, tN temporary value (in our db, no logged in user yet)
605 # y, yN value corresponds to logged-in user
606 # and, aggregated conditions:
607 # a, aN anything including -
609 # if N differs the case applies only when the two values differ
610 # (eg, a1 y2 does not apply when the logged-in value is supplied twice)
612 # "stale session" means request originates from a page from a login
613 # session which has been revoked (eg by logout); "cleared session"
614 # means request originates from a browser which has a different (or
617 # Case analysis, cookie mode, app promises re mutate:
618 # cook parm meth form
620 # any - POST nrmuoi bug or attack, fail
621 # any - GET rmuoi bug or attack, fail
622 # any any GET muoi bug or attack, fail
623 # any t any nrmu bug or attack, fail
625 # - - GET O "just logged out" page
626 # (any other) O bug or attack, fail
628 # a1 a2 POST o logout
629 # if a1 is valid, revoke it
630 # if a2 is valid, revoke it
632 # redirect to "just logged out" page
633 # (which contains link to login form)
635 # - t POST i complain about cookies being disabled
636 # (with link to login form)
638 # t1 t1 POST i login (or switch user)
640 # show new login form
642 # upgrade t1 to y1 in our db (setting username)
643 # redirect to GET of remaining params
645 # y1 a2 POST i complain about stale login form
647 # show new login form
649 # (other) POST i complain about stale login form
650 # show new login form
652 # t1 a2 ANY nrmu treat as - a2 ANY
654 # y - GET n cross-site link
657 # y y GET nr fine, show page or send data
658 # y y POST nrmu mutation is OK, do operation
660 # y1 y2 GET nr request from stale page
661 # do not revoke y2 as not RESTful
664 # y1 y2 POST nrmu request from stale page
668 # y n GET n intra-site link from stale page,
669 # treat as cross-site link, show data
671 # y n POST n m intra-site form submission from stale page
672 # show "session interrupted"
673 # with link to main data page
675 # y n GET r intra-site request from stale page
678 # y n POST r u intra-site request from stale page
681 # -/n y2 GET nr intra-site link from cleared session
682 # do not revoke y2 as not RESTful
685 # -/n y2 POST nrmu request from cleared session
687 # treat as -/n n POST
689 # -/n -/n GET n cross-site link but user not logged in
690 # show login form with redirect to orig params
691 # generate fresh cookie
693 # -/n n GET rmu user not logged in
696 # -/n n POST n m user not logged in
699 # -/n n POST r u user not logged in
702 sub _check_divert_core ($) {
705 my $srcdump = $r->_rp('srcdump_param_name');
707 die if $srcdump =~ m/\W/;
708 return ({ Kind => 'SRCDUMP-'.uc $srcdump,
710 CookieSecret => undef,
714 my $cooks = $r->_ch('get_cookie');
716 if ($r->{S}{encrypted_only} && !$r->_ch('check_https')) {
717 return ({ Kind => 'REDIRECT-HTTPS',
718 Message => $r->_gt("Redirecting to secure server..."),
719 CookieSecret => undef,
723 my $meth = $r->_ch('get_method');
724 my $parmh = $r->_rp('assoc_param_name');
725 my $cookh = defined $cooks ? $r->hash($cooks) : undef;
727 my ($cookt,$cooku) = $r->_identify($cookh, $cooks);
728 my $parms = (defined $cooks && defined $parmh && $parmh eq $cookh)
730 my ($parmt) = $r->_identify($parmh, $parms);
732 $r->_debug("_c_d_c cookt=$cookt parmt=$parmt\n");
734 if ($r->_ch('is_logout')) {
737 $r->_db_revoke($cookh);
738 $r->_db_revoke($parmh);
739 return ({ Kind => 'REDIRECT-LOGGEDOUT',
740 Message => $r->_gt("Logging out..."),
744 if ($r->_ch('is_loggedout')) {
745 die unless $meth eq 'GET';
746 die if $cookt eq 'y';
748 return ({ Kind => 'SMALLPAGE-LOGGEDOUT',
749 Message => $r->_gt("You have been logged out."),
753 if ($r->_ch('is_login')) {
756 if (!$cookt && $parmt eq 'n') {
757 return ({ Kind => 'SMALLPAGE-NOCOOKIE',
758 Message => $r->_gt("You do not seem to have cookies".
759 " enabled. You must enable cookies".
760 " as we use them for login."),
761 CookieSecret => $r->_fresh_secret(),
762 Params => $r->chain_params() })
764 if (!$cookt || $cookt eq 'n' || $cookh ne $parmh) {
765 $r->_db_revoke($cookh);
766 return ({ Kind => 'LOGIN-STALE',
767 Message => $r->_gt("Stale session;".
768 " you need to log in again."),
769 CookieSecret => $r->_fresh_secret(),
772 die unless $parmt eq 't' || $parmt eq 'y';
773 my ($username, $login_errormessage) = $r->_ch('login_ok');
774 unless (defined $username && length $username) {
775 $login_errormessage = $r->_gt("Incorrect username/password.")
776 if !$login_errormessage;
777 return ({ Kind => 'LOGIN-BAD',
778 Message => $login_errormessage,
779 CookieSecret => $cooks,
780 Params => $r->chain_params() })
782 $r->_db_record_login_ok($parmh,$username);
783 return ({ Kind => 'REDIRECT-LOGGEDIN',
784 Message => $r->_gt("Logging in..."),
785 CookieSecret => $cooks,
786 Params => $r->chain_params() });
791 die if $parmt eq 't';
793 if ($cookt eq 'y' && $parmt eq 'y' && $cookh ne $parmh) {
794 $r->_db_revoke($parmh) if $meth eq 'POST';
799 die unless !$cookt || $cookt eq 'n';
800 die unless !$parmt || $parmt eq 'n' || $parmt eq 'y';
801 my $news = $r->_fresh_secret();
802 if ($meth eq 'GET') {
803 return ({ Kind => 'LOGIN-INCOMINGLINK',
804 Message => $r->_gt("You need to log in."),
805 CookieSecret => $news,
806 Params => $r->chain_params() });
808 $r->_db_revoke($parmh);
809 return ({ Kind => 'LOGIN-FRESH',
810 Message => $r->_gt("You need to log in."),
811 CookieSecret => $news,
816 if (!$r->{S}{promise_check_mutate}) {
817 if ($meth ne 'POST') {
818 return ({ Kind => 'MAINPAGEONLY',
819 Message => $r->_gt('Entering via cross-site link.'),
820 CookieSecret => $cooks,
822 # NB caller must then ignore params & path!
823 # if this is too hard they can spit out a small form
824 # with a "click to continue"
828 die unless $cookt eq 'y';
829 unless ($r->{S}{promise_check_mutate} && $meth eq 'GET') {
830 die unless $parmt eq 'y';
831 die unless $cookh eq $parmh;
833 $r->{AssocSecret} = $cooks;
834 $r->{UserOK} = $cooku;
835 #print STDERR "C-D-C OK\n";
839 sub chain_params ($) {
841 my %p = %{ $r->_ch('get_params') };
842 foreach my $pncn (keys %{ $r->{S} }) {
844 if ($pncn =~ m/_param_name$/) {
845 my $name = $r->{S}{$pncn};
846 die "$pncn ?" if ref $name;
848 } elsif ($pncn =~ m/_param_names$/) {
849 $names = $r->{S}{$pncn};
853 foreach my $name (@$names) {
857 my $dummy_prefix = $r->{S}{dummy_param_name_prefix};
858 foreach my $name (grep /^$dummy_prefix/, keys %p) {
861 die if exists $p{''};
862 $p{''} = [ $r->_ch('get_path_info') ];
868 # returns ($t,$username)
869 # where $t is one of "t" "y" "n", or "" (for -)
870 # either $s must be undef, or $h eq $r->hash($s)
872 #print STDERR "_identify\n";
873 return '' unless defined $h && length $h;
874 #print STDERR "_identify h=$h s=".(defined $s ? $s : '<undef>')."\n";
878 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
879 " WHERE last < ?", {},
880 time - $r->{S}{login_timeout});
882 my $row = $dbh->selectrow_arrayref("SELECT username, last".
883 " FROM $r->{S}{assocdb_table}".
884 " WHERE assochash = ?", {}, $h);
886 #print STDERR "_identify h=$h s=$s YES @$row\n";
887 my ($nusername, $nlast) = @$row;
888 return ('y', $nusername);
891 # Well, it's not in the database. But maybe it's a hash of a
894 return 'n' unless defined $s;
896 my ($keyt, $signature, $message, $noncet, $nonce) =
897 $s =~ m/^(\d+)\.(\w+)\.((\d+)\.(\w+))$/ or die;
899 return 'n' if time > $noncet + $r->{S}{login_form_timeout};
901 #print STDERR "_identify noncet=$noncet ok\n";
903 my $keys = $r->_open_keys();
904 while (my ($rkeyt, $rkey, $line) = $r->_read_key($keys)) {
905 #print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey\n";
906 last if $rkeyt < $keyt; # too far down in the file
907 my $trysignature = $r->_hmac($rkey, $message);
908 #print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey try=$trysignature\n";
909 return 't' if $trysignature eq $signature;
912 #print STDERR "_identify NO\n";
914 $keys->error and die $!;
918 sub _db_revoke ($$) {
919 # revokes $h if it's valid; no-op if it's not
924 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
925 " WHERE assochash = ?", {}, $h);
928 sub _db_record_login_ok ($$$) {
929 my ($r,$h,$user) = @_;
932 $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
933 " (assochash, username, last) VALUES (?,?,?)", {},
937 sub check_divert ($) {
939 if (exists $r->{Divert}) {
943 $r->{Divert} = $r->_db_transaction(sub { $r->_check_divert_core(); });
945 $r->_debug(Data::Dumper->Dump([$r->{Divert}],[qw(divert)]));
951 die "unchecked" unless exists $r->{Divert};
955 sub get_username ($) {
957 my $divert = $r->get_divert();
958 return undef if $divert;
962 sub url_with_query_params ($$) {
963 my ($r, $params) = @_;
964 #print STDERR "PARAMS ",Dumper($params);
965 my $uri = URI->new($r->_ch('get_url'));
966 $uri->path($uri->path() . $params->{''}[0]) if $params->{''};
967 $uri->query_form(flatten_params($params));
968 return $uri->as_string();
971 sub _cgi_header_args ($$@) {
972 my ($r, $cookie, @ha) = @_;
973 unshift @ha, qw(-type text/html);
974 push @ha, (-cookie => $cookie) if defined $cookie;
975 #print STDERR "_cgi_header_args ",join('|',@ha),".\n";
982 my ($divert) = $r->check_divert();
983 return 1 if !$divert;
985 my $handled = $r->_ch('handle_divert',$divert);
986 return 0 if $handled;
988 my $kind = $divert->{Kind};
989 my $cookiesecret = $divert->{CookieSecret};
990 my $params = $divert->{Params};
991 my $cookie = $r->construct_cookie($cookiesecret);
993 if ($kind =~ m/^SRCDUMP-(\w+)$/) {
994 $r->_ch('srcdump_dump', (lc $1));
998 if ($kind =~ m/^REDIRECT-/) {
999 # for redirects, we honour stored NextParams and SetCookie,
1000 # as we would for non-divert
1001 if ($kind eq 'REDIRECT-LOGGEDOUT') {
1002 $params->{$r->{S}{loggedout_param_names}[0]} = [ 1 ];
1003 } elsif ($kind eq 'REDIRECT-LOGOUT') {
1004 $params->{$r->{S}{logout_param_names}[0]} = [ 1 ];
1005 } elsif ($kind =~ m/REDIRECT-(?:LOGGEDIN|HTTPS)/) {
1009 my $new_url = $r->url_with_query_params($params);
1010 if ($kind eq 'REDIRECT-HTTPS') {
1011 my $uri = URI->new($new_url);
1012 die unless $uri->scheme eq 'http';
1013 $uri->scheme('https');
1014 $new_url = $uri->as_string();
1016 $r->_ch('do_redirect',$new_url, $cookie);
1020 if (defined $cookiesecret) {
1021 $params->{$r->{S}{assoc_param_name}} = [ $r->hash($cookiesecret) ];
1025 if ($kind =~ m/^LOGIN-/) {
1026 $title = $r->_gt('Login');
1027 push @body, $divert->{Message};
1028 push @body, $r->_ch('gen_login_form', $params);
1029 } elsif ($kind =~ m/^SMALLPAGE-/) {
1030 $title = $r->_gt('Not logged in');
1031 push @body, $divert->{Message};
1032 push @body, $r->_ch('gen_login_link', $params);
1033 } elsif ($kind =~ m/^MAINPAGEONLY$/) {
1034 $title = $r->_gt('Entering secure site.');
1035 push @body, $divert->{Message};
1036 push @body, $r->_ch('gen_postmainpage_form', $params);
1041 $r->_print($r->{Cgi}->header($r->_cgi_header_args($cookie)),
1042 $r->_ch('gen_start_html',$title),
1044 $r->_ch('gen_footer_html'),
1045 $r->_ch('gen_end_html'))));
1050 my ($r, $bytes) = @_;
1052 my $rsf = $v->{RandomHandle};
1053 my $rsp = $r->{S}{random_source};
1055 $v->{RandomHandle} = $rsf = new IO::File $rsp, '<' or die "$rsp $!";
1056 #print STDERR "RH $rsf\n";
1060 read($rsf,$bin,$bytes) == $bytes or die "$rsp $!";
1061 my $out = unpack "H*", $bin;
1062 #print STDERR "_random out $out\n";
1066 sub _random_key ($) {
1068 #print STDERR "_random_key\n";
1069 my $bytes = ($r->{S}{secretbits} + 7) >> 3;
1070 return $r->_random($bytes);
1073 sub _read_key ($$) {
1074 my ($r, $keys) = @_;
1075 # returns $gen_time_t, $key_value_in_hex, $complete_line
1077 my ($gen, $k) = m/^(\d+) (\S+)$/ or die "$_ ?";
1078 my $age = time - $gen;
1079 next if $age > $r->{S}{key_rollover} &&
1080 $age > $r->{S}{login_form_timeout}*2;
1081 return ($gen, $k, $_);
1086 sub _open_keys ($) {
1088 my $spath = $r->_get_path('keys');
1090 #print STDERR "_open_keys\n";
1091 my $keys = new IO::File $spath, 'r+';
1093 #print STDERR "_open_keys open\n";
1094 stat $keys or die $!; # NB must not disturb stat _
1095 my $size = (stat _)[7];
1096 my $age = time - (stat _)[9];
1097 #print STDERR "_open_keys open size=$size age=$age\n";
1099 if $size && $age <= $r->{S}{key_rollover} / 2;
1100 #print STDERR "_open_keys open bad\n";
1102 # file doesn't exist, or is empty or too old
1104 #print STDERR "_open_keys closed\n";
1105 die "$spath $!" unless $!==&ENOENT;
1106 # doesn't exist, so create it just so we can lock it
1107 $keys = new IO::File $spath, 'a+';
1108 die "$keys $!" unless $keys;
1109 stat $keys or die $!; # NB must not disturb stat _
1110 my $size = (stat _)[7];
1111 #print STDERR "_open_keys created size=$size\n";
1112 next if $size; # oh someone else has done it, reopen and read it
1114 # file now exists is empty or too old, we must try to replace it
1115 my $our_inum = (stat _)[1]; # last use of that stat _
1116 flock $keys, LOCK_EX or die "$spath $!";
1117 stat $spath or die "$spath $!";
1118 my $path_inum = (stat _)[1];
1119 #print STDERR "_open_keys locked our=$our_inum path=$path_inum\n";
1120 next if $our_inum != $path_inum; # someone else has done it
1121 # We now hold the lock!
1122 #print STDERR "_open_keys creating\n";
1123 my $newkeys = new IO::Handle;
1124 sysopen $newkeys, "$spath.new", O_CREAT|O_TRUNC|O_WRONLY, 0600
1125 or die "$spath.new $!";
1126 # we add the new key to the front which means it's always sorted
1127 print $newkeys time, ' ', $r->_random_key(), "\n" or die $!;
1128 while (my ($gen,$key,$line) = $r->_read_key($keys)) {
1129 #print STDERR "_open_keys copy1\n";
1130 print $newkeys, $line or die $!;
1132 $keys->error and die $!;
1133 close $newkeys or die "$spath.new $!";
1134 rename "$spath.new", "$spath" or die "$spath: $!";
1135 #print STDERR "_open_keys installed\n";
1136 # that rename effective unlocks, since it makes the name refer
1137 # to the new file which we haven't locked
1138 # we go round again opening the file at the beginning
1139 # so that our caller gets a fresh handle onto the existing key file
1143 sub _fresh_secret ($) {
1145 #print STDERR "_fresh_secret\n";
1147 my $keys = $r->_open_keys();
1148 my ($keyt, $key) = $r->_read_key($keys);
1149 die unless defined $keyt;
1151 my $nonce = $r->_random_key();
1153 my $message = "$noncet.$nonce";
1155 my $signature = $r->_hmac($key, $message);
1156 my $secret = "$keyt.$signature.$message";
1157 #print STDERR "FRESH $secret\n";
1162 my ($r, $keyhex, $message) = @_;
1163 my $keybin = pack "H*", $keyhex;
1164 my $alg = $r->{S}{hash_algorithm};
1165 #print STDERR "hmac $alg\n";
1166 my $base = new Digest $alg;
1167 #print STDERR "hmac $alg $base\n";
1168 my $digest = new Digest::HMAC $keybin, $base;
1169 #print STDERR "hmac $alg $base $digest\n";
1170 $digest->add($message);
1171 return $digest->hexdigest();
1175 my ($r, $message) = @_;
1176 my $alg = $r->{S}{hash_algorithm};
1177 #print STDERR "hash $alg\n";
1178 my $digest = new Digest $alg;
1179 $digest->add($message);
1180 return $digest->hexdigest();
1183 sub _assert_checked ($) {
1185 die "unchecked" unless exists $r->{Divert};
1190 my $meth = $r->_ch('get_method');
1191 return $meth eq 'POST';
1194 sub _must_be_post ($) {
1196 my $meth = $r->_ch('get_method');
1197 die "mutating non-POST" if $meth ne 'POST';
1200 sub check_mutate ($) {
1202 $r->_assert_checked();
1203 die if $r->{Divert};
1204 $r->_must_be_post();
1209 $r->_assert_checked();
1210 die if $r->{Divert};
1211 return $r->_is_post();
1214 #---------- output ----------
1216 sub secret_cookie_val ($) {
1218 $r->_assert_checked();
1219 return defined $r->{AssocSecret} ? $r->{AssocSecret} : '';
1222 sub secret_hidden_val ($) {
1224 $r->_assert_checked();
1225 return defined $r->{AssocSecret} ? $r->hash($r->{AssocSecret}) : '';
1228 sub secret_hidden_html ($) {
1230 return $r->{Cgi}->hidden(-name => $r->{S}{assoc_param_name},
1231 -default => $r->secret_hidden_val());
1234 sub secret_cookie ($) {
1236 my $secret = $r->secret_cookie_val();
1237 return undef if !defined $secret;
1238 #print STDERR "SC\n";
1239 my $cookv = $r->construct_cookie($secret);
1240 #print STDERR "SC=$cookv\n";
1250 CGI::Auth::Flexible - web authentication optionally using cookies
1254 my $verifier = CGI::Auth::Flexible->new_verifier(setting => value,...);
1255 my $authreq = $verifier->new_request($cgi_request_object);
1257 my $authreq = CGI::Auth::Flexible->new_request($cgi_request_object,
1258 setting => value,...);
1260 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
1262 $authreq->check_ok() or return;
1265 $authreq->check_mutate();
1268 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
1270 my $divert_kind = $authreq->check_divert();
1272 if ($divert_kind eq 'LOGGEDOUT') {
1273 print "goodbye you are now logged out" and quit
1274 } elsif ($divert_kind eq 'NOCOOKIES') {
1275 print "you need cookies" and quit
1281 $authreq->check_mutate();