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 $?;
296 sub srcdump_dirscan_prepare ($$) {
298 my $dumpdir = $v->_get_path('srcdump');
299 mkdir $dumpdir or $!==&EEXIST or die "mkdir $dumpdir $!";
300 my $lockf = new IO::File "$dumpdir/generate.lock", 'w+'
301 or die "$dumpdir/generate.lock $!";
302 flock $lockf, LOCK_EX or die "$dumpdir/generate.lock $!";
303 my $needlicence = "$dumpdir/licence.tmp";
304 unlink $needlicence or $!==&ENOENT or die "rm $needlicence $!";
305 if (defined $v->{S}{srcdump_licence_path}) {
306 copy($v->{S}{srcdump_licence_path}, $needlicence)
307 or die "$v->{S}{srcdump_licence_path} $!";
308 $needlicence = undef;
310 my $srctarballcounter = 'aaa';
312 my @srcfiles = ("$dumpdir/licence.data");
313 foreach my $incdir ($v->_ch('srcdump_includedirs')) {
314 if (defined $needlicence) {
315 foreach my $try (@{ $v->{S}{srcdump_licence_files} }) {
316 last if copy("$incdir/$try", $needlicence);
317 $!==&ENOENT or die "copy $incdir/$try $!";
320 push @srcfiles, $v->_ch('srcdump_process_dir', $dumpdir, $incdir,
321 \$srctarballcounter, \$needlicence, \%dirsdone);
322 $dirsdone{$incdir}++;
324 die "licence file not found" unless defined $needlicence;
325 srcdump_install($c,$v, $dumpdir, 'licence', 'text/plain');
326 close $lockf or die $!;
329 sub srcdump_install ($$$$$) {
330 my ($c,$v, $dumpdir, $which, $ctype) = @_;
331 rename "$dumpdir/$which.tmp", "$dumpdir/$which.data"
332 or die "$dumpdir/$which.data $!";
333 my $ctf = new IO::File "$dumpdir/$which.tmp", 'w'
334 or die "$dumpdir/$which.tmp $!";
335 print $ctf $ctype, "\n" or die $!;
336 close $ctf or die $!;
337 rename "$dumpdir/$which.tmp", "$dumpdir/$which.ctype"
338 or die "$dumpdir/$which.ctype $!";
341 #---------- verifier object methods ----------
348 assocdb_dbh => undef, # must have AutoCommit=0, RaiseError=1
349 assocdb_path => 'caf-assocs.db',
350 keys_path => 'caf-keys',
351 srcdump_path => 'caf-srcdump',
352 assocdb_dsn => undef,
354 assocdb_password => '',
355 assocdb_table => 'caf_assocs',
356 random_source => '/dev/urandom',
357 secretbits => 128, # bits
358 hash_algorithm => "SHA-256",
359 login_timeout => 86400, # seconds
360 login_form_timeout => 3600, # seconds
361 key_rollover => 86400, # seconds
362 assoc_param_name => 'caf_assochash',
363 dummy_param_name_prefix => 'caf__',
364 cookie_name => "caf_assocsecret",
365 password_param_name => 'password',
366 srcdump_param_name => 'caf_srcdump',
367 username_param_names => [qw(username)],
368 form_entry_size => 60,
369 logout_param_names => [qw(caf_logout)],
370 loggedout_param_names => [qw(caf_loggedout)],
371 promise_check_mutate => 0,
372 get_param => sub { $_[0]->param($_[2]) },
373 get_params => sub { $_[1]->get_params() },
374 get_path_info => sub { $_[0]->path_info() },
375 get_cookie => sub { $_[0]->cookie($_[1]->{S}{cookie_name}) },
376 get_method => sub { $_[0]->request_method() },
377 check_https => sub { !!$_[0]->https() },
378 get_url => sub { $_[0]->url(); },
379 is_login => sub { defined $_[1]->_rp('password_param_name') },
380 login_ok => \&login_ok_password,
381 username_password_error => sub { die },
382 is_logout => sub { $_[1]->has_a_param('logout_param_names') },
383 is_loggedout => sub { $_[1]->has_a_param('loggedout_param_names') },
384 is_page => sub { return 1 },
385 handle_divert => sub { return 0 },
386 do_redirect => \&do_redirect_cgi, # this hook is allowed to throw
388 get_cookie_domain => \&get_cookie_domain,
390 gen_start_html => sub { $_[0]->start_html($_[2]); },
391 gen_footer_html => \&gen_plain_footer_html,
392 gen_licence_link_html => \&gen_plain_licence_link_html,
393 gen_source_link_html => \&gen_plain_source_link_html,
394 gen_end_html => sub { $_[0]->end_html(); },
395 gen_login_form => \&gen_plain_login_form,
396 gen_login_link => \&gen_plain_login_link,
397 gen_postmainpage_form => \&gen_postmainpage_form,
398 srcdump_dump => \&srcdump_dump,
399 srcdump_prepare => \&srcdump_dirscan_prepare,
400 srcdump_licence_path => undef,
401 srcdump_licence_files => [qw(AGPLv3 CGI/Auth/Flexible/AGPLv3)],
402 srcdump_includedirs => sub { return @INC; },
403 srcdump_system_dir => sub { $_[2] =~ m#^/etc/|^/usr/(?!local/)#; },
404 srcdump_process_dir => \&srcdump_process_dir,
405 srcdump_vcs_dirs => [qw(.git .hg .svn CVS)],
406 srcdump_byvcs_git => \&srcdump_byvcs_git,
407 srcdump_byvcs_hg => \&srcdump_byvcs_hg,
408 srcdump_byvcs_svn => \&srcdump_byvcs_svn,
409 srcdump_byvcs_cvs => \&srcdump_byvcs_cvs,
410 srcdump_novcs => \&srcdump_novcs,
411 srcdump_excludes => [qw(*~ *.bak *.tmp), '#*#'],
412 dump => \&dump_plain,
413 gettext => sub { gettext($_[2]); },
414 print => sub { print $_[2] or die $!; },
415 debug => sub { }, # like print; msgs contain trailing \n
420 while (($k,$v,@_) = @_) {
421 die "unknown setting $k" unless exists $verifier->{S}{$k};
422 $verifier->{S}{$k} = $v;
424 bless $verifier, $class;
425 $verifier->_dbopen();
426 $verifier->_ch('srcdump_prepare');
430 sub _db_setup_do ($$) {
434 $v->_db_transaction(sub {
435 local ($dbh->{PrintError}) = 0;
446 $dbh = $v->{S}{assocdb_dbh};
448 die if $dbh->{AutoCommit};
449 die unless $dbh->{RaiseError};
451 $v->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=".$v->_get_path('assocdb');
452 my $dsn = $v->{S}{assocdb_dsn};
455 $dbh = DBI->connect($dsn, $v->{S}{assocdb_user},
456 $v->{S}{assocdb_password}, {
459 ShowErrorStatement => 1,
462 die "$dsn $! ?" unless $dbh;
466 $v->_db_setup_do("CREATE TABLE $v->{S}{assocdb_table} (".
467 " assochash VARCHAR PRIMARY KEY,".
468 " username VARCHAR NOT NULL,".
469 " last INTEGER NOT NULL".
471 $v->_db_setup_do("CREATE INDEX $v->{S}{assocdb_table}_timeout_index".
472 " ON $v->{S}{assocdb_table}".
484 sub _db_transaction ($$) {
489 #print STDERR "DT entry\n";
491 #print STDERR "DT loop\n";
494 #print STDERR "DT fn ok\n";
497 #print STDERR "DT fn error\n";
498 { local ($@); $dbh->rollback(); }
499 #print STDERR "DT fn throwing\n";
502 #print STDERR "DT fn eval ok\n";
505 #print STDERR "DT commit ok\n";
508 #print STDERR "DT commit eval ok ",Dumper($rv);
511 #print STDERR "DT commit throw?\n";
512 die $@ if !--$retries;
513 #print STDERR "DT loop again\n";
517 #---------- request object methods ----------
520 my ($classbase, $cgi, @extra) = @_;
521 if (!ref $classbase) {
522 $classbase = $classbase->new_verifier(@extra);
528 S => $classbase->{S},
529 Dbh => $classbase->{Dbh},
532 bless $r, ref $classbase;
535 sub _ch ($$@) { # calls an application hook
536 my ($r,$methname, @args) = @_;
537 my $methfunc = $r->{S}{$methname};
538 die "$methname ?" unless $methfunc;
539 return $methfunc->($r->{Cgi}, $r, @args);
544 my $pn = $r->{S}{$pnvb};
545 my $p = scalar $r->_ch('get_param',$pn)
550 $r->_ch('debug',@args);
554 my ($r,$keybase) = @_;
555 my $leaf = $r->{S}{"${keybase}_path"};
556 return $r->_absify_path($leaf);
559 sub _absify_path ($$) {
561 return $leaf if $leaf =~ m,^/,;
562 my $dir = $v->{S}{dir};
563 die "relying on cwd by default ?! set dir" unless defined $dir;
567 sub _gt ($$) { my ($r, $t) = @_; return $r->_ch('gettext',$t); }
568 sub _print ($$) { my ($r, @t) = @_; return $r->_ch('print', join '', @t); }
570 sub construct_cookie ($$$) {
571 my ($r, $cooks) = @_;
572 return undef unless $cooks;
574 my @ca = (-name => $r->{S}{cookie_name},
576 -path => $r->{S}{cookie_path},
577 -domain => $r->_ch('get_cookie_domain'),
578 -expires => '+'.$r->{S}{login_timeout}.'s',
579 -secure => $r->{S}{encrypted_only});
580 my $cookie = $c->cookie(@ca);
581 #print STDERR "CC $r $c $cooks $cookie (@ca).\n";
585 # pages/param-sets are
586 # n normal non-mutating page
587 # r retrieval of information for JS, non-mutating
589 # u update of information by JS, mutating
592 # O "you have just logged out" page load
595 # - no value supplied (represented in code as $cookt='')
596 # n, nN value not in our db
597 # t, tN temporary value (in our db, no logged in user yet)
598 # y, yN value corresponds to logged-in user
599 # and, aggregated conditions:
600 # a, aN anything including -
602 # if N differs the case applies only when the two values differ
603 # (eg, a1 y2 does not apply when the logged-in value is supplied twice)
605 # "stale session" means request originates from a page from a login
606 # session which has been revoked (eg by logout); "cleared session"
607 # means request originates from a browser which has a different (or
610 # Case analysis, cookie mode, app promises re mutate:
611 # cook parm meth form
613 # any - POST nrmuoi bug or attack, fail
614 # any - GET rmuoi bug or attack, fail
615 # any any GET muoi bug or attack, fail
616 # any t any nrmu bug or attack, fail
618 # - - GET O "just logged out" page
619 # (any other) O bug or attack, fail
621 # a1 a2 POST o logout
622 # if a1 is valid, revoke it
623 # if a2 is valid, revoke it
625 # redirect to "just logged out" page
626 # (which contains link to login form)
628 # - t POST i complain about cookies being disabled
629 # (with link to login form)
631 # t1 t1 POST i login (or switch user)
633 # show new login form
635 # upgrade t1 to y1 in our db (setting username)
636 # redirect to GET of remaining params
638 # y1 a2 POST i complain about stale login form
640 # show new login form
642 # (other) POST i complain about stale login form
643 # show new login form
645 # t1 a2 ANY nrmu treat as - a2 ANY
647 # y - GET n cross-site link
650 # y y GET nr fine, show page or send data
651 # y y POST nrmu mutation is OK, do operation
653 # y1 y2 GET nr request from stale page
654 # do not revoke y2 as not RESTful
657 # y1 y2 POST nrmu request from stale page
661 # y n GET n intra-site link from stale page,
662 # treat as cross-site link, show data
664 # y n POST n m intra-site form submission from stale page
665 # show "session interrupted"
666 # with link to main data page
668 # y n GET r intra-site request from stale page
671 # y n POST r u intra-site request from stale page
674 # -/n y2 GET nr intra-site link from cleared session
675 # do not revoke y2 as not RESTful
678 # -/n y2 POST nrmu request from cleared session
680 # treat as -/n n POST
682 # -/n -/n GET n cross-site link but user not logged in
683 # show login form with redirect to orig params
684 # generate fresh cookie
686 # -/n n GET rmu user not logged in
689 # -/n n POST n m user not logged in
692 # -/n n POST r u user not logged in
695 sub _check_divert_core ($) {
698 my $srcdump = $r->_rp('srcdump_param_name');
700 die if $srcdump =~ m/\W/;
701 return ({ Kind => 'SRCDUMP-'.uc $srcdump,
703 CookieSecret => undef,
707 my $cooks = $r->_ch('get_cookie');
709 if ($r->{S}{encrypted_only} && !$r->_ch('check_https')) {
710 return ({ Kind => 'REDIRECT-HTTPS',
711 Message => $r->_gt("Redirecting to secure server..."),
712 CookieSecret => undef,
716 my $meth = $r->_ch('get_method');
717 my $parmh = $r->_rp('assoc_param_name');
718 my $cookh = defined $cooks ? $r->hash($cooks) : undef;
720 my ($cookt,$cooku) = $r->_identify($cookh, $cooks);
721 my $parms = (defined $cooks && defined $parmh && $parmh eq $cookh)
723 my ($parmt) = $r->_identify($parmh, $parms);
725 $r->_debug("_c_d_c cookt=$cookt parmt=$parmt\n");
727 if ($r->_ch('is_logout')) {
730 $r->_db_revoke($cookh);
731 $r->_db_revoke($parmh);
732 return ({ Kind => 'REDIRECT-LOGGEDOUT',
733 Message => $r->_gt("Logging out..."),
737 if ($r->_ch('is_loggedout')) {
738 die unless $meth eq 'GET';
739 die if $cookt eq 'y';
741 return ({ Kind => 'SMALLPAGE-LOGGEDOUT',
742 Message => $r->_gt("You have been logged out."),
746 if ($r->_ch('is_login')) {
749 if (!$cookt && $parmt eq 'n') {
750 return ({ Kind => 'SMALLPAGE-NOCOOKIE',
751 Message => $r->_gt("You do not seem to have cookies".
752 " enabled. You must enable cookies".
753 " as we use them for login."),
754 CookieSecret => $r->_fresh_secret(),
755 Params => $r->chain_params() })
757 if (!$cookt || $cookt eq 'n' || $cookh ne $parmh) {
758 $r->_db_revoke($cookh);
759 return ({ Kind => 'LOGIN-STALE',
760 Message => $r->_gt("Stale session;".
761 " you need to log in again."),
762 CookieSecret => $r->_fresh_secret(),
765 die unless $parmt eq 't' || $parmt eq 'y';
766 my ($username, $login_errormessage) = $r->_ch('login_ok');
767 unless (defined $username && length $username) {
768 $login_errormessage = $r->_gt("Incorrect username/password.")
769 if !$login_errormessage;
770 return ({ Kind => 'LOGIN-BAD',
771 Message => $login_errormessage,
772 CookieSecret => $cooks,
773 Params => $r->chain_params() })
775 $r->_db_record_login_ok($parmh,$username);
776 return ({ Kind => 'REDIRECT-LOGGEDIN',
777 Message => $r->_gt("Logging in..."),
778 CookieSecret => $cooks,
779 Params => $r->chain_params() });
784 die if $parmt eq 't';
786 if ($cookt eq 'y' && $parmt eq 'y' && $cookh ne $parmh) {
787 $r->_db_revoke($parmh) if $meth eq 'POST';
792 die unless !$cookt || $cookt eq 'n';
793 die unless !$parmt || $parmt eq 'n' || $parmt eq 'y';
794 my $news = $r->_fresh_secret();
795 if ($meth eq 'GET') {
796 return ({ Kind => 'LOGIN-INCOMINGLINK',
797 Message => $r->_gt("You need to log in."),
798 CookieSecret => $news,
799 Params => $r->chain_params() });
801 $r->_db_revoke($parmh);
802 return ({ Kind => 'LOGIN-FRESH',
803 Message => $r->_gt("You need to log in."),
804 CookieSecret => $news,
809 if (!$r->{S}{promise_check_mutate}) {
810 if ($meth ne 'POST') {
811 return ({ Kind => 'MAINPAGEONLY',
812 Message => $r->_gt('Entering via cross-site link.'),
813 CookieSecret => $cooks,
815 # NB caller must then ignore params & path!
816 # if this is too hard they can spit out a small form
817 # with a "click to continue"
821 die unless $cookt eq 'y';
822 unless ($r->{S}{promise_check_mutate} && $meth eq 'GET') {
823 die unless $parmt eq 'y';
824 die unless $cookh eq $parmh;
826 $r->{AssocSecret} = $cooks;
827 $r->{UserOK} = $cooku;
828 #print STDERR "C-D-C OK\n";
832 sub chain_params ($) {
834 my %p = %{ $r->_ch('get_params') };
835 foreach my $pncn (keys %{ $r->{S} }) {
837 if ($pncn =~ m/_param_name$/) {
838 my $name = $r->{S}{$pncn};
839 die "$pncn ?" if ref $name;
841 } elsif ($pncn =~ m/_param_names$/) {
842 $names = $r->{S}{$pncn};
846 foreach my $name (@$names) {
850 my $dummy_prefix = $r->{S}{dummy_param_name_prefix};
851 foreach my $name (grep /^$dummy_prefix/, keys %p) {
854 die if exists $p{''};
855 $p{''} = [ $r->_ch('get_path_info') ];
861 # returns ($t,$username)
862 # where $t is one of "t" "y" "n", or "" (for -)
863 # either $s must be undef, or $h eq $r->hash($s)
865 #print STDERR "_identify\n";
866 return '' unless defined $h && length $h;
867 #print STDERR "_identify h=$h s=".(defined $s ? $s : '<undef>')."\n";
871 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
872 " WHERE last < ?", {},
873 time - $r->{S}{login_timeout});
875 my $row = $dbh->selectrow_arrayref("SELECT username, last".
876 " FROM $r->{S}{assocdb_table}".
877 " WHERE assochash = ?", {}, $h);
879 #print STDERR "_identify h=$h s=$s YES @$row\n";
880 my ($nusername, $nlast) = @$row;
881 return ('y', $nusername);
884 # Well, it's not in the database. But maybe it's a hash of a
887 return 'n' unless defined $s;
889 my ($keyt, $signature, $message, $noncet, $nonce) =
890 $s =~ m/^(\d+)\.(\w+)\.((\d+)\.(\w+))$/ or die;
892 return 'n' if time > $noncet + $r->{S}{login_form_timeout};
894 #print STDERR "_identify noncet=$noncet ok\n";
896 my $keys = $r->_open_keys();
897 while (my ($rkeyt, $rkey, $line) = $r->_read_key($keys)) {
898 #print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey\n";
899 last if $rkeyt < $keyt; # too far down in the file
900 my $trysignature = $r->_hmac($rkey, $message);
901 #print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey try=$trysignature\n";
902 return 't' if $trysignature eq $signature;
905 #print STDERR "_identify NO\n";
907 $keys->error and die $!;
911 sub _db_revoke ($$) {
912 # revokes $h if it's valid; no-op if it's not
917 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
918 " WHERE assochash = ?", {}, $h);
921 sub _db_record_login_ok ($$$) {
922 my ($r,$h,$user) = @_;
925 $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
926 " (assochash, username, last) VALUES (?,?,?)", {},
930 sub check_divert ($) {
932 if (exists $r->{Divert}) {
936 $r->{Divert} = $r->_db_transaction(sub { $r->_check_divert_core(); });
938 $r->_debug(Data::Dumper->Dump([$r->{Divert}],[qw(divert)]));
944 die "unchecked" unless exists $r->{Divert};
948 sub get_username ($) {
950 my $divert = $r->get_divert();
951 return undef if $divert;
955 sub url_with_query_params ($$) {
956 my ($r, $params) = @_;
957 #print STDERR "PARAMS ",Dumper($params);
958 my $uri = URI->new($r->_ch('get_url'));
959 $uri->path($uri->path() . $params->{''}[0]) if $params->{''};
960 $uri->query_form(flatten_params($params));
961 return $uri->as_string();
964 sub _cgi_header_args ($$@) {
965 my ($r, $cookie, @ha) = @_;
966 unshift @ha, qw(-type text/html);
967 push @ha, (-cookie => $cookie) if defined $cookie;
968 #print STDERR "_cgi_header_args ",join('|',@ha),".\n";
975 my ($divert) = $r->check_divert();
976 return 1 if !$divert;
978 my $handled = $r->_ch('handle_divert',$divert);
979 return 0 if $handled;
981 my $kind = $divert->{Kind};
982 my $cookiesecret = $divert->{CookieSecret};
983 my $params = $divert->{Params};
984 my $cookie = $r->construct_cookie($cookiesecret);
986 if ($kind =~ m/^SRCDUMP-(\w+)$/) {
987 $r->_ch('srcdump_dump', (lc $1));
991 if ($kind =~ m/^REDIRECT-/) {
992 # for redirects, we honour stored NextParams and SetCookie,
993 # as we would for non-divert
994 if ($kind eq 'REDIRECT-LOGGEDOUT') {
995 $params->{$r->{S}{loggedout_param_names}[0]} = [ 1 ];
996 } elsif ($kind eq 'REDIRECT-LOGOUT') {
997 $params->{$r->{S}{logout_param_names}[0]} = [ 1 ];
998 } elsif ($kind =~ m/REDIRECT-(?:LOGGEDIN|HTTPS)/) {
1002 my $new_url = $r->url_with_query_params($params);
1003 if ($kind eq 'REDIRECT-HTTPS') {
1004 my $uri = URI->new($new_url);
1005 die unless $uri->scheme eq 'http';
1006 $uri->scheme('https');
1007 $new_url = $uri->as_string();
1009 $r->_ch('do_redirect',$new_url, $cookie);
1013 if (defined $cookiesecret) {
1014 $params->{$r->{S}{assoc_param_name}} = [ $r->hash($cookiesecret) ];
1018 if ($kind =~ m/^LOGIN-/) {
1019 $title = $r->_gt('Login');
1020 push @body, $divert->{Message};
1021 push @body, $r->_ch('gen_login_form', $params);
1022 } elsif ($kind =~ m/^SMALLPAGE-/) {
1023 $title = $r->_gt('Not logged in');
1024 push @body, $divert->{Message};
1025 push @body, $r->_ch('gen_login_link', $params);
1026 } elsif ($kind =~ m/^MAINPAGEONLY$/) {
1027 $title = $r->_gt('Entering secure site.');
1028 push @body, $divert->{Message};
1029 push @body, $r->_ch('gen_postmainpage_form', $params);
1034 $r->_print($r->{Cgi}->header($r->_cgi_header_args($cookie)),
1035 $r->_ch('gen_start_html',$title),
1037 $r->_ch('gen_footer_html'),
1038 $r->_ch('gen_end_html'))));
1043 my ($r, $bytes) = @_;
1045 my $rsf = $v->{RandomHandle};
1046 my $rsp = $r->{S}{random_source};
1048 $v->{RandomHandle} = $rsf = new IO::File $rsp, '<' or die "$rsp $!";
1049 #print STDERR "RH $rsf\n";
1053 read($rsf,$bin,$bytes) == $bytes or die "$rsp $!";
1054 my $out = unpack "H*", $bin;
1055 #print STDERR "_random out $out\n";
1059 sub _random_key ($) {
1061 #print STDERR "_random_key\n";
1062 my $bytes = ($r->{S}{secretbits} + 7) >> 3;
1063 return $r->_random($bytes);
1066 sub _read_key ($$) {
1067 my ($r, $keys) = @_;
1068 # returns $gen_time_t, $key_value_in_hex, $complete_line
1070 my ($gen, $k) = m/^(\d+) (\S+)$/ or die "$_ ?";
1071 my $age = time - $gen;
1072 next if $age > $r->{S}{key_rollover} &&
1073 $age > $r->{S}{login_form_timeout}*2;
1074 return ($gen, $k, $_);
1079 sub _open_keys ($) {
1081 my $spath = $r->_get_path('keys');
1083 #print STDERR "_open_keys\n";
1084 my $keys = new IO::File $spath, 'r+';
1086 #print STDERR "_open_keys open\n";
1087 stat $keys or die $!; # NB must not disturb stat _
1088 my $size = (stat _)[7];
1089 my $age = time - (stat _)[9];
1090 #print STDERR "_open_keys open size=$size age=$age\n";
1092 if $size && $age <= $r->{S}{key_rollover} / 2;
1093 #print STDERR "_open_keys open bad\n";
1095 # file doesn't exist, or is empty or too old
1097 #print STDERR "_open_keys closed\n";
1098 die "$spath $!" unless $!==&ENOENT;
1099 # doesn't exist, so create it just so we can lock it
1100 $keys = new IO::File $spath, 'a+';
1101 die "$keys $!" unless $keys;
1102 stat $keys or die $!; # NB must not disturb stat _
1103 my $size = (stat _)[7];
1104 #print STDERR "_open_keys created size=$size\n";
1105 next if $size; # oh someone else has done it, reopen and read it
1107 # file now exists is empty or too old, we must try to replace it
1108 my $our_inum = (stat _)[1]; # last use of that stat _
1109 flock $keys, LOCK_EX or die "$spath $!";
1110 stat $spath or die "$spath $!";
1111 my $path_inum = (stat _)[1];
1112 #print STDERR "_open_keys locked our=$our_inum path=$path_inum\n";
1113 next if $our_inum != $path_inum; # someone else has done it
1114 # We now hold the lock!
1115 #print STDERR "_open_keys creating\n";
1116 my $newkeys = new IO::Handle;
1117 sysopen $newkeys, "$spath.new", O_CREAT|O_TRUNC|O_WRONLY, 0600
1118 or die "$spath.new $!";
1119 # we add the new key to the front which means it's always sorted
1120 print $newkeys time, ' ', $r->_random_key(), "\n" or die $!;
1121 while (my ($gen,$key,$line) = $r->_read_key($keys)) {
1122 #print STDERR "_open_keys copy1\n";
1123 print $newkeys, $line or die $!;
1125 $keys->error and die $!;
1126 close $newkeys or die "$spath.new $!";
1127 rename "$spath.new", "$spath" or die "$spath: $!";
1128 #print STDERR "_open_keys installed\n";
1129 # that rename effective unlocks, since it makes the name refer
1130 # to the new file which we haven't locked
1131 # we go round again opening the file at the beginning
1132 # so that our caller gets a fresh handle onto the existing key file
1136 sub _fresh_secret ($) {
1138 #print STDERR "_fresh_secret\n";
1140 my $keys = $r->_open_keys();
1141 my ($keyt, $key) = $r->_read_key($keys);
1142 die unless defined $keyt;
1144 my $nonce = $r->_random_key();
1146 my $message = "$noncet.$nonce";
1148 my $signature = $r->_hmac($key, $message);
1149 my $secret = "$keyt.$signature.$message";
1150 #print STDERR "FRESH $secret\n";
1155 my ($r, $keyhex, $message) = @_;
1156 my $keybin = pack "H*", $keyhex;
1157 my $alg = $r->{S}{hash_algorithm};
1158 #print STDERR "hmac $alg\n";
1159 my $base = new Digest $alg;
1160 #print STDERR "hmac $alg $base\n";
1161 my $digest = new Digest::HMAC $keybin, $base;
1162 #print STDERR "hmac $alg $base $digest\n";
1163 $digest->add($message);
1164 return $digest->hexdigest();
1168 my ($r, $message) = @_;
1169 my $alg = $r->{S}{hash_algorithm};
1170 #print STDERR "hash $alg\n";
1171 my $digest = new Digest $alg;
1172 $digest->add($message);
1173 return $digest->hexdigest();
1176 sub _assert_checked ($) {
1178 die "unchecked" unless exists $r->{Divert};
1183 my $meth = $r->_ch('get_method');
1184 return $meth eq 'POST';
1187 sub _must_be_post ($) {
1189 my $meth = $r->_ch('get_method');
1190 die "mutating non-POST" if $meth ne 'POST';
1193 sub check_mutate ($) {
1195 $r->_assert_checked();
1196 die if $r->{Divert};
1197 $r->_must_be_post();
1202 $r->_assert_checked();
1203 die if $r->{Divert};
1204 return $r->_is_post();
1207 #---------- output ----------
1209 sub secret_cookie_val ($) {
1211 $r->_assert_checked();
1212 return defined $r->{AssocSecret} ? $r->{AssocSecret} : '';
1215 sub secret_hidden_val ($) {
1217 $r->_assert_checked();
1218 return defined $r->{AssocSecret} ? $r->hash($r->{AssocSecret}) : '';
1221 sub secret_hidden_html ($) {
1223 return $r->{Cgi}->hidden(-name => $r->{S}{assoc_param_name},
1224 -default => $r->secret_hidden_val());
1227 sub secret_cookie ($) {
1229 my $secret = $r->secret_cookie_val();
1230 return undef if !defined $secret;
1231 #print STDERR "SC\n";
1232 my $cookv = $r->construct_cookie($secret);
1233 #print STDERR "SC=$cookv\n";
1243 CGI::Auth::Flexible - web authentication optionally using cookies
1247 my $verifier = CGI::Auth::Flexible->new_verifier(setting => value,...);
1248 my $authreq = $verifier->new_request($cgi_request_object);
1250 my $authreq = CGI::Auth::Flexible->new_request($cgi_request_object,
1251 setting => value,...);
1253 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
1255 $authreq->check_ok() or return;
1258 $authreq->check_mutate();
1261 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
1263 my $divert_kind = $authreq->check_divert();
1265 if ($divert_kind eq 'LOGGEDOUT') {
1266 print "goodbye you are now logged out" and quit
1267 } elsif ($divert_kind eq 'NOCOOKIES') {
1268 print "you need cookies" and quit
1274 $authreq->check_mutate();