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_thing ($$$) {
204 my ($c,$r, $thing, $outfn) = @_;
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 $ct->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 scrdump_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 my $lockf = new IO::File "$dumpdir/generate.lock", 'w+'
300 or die "$dumpdir/generate.lock $!";
301 flock $lockf, LOCK_EX or die "$dumpdir/generate.lock $!";
302 my $needlicence = "$dumpdir/licence.tmp";
303 unlink $needlicence || $!==&ENOENT or die "rm $needlicence $!";
304 if (defined $v->{S}{srcdump_licence_path}) {
305 copy($v->{S}{srcdump_licence_path}, $needlicence)
306 or die "$v->{S}{srcdump_licence_path} $!";
307 $needlicence = undef;
309 my $srctarballcounter = 'aaa';
311 my @srcfiles = ("$dumpdir/licence.data");
312 foreach my $incdir ($v->_ch('getsource_includedirs')) {
313 if (defined $needlicence) {
314 foreach my $try (@{ $v->{S}{srcdump_licence_files} }) {
315 last if copy("$incdir/$try", $needlicence);
316 $!==&ENOENT or die "copy $incdir/$try $!";
319 push @srcfiles, $v->_ch('srcdump_process_dir', $dumpdir, $incdir,
320 \$srctarballcounter, \$needlicence, \%dirsdone);
321 $dirsdone{$incdir}++;
323 die "licence file not found" unless defined $needlicence;
324 srcdump_install($c,$v, $dumpdir, 'licence', 'text/plain');
325 close $lockf or die $!;
328 sub srcdump_install ($$$$$) {
329 my ($c,$v, $dumpdir, $which, $ctype) = @_;
330 rename "$dumpdir/$which.tmp", "$dumpdir/$which.data"
331 or die "$dumpdir/$which.data $!";
332 my $ctf = new IO::File "$dumpdir/$which.tmp", 'w'
333 or die "$dumpdir/$which.tmp $!";
334 print $ctf $ctype, "\n" or die $!;
335 close $ctf or die $!;
336 rename "$dumpdir/$which.tmp", "$dumpdir/$which.ctype"
337 or die "$dumpdir/$which.ctype $!";
340 #---------- verifier object methods ----------
347 assocdb_dbh => undef, # must have AutoCommit=0, RaiseError=1
348 assocdb_path => 'caf-assocs.db',
349 keys_path => 'caf-keys',
350 srcdump_path => 'caf-srcdump',
351 assocdb_dsn => undef,
353 assocdb_password => '',
354 assocdb_table => 'caf_assocs',
355 random_source => '/dev/urandom',
356 secretbits => 128, # bits
357 hash_algorithm => "SHA-256",
358 login_timeout => 86400, # seconds
359 login_form_timeout => 3600, # seconds
360 key_rollover => 86400, # seconds
361 assoc_param_name => 'caf_assochash',
362 dummy_param_name_prefix => 'caf__',
363 cookie_name => "caf_assocsecret",
364 password_param_name => 'password',
365 srcdump_param_name => 'caf_srcdump',
366 username_param_names => [qw(username)],
367 form_entry_size => 60,
368 logout_param_names => [qw(caf_logout)],
369 loggedout_param_names => [qw(caf_loggedout)],
370 promise_check_mutate => 0,
371 get_param => sub { $_[0]->param($_[2]) },
372 get_params => sub { $_[1]->get_params() },
373 get_path_info => sub { $_[0]->path_info() },
374 get_cookie => sub { $_[0]->cookie($_[1]->{S}{cookie_name}) },
375 get_method => sub { $_[0]->request_method() },
376 check_https => sub { !!$_[0]->https() },
377 get_url => sub { $_[0]->url(); },
378 is_login => sub { defined $_[1]->_rp('password_param_name') },
379 login_ok => \&login_ok_password,
380 username_password_error => sub { die },
381 is_logout => sub { $_[1]->has_a_param('logout_param_names') },
382 is_loggedout => sub { $_[1]->has_a_param('loggedout_param_names') },
383 is_page => sub { return 1 },
384 handle_divert => sub { return 0 },
385 do_redirect => \&do_redirect_cgi, # this hook is allowed to throw
387 get_cookie_domain => \&get_cookie_domain,
389 gen_start_html => sub { $_[0]->start_html($_[2]); },
390 gen_footer_html => \&gen_plain_footer_html,
391 gen_licence_link_html => \&gen_plain_licence_link_html,
392 gen_source_link_html => \&gen_plain_source_link_html,
393 gen_end_html => sub { $_[0]->end_html(); },
394 gen_login_form => \&gen_plain_login_form,
395 gen_login_link => \&gen_plain_login_link,
396 gen_postmainpage_form => \&gen_postmainpage_form,
397 srcdump_dump_thing => \&srcdump_dump_thing,
398 srcdump_prepare => \&srcdump_dirscan_prepare,
399 srcdump_licence_path => undef,
400 srcdump_licence_files => [qw(AGPLv3 CGI/Auth/Flexible/AGPLv3)],
401 srcdump_system_dir => sub { $_[2] =~ m#^/etc/|^/usr/(?!local/)#; },
402 srcdump_vcs_dirs => [qw(.git .hg .svn CVS)],
403 srcdump_byvcs_git => \&srcdump_byvcs_git,
404 srcdump_byvcs_hg => \&srcdump_byvcs_hg,
405 srcdump_byvcs_svn => \&srcdump_byvcs_svn,
406 srcdump_byvcs_cvs => \&srcdump_byvcs_cvs,
407 srcdump_novcs => \&srcdump_novcs,
408 srcdump_excludes => [qw(*~ *.bak *.tmp), '#*#'],
409 gettext => sub { gettext($_[2]); },
410 print => sub { print $_[2] or die $!; },
411 debug => sub { }, # like print; msgs contain trailing \n
416 while (($k,$v,@_) = @_) {
417 die "unknown setting $k" unless exists $verifier->{S}{$k};
418 $verifier->{S}{$k} = $v;
420 bless $verifier, $class;
421 $verifier->_dbopen();
425 sub _db_setup_do ($$) {
429 $v->_db_transaction(sub {
430 local ($dbh->{PrintError}) = 0;
441 $dbh = $v->{S}{assocdb_dbh};
443 die if $dbh->{AutoCommit};
444 die unless $dbh->{RaiseError};
446 $v->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=".$v->_get_path('assocdb');
447 my $dsn = $v->{S}{assocdb_dsn};
450 $dbh = DBI->connect($dsn, $v->{S}{assocdb_user},
451 $v->{S}{assocdb_password}, {
454 ShowErrorStatement => 1,
457 die "$dsn $! ?" unless $dbh;
461 $v->_db_setup_do("CREATE TABLE $v->{S}{assocdb_table} (".
462 " assochash VARCHAR PRIMARY KEY,".
463 " username VARCHAR NOT NULL,".
464 " last INTEGER NOT NULL".
466 $v->_db_setup_do("CREATE INDEX $v->{S}{assocdb_table}_timeout_index".
467 " ON $v->{S}{assocdb_table}".
479 sub _db_transaction ($$) {
484 #print STDERR "DT entry\n";
486 #print STDERR "DT loop\n";
489 #print STDERR "DT fn ok\n";
492 #print STDERR "DT fn error\n";
493 { local ($@); $dbh->rollback(); }
494 #print STDERR "DT fn throwing\n";
497 #print STDERR "DT fn eval ok\n";
500 #print STDERR "DT commit ok\n";
503 #print STDERR "DT commit eval ok ",Dumper($rv);
506 #print STDERR "DT commit throw?\n";
507 die $@ if !--$retries;
508 #print STDERR "DT loop again\n";
512 #---------- request object methods ----------
515 my ($classbase, $cgi, @extra) = @_;
516 if (!ref $classbase) {
517 $classbase = $classbase->new_verifier(@extra);
523 S => $classbase->{S},
524 Dbh => $classbase->{Dbh},
527 bless $r, ref $classbase;
530 sub _ch ($$@) { # calls an application hook
531 my ($r,$methname, @args) = @_;
532 my $methfunc = $r->{S}{$methname};
533 die "$methname ?" unless $methfunc;
534 return $methfunc->($r->{Cgi}, $r, @args);
539 my $pn = $r->{S}{$pnvb};
540 my $p = scalar $r->_ch('get_param',$pn)
545 $r->_ch('debug',@args);
549 my ($r,$keybase) = @_;
550 my $leaf = $r->{S}{"${keybase}_path"};
551 return $r->_absify_path($leaf);
554 sub _absify_path ($$) {
556 return $leaf if $leaf =~ m,^/,;
557 my $dir = $v->{S}{dir};
558 die "relying on cwd by default ?! set dir" unless defined $dir;
562 sub _gt ($$) { my ($r, $t) = @_; return $r->_ch('gettext',$t); }
563 sub _print ($$) { my ($r, @t) = @_; return $r->_ch('print', join '', @t); }
565 sub construct_cookie ($$$) {
566 my ($r, $cooks) = @_;
567 return undef unless $cooks;
569 my @ca = (-name => $r->{S}{cookie_name},
571 -path => $r->{S}{cookie_path},
572 -domain => $r->_ch('get_cookie_domain'),
573 -expires => '+'.$r->{S}{login_timeout}.'s',
574 -secure => $r->{S}{encrypted_only});
575 my $cookie = $c->cookie(@ca);
576 #print STDERR "CC $r $c $cooks $cookie (@ca).\n";
580 # pages/param-sets are
581 # n normal non-mutating page
582 # r retrieval of information for JS, non-mutating
584 # u update of information by JS, mutating
587 # O "you have just logged out" page load
590 # - no value supplied (represented in code as $cookt='')
591 # n, nN value not in our db
592 # t, tN temporary value (in our db, no logged in user yet)
593 # y, yN value corresponds to logged-in user
594 # and, aggregated conditions:
595 # a, aN anything including -
597 # if N differs the case applies only when the two values differ
598 # (eg, a1 y2 does not apply when the logged-in value is supplied twice)
600 # "stale session" means request originates from a page from a login
601 # session which has been revoked (eg by logout); "cleared session"
602 # means request originates from a browser which has a different (or
605 # Case analysis, cookie mode, app promises re mutate:
606 # cook parm meth form
608 # any - POST nrmuoi bug or attack, fail
609 # any - GET rmuoi bug or attack, fail
610 # any any GET muoi bug or attack, fail
611 # any t any nrmu bug or attack, fail
613 # - - GET O "just logged out" page
614 # (any other) O bug or attack, fail
616 # a1 a2 POST o logout
617 # if a1 is valid, revoke it
618 # if a2 is valid, revoke it
620 # redirect to "just logged out" page
621 # (which contains link to login form)
623 # - t POST i complain about cookies being disabled
624 # (with link to login form)
626 # t1 t1 POST i login (or switch user)
628 # show new login form
630 # upgrade t1 to y1 in our db (setting username)
631 # redirect to GET of remaining params
633 # y1 a2 POST i complain about stale login form
635 # show new login form
637 # (other) POST i complain about stale login form
638 # show new login form
640 # t1 a2 ANY nrmu treat as - a2 ANY
642 # y - GET n cross-site link
645 # y y GET nr fine, show page or send data
646 # y y POST nrmu mutation is OK, do operation
648 # y1 y2 GET nr request from stale page
649 # do not revoke y2 as not RESTful
652 # y1 y2 POST nrmu request from stale page
656 # y n GET n intra-site link from stale page,
657 # treat as cross-site link, show data
659 # y n POST n m intra-site form submission from stale page
660 # show "session interrupted"
661 # with link to main data page
663 # y n GET r intra-site request from stale page
666 # y n POST r u intra-site request from stale page
669 # -/n y2 GET nr intra-site link from cleared session
670 # do not revoke y2 as not RESTful
673 # -/n y2 POST nrmu request from cleared session
675 # treat as -/n n POST
677 # -/n -/n GET n cross-site link but user not logged in
678 # show login form with redirect to orig params
679 # generate fresh cookie
681 # -/n n GET rmu user not logged in
684 # -/n n POST n m user not logged in
687 # -/n n POST r u user not logged in
690 sub _check_divert_core ($) {
693 my $srcdump = $r->_rp('srcdump_param_name');
695 die if $srcdump =~ m/\W/;
696 return ({ Kind => 'SRCDUMP-'.uc $srcdump,
698 CookieSecret => undef,
702 my $cooks = $r->_ch('get_cookie');
704 if ($r->{S}{encrypted_only} && !$r->_ch('check_https')) {
705 return ({ Kind => 'REDIRECT-HTTPS',
706 Message => $r->_gt("Redirecting to secure server..."),
707 CookieSecret => undef,
711 my $meth = $r->_ch('get_method');
712 my $parmh = $r->_rp('assoc_param_name');
713 my $cookh = defined $cooks ? $r->hash($cooks) : undef;
715 my ($cookt,$cooku) = $r->_identify($cookh, $cooks);
716 my $parms = (defined $cooks && defined $parmh && $parmh eq $cookh)
718 my ($parmt) = $r->_identify($parmh, $parms);
720 $r->_debug("_c_d_c cookt=$cookt parmt=$parmt\n");
722 if ($r->_ch('is_logout')) {
725 $r->_db_revoke($cookh);
726 $r->_db_revoke($parmh);
727 return ({ Kind => 'REDIRECT-LOGGEDOUT',
728 Message => $r->_gt("Logging out..."),
732 if ($r->_ch('is_loggedout')) {
733 die unless $meth eq 'GET';
734 die if $cookt eq 'y';
736 return ({ Kind => 'SMALLPAGE-LOGGEDOUT',
737 Message => $r->_gt("You have been logged out."),
741 if ($r->_ch('is_login')) {
744 if (!$cookt && $parmt eq 'n') {
745 return ({ Kind => 'SMALLPAGE-NOCOOKIE',
746 Message => $r->_gt("You do not seem to have cookies".
747 " enabled. You must enable cookies".
748 " as we use them for login."),
749 CookieSecret => $r->_fresh_secret(),
750 Params => $r->chain_params() })
752 if (!$cookt || $cookt eq 'n' || $cookh ne $parmh) {
753 $r->_db_revoke($cookh);
754 return ({ Kind => 'LOGIN-STALE',
755 Message => $r->_gt("Stale session;".
756 " you need to log in again."),
757 CookieSecret => $r->_fresh_secret(),
760 die unless $parmt eq 't' || $parmt eq 'y';
761 my ($username, $login_errormessage) = $r->_ch('login_ok');
762 unless (defined $username && length $username) {
763 $login_errormessage = $r->_gt("Incorrect username/password.")
764 if !$login_errormessage;
765 return ({ Kind => 'LOGIN-BAD',
766 Message => $login_errormessage,
767 CookieSecret => $cooks,
768 Params => $r->chain_params() })
770 $r->_db_record_login_ok($parmh,$username);
771 return ({ Kind => 'REDIRECT-LOGGEDIN',
772 Message => $r->_gt("Logging in..."),
773 CookieSecret => $cooks,
774 Params => $r->chain_params() });
779 die if $parmt eq 't';
781 if ($cookt eq 'y' && $parmt eq 'y' && $cookh ne $parmh) {
782 $r->_db_revoke($parmh) if $meth eq 'POST';
787 die unless !$cookt || $cookt eq 'n';
788 die unless !$parmt || $parmt eq 'n' || $parmt eq 'y';
789 my $news = $r->_fresh_secret();
790 if ($meth eq 'GET') {
791 return ({ Kind => 'LOGIN-INCOMINGLINK',
792 Message => $r->_gt("You need to log in."),
793 CookieSecret => $news,
794 Params => $r->chain_params() });
796 $r->_db_revoke($parmh);
797 return ({ Kind => 'LOGIN-FRESH',
798 Message => $r->_gt("You need to log in."),
799 CookieSecret => $news,
804 if (!$r->{S}{promise_check_mutate}) {
805 if ($meth ne 'POST') {
806 return ({ Kind => 'MAINPAGEONLY',
807 Message => $r->_gt('Entering via cross-site link.'),
808 CookieSecret => $cooks,
810 # NB caller must then ignore params & path!
811 # if this is too hard they can spit out a small form
812 # with a "click to continue"
816 die unless $cookt eq 'y';
817 unless ($r->{S}{promise_check_mutate} && $meth eq 'GET') {
818 die unless $parmt eq 'y';
819 die unless $cookh eq $parmh;
821 $r->{AssocSecret} = $cooks;
822 $r->{UserOK} = $cooku;
823 #print STDERR "C-D-C OK\n";
827 sub chain_params ($) {
829 my %p = %{ $r->_ch('get_params') };
830 foreach my $pncn (keys %{ $r->{S} }) {
832 if ($pncn =~ m/_param_name$/) {
833 my $name = $r->{S}{$pncn};
834 die "$pncn ?" if ref $name;
836 } elsif ($pncn =~ m/_param_names$/) {
837 $names = $r->{S}{$pncn};
841 foreach my $name (@$names) {
845 my $dummy_prefix = $r->{S}{dummy_param_name_prefix};
846 foreach my $name (grep /^$dummy_prefix/, keys %p) {
849 die if exists $p{''};
850 $p{''} = [ $r->_ch('get_path_info') ];
856 # returns ($t,$username)
857 # where $t is one of "t" "y" "n", or "" (for -)
858 # either $s must be undef, or $h eq $r->hash($s)
860 #print STDERR "_identify\n";
861 return '' unless defined $h && length $h;
862 #print STDERR "_identify h=$h s=".(defined $s ? $s : '<undef>')."\n";
866 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
867 " WHERE last < ?", {},
868 time - $r->{S}{login_timeout});
870 my $row = $dbh->selectrow_arrayref("SELECT username, last".
871 " FROM $r->{S}{assocdb_table}".
872 " WHERE assochash = ?", {}, $h);
874 #print STDERR "_identify h=$h s=$s YES @$row\n";
875 my ($nusername, $nlast) = @$row;
876 return ('y', $nusername);
879 # Well, it's not in the database. But maybe it's a hash of a
882 return 'n' unless defined $s;
884 my ($keyt, $signature, $message, $noncet, $nonce) =
885 $s =~ m/^(\d+)\.(\w+)\.((\d+)\.(\w+))$/ or die;
887 return 'n' if time > $noncet + $r->{S}{login_form_timeout};
889 #print STDERR "_identify noncet=$noncet ok\n";
891 my $keys = $r->_open_keys();
892 while (my ($rkeyt, $rkey, $line) = $r->_read_key($keys)) {
893 #print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey\n";
894 last if $rkeyt < $keyt; # too far down in the file
895 my $trysignature = $r->_hmac($rkey, $message);
896 #print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey try=$trysignature\n";
897 return 't' if $trysignature eq $signature;
900 #print STDERR "_identify NO\n";
902 $keys->error and die $!;
906 sub _db_revoke ($$) {
907 # revokes $h if it's valid; no-op if it's not
912 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
913 " WHERE assochash = ?", {}, $h);
916 sub _db_record_login_ok ($$$) {
917 my ($r,$h,$user) = @_;
920 $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
921 " (assochash, username, last) VALUES (?,?,?)", {},
925 sub check_divert ($) {
927 if (exists $r->{Divert}) {
931 $r->{Divert} = $r->_db_transaction(sub { $r->_check_divert_core(); });
933 $r->_debug(Data::Dumper->Dump([$r->{Divert}],[qw(divert)]));
939 die "unchecked" unless exists $r->{Divert};
943 sub get_username ($) {
945 my $divert = $r->get_divert();
946 return undef if $divert;
950 sub url_with_query_params ($$) {
951 my ($r, $params) = @_;
952 #print STDERR "PARAMS ",Dumper($params);
953 my $uri = URI->new($r->_ch('get_url'));
954 $uri->path($uri->path() . $params->{''}[0]) if $params->{''};
955 $uri->query_form(flatten_params($params));
956 return $uri->as_string();
959 sub _cgi_header_args ($$@) {
960 my ($r, $cookie, @ha) = @_;
961 unshift @ha, qw(-type text/html);
962 push @ha, (-cookie => $cookie) if defined $cookie;
963 #print STDERR "_cgi_header_args ",join('|',@ha),".\n";
970 my ($divert) = $r->check_divert();
971 return 1 if !$divert;
973 my $handled = $r->_ch('handle_divert',$divert);
974 return 0 if $handled;
976 my $kind = $divert->{Kind};
977 my $cookiesecret = $divert->{CookieSecret};
978 my $params = $divert->{Params};
979 my $cookie = $r->construct_cookie($cookiesecret);
981 if ($kind =~ m/^SRCDUMP-(\w+)$/) {
982 $r->_ch('srcdump_dump_thing', (lc $1));
986 if ($kind =~ m/^REDIRECT-/) {
987 # for redirects, we honour stored NextParams and SetCookie,
988 # as we would for non-divert
989 if ($kind eq 'REDIRECT-LOGGEDOUT') {
990 $params->{$r->{S}{loggedout_param_names}[0]} = [ 1 ];
991 } elsif ($kind eq 'REDIRECT-LOGOUT') {
992 $params->{$r->{S}{logout_param_names}[0]} = [ 1 ];
993 } elsif ($kind =~ m/REDIRECT-(?:LOGGEDIN|HTTPS)/) {
997 my $new_url = $r->url_with_query_params($params);
998 if ($kind eq 'REDIRECT-HTTPS') {
999 my $uri = URI->new($new_url);
1000 die unless $uri->scheme eq 'http';
1001 $uri->scheme('https');
1002 $new_url = $uri->as_string();
1004 $r->_ch('do_redirect',$new_url, $cookie);
1008 if (defined $cookiesecret) {
1009 $params->{$r->{S}{assoc_param_name}} = [ $r->hash($cookiesecret) ];
1013 if ($kind =~ m/^LOGIN-/) {
1014 $title = $r->_gt('Login');
1015 push @body, $divert->{Message};
1016 push @body, $r->_ch('gen_login_form', $params);
1017 } elsif ($kind =~ m/^SMALLPAGE-/) {
1018 $title = $r->_gt('Not logged in');
1019 push @body, $divert->{Message};
1020 push @body, $r->_ch('gen_login_link', $params);
1021 } elsif ($kind =~ m/^MAINPAGEONLY$/) {
1022 $title = $r->_gt('Entering secure site.');
1023 push @body, $divert->{Message};
1024 push @body, $r->_ch('gen_postmainpage_form', $params);
1029 $r->_print($r->{Cgi}->header($r->_cgi_header_args($cookie)),
1030 $r->_ch('gen_start_html',$title),
1032 $r->_ch('gen_footer_html'),
1033 $r->_ch('gen_end_html'))));
1038 my ($r, $bytes) = @_;
1040 my $rsf = $v->{RandomHandle};
1041 my $rsp = $r->{S}{random_source};
1043 $v->{RandomHandle} = $rsf = new IO::File $rsp, '<' or die "$rsp $!";
1044 #print STDERR "RH $rsf\n";
1048 read($rsf,$bin,$bytes) == $bytes or die "$rsp $!";
1049 my $out = unpack "H*", $bin;
1050 #print STDERR "_random out $out\n";
1054 sub _random_key ($) {
1056 #print STDERR "_random_key\n";
1057 my $bytes = ($r->{S}{secretbits} + 7) >> 3;
1058 return $r->_random($bytes);
1061 sub _read_key ($$) {
1062 my ($r, $keys) = @_;
1063 # returns $gen_time_t, $key_value_in_hex, $complete_line
1065 my ($gen, $k) = m/^(\d+) (\S+)$/ or die "$_ ?";
1066 my $age = time - $gen;
1067 next if $age > $r->{S}{key_rollover} &&
1068 $age > $r->{S}{login_form_timeout}*2;
1069 return ($gen, $k, $_);
1074 sub _open_keys ($) {
1076 my $spath = $r->_get_path('keys');
1078 #print STDERR "_open_keys\n";
1079 my $keys = new IO::File $spath, 'r+';
1081 #print STDERR "_open_keys open\n";
1082 stat $keys or die $!; # NB must not disturb stat _
1083 my $size = (stat _)[7];
1084 my $age = time - (stat _)[9];
1085 #print STDERR "_open_keys open size=$size age=$age\n";
1087 if $size && $age <= $r->{S}{key_rollover} / 2;
1088 #print STDERR "_open_keys open bad\n";
1090 # file doesn't exist, or is empty or too old
1092 #print STDERR "_open_keys closed\n";
1093 die "$spath $!" unless $!==&ENOENT;
1094 # doesn't exist, so create it just so we can lock it
1095 $keys = new IO::File $spath, 'a+';
1096 die "$keys $!" unless $keys;
1097 stat $keys or die $!; # NB must not disturb stat _
1098 my $size = (stat _)[7];
1099 #print STDERR "_open_keys created size=$size\n";
1100 next if $size; # oh someone else has done it, reopen and read it
1102 # file now exists is empty or too old, we must try to replace it
1103 my $our_inum = (stat _)[1]; # last use of that stat _
1104 flock $keys, LOCK_EX or die "$spath $!";
1105 stat $spath or die "$spath $!";
1106 my $path_inum = (stat _)[1];
1107 #print STDERR "_open_keys locked our=$our_inum path=$path_inum\n";
1108 next if $our_inum != $path_inum; # someone else has done it
1109 # We now hold the lock!
1110 #print STDERR "_open_keys creating\n";
1111 my $newkeys = new IO::Handle;
1112 sysopen $newkeys, "$spath.new", O_CREAT|O_TRUNC|O_WRONLY, 0600
1113 or die "$spath.new $!";
1114 # we add the new key to the front which means it's always sorted
1115 print $newkeys time, ' ', $r->_random_key(), "\n" or die $!;
1116 while (my ($gen,$key,$line) = $r->_read_key($keys)) {
1117 #print STDERR "_open_keys copy1\n";
1118 print $newkeys, $line or die $!;
1120 $keys->error and die $!;
1121 close $newkeys or die "$spath.new $!";
1122 rename "$spath.new", "$spath" or die "$spath: $!";
1123 #print STDERR "_open_keys installed\n";
1124 # that rename effective unlocks, since it makes the name refer
1125 # to the new file which we haven't locked
1126 # we go round again opening the file at the beginning
1127 # so that our caller gets a fresh handle onto the existing key file
1131 sub _fresh_secret ($) {
1133 #print STDERR "_fresh_secret\n";
1135 my $keys = $r->_open_keys();
1136 my ($keyt, $key) = $r->_read_key($keys);
1137 die unless defined $keyt;
1139 my $nonce = $r->_random_key();
1141 my $message = "$noncet.$nonce";
1143 my $signature = $r->_hmac($key, $message);
1144 my $secret = "$keyt.$signature.$message";
1145 #print STDERR "FRESH $secret\n";
1150 my ($r, $keyhex, $message) = @_;
1151 my $keybin = pack "H*", $keyhex;
1152 my $alg = $r->{S}{hash_algorithm};
1153 #print STDERR "hmac $alg\n";
1154 my $base = new Digest $alg;
1155 #print STDERR "hmac $alg $base\n";
1156 my $digest = new Digest::HMAC $keybin, $base;
1157 #print STDERR "hmac $alg $base $digest\n";
1158 $digest->add($message);
1159 return $digest->hexdigest();
1163 my ($r, $message) = @_;
1164 my $alg = $r->{S}{hash_algorithm};
1165 #print STDERR "hash $alg\n";
1166 my $digest = new Digest $alg;
1167 $digest->add($message);
1168 return $digest->hexdigest();
1171 sub _assert_checked ($) {
1173 die "unchecked" unless exists $r->{Divert};
1178 my $meth = $r->_ch('get_method');
1179 return $meth eq 'POST';
1182 sub _must_be_post ($) {
1184 my $meth = $r->_ch('get_method');
1185 die "mutating non-POST" if $meth ne 'POST';
1188 sub check_mutate ($) {
1190 $r->_assert_checked();
1191 die if $r->{Divert};
1192 $r->_must_be_post();
1197 $r->_assert_checked();
1198 die if $r->{Divert};
1199 return $r->_is_post();
1202 #---------- output ----------
1204 sub secret_cookie_val ($) {
1206 $r->_assert_checked();
1207 return defined $r->{AssocSecret} ? $r->{AssocSecret} : '';
1210 sub secret_hidden_val ($) {
1212 $r->_assert_checked();
1213 return defined $r->{AssocSecret} ? $r->hash($r->{AssocSecret}) : '';
1216 sub secret_hidden_html ($) {
1218 return $r->{Cgi}->hidden(-name => $r->{S}{assoc_param_name},
1219 -default => $r->secret_hidden_val());
1222 sub secret_cookie ($) {
1224 my $secret = $r->secret_cookie_val();
1225 return undef if !defined $secret;
1226 #print STDERR "SC\n";
1227 my $cookv = $r->construct_cookie($secret);
1228 #print STDERR "SC=$cookv\n";
1238 CGI::Auth::Flexible - web authentication optionally using cookies
1242 my $verifier = CGI::Auth::Flexible->new_verifier(setting => value,...);
1243 my $authreq = $verifier->new_request($cgi_request_object);
1245 my $authreq = CGI::Auth::Flexible->new_request($cgi_request_object,
1246 setting => value,...);
1248 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
1250 $authreq->check_ok() or return;
1253 $authreq->check_mutate();
1256 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
1258 my $divert_kind = $authreq->check_divert();
1260 if ($divert_kind eq 'LOGGEDOUT') {
1261 print "goodbye you are now logged out" and quit
1262 } elsif ($divert_kind eq 'NOCOOKIES') {
1263 print "you need cookies" and quit
1269 $authreq->check_mutate();