3 # This is part of CGI::Auth::Hybrid, 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/>.
23 package CGI::Auth::Hybrid;
28 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
33 %EXPORT_TAGS = ( ); # eg: TAG => [ qw!name1 name2! ],
35 @EXPORT_OK = qw(setup);
44 #---------- public utilities ----------
46 sub flatten_params ($) {
49 foreach my $k (keys %$p) {
50 foreach my $v (@{ $p->{$k} }) {
57 #---------- default callbacks ----------
59 sub has_a_param ($$) {
61 foreach my $pn (@{ $r->{S}{$cn} }) {
62 return 1 if $r->_ch('get_param',$pn);
71 foreach my $name ($c->param()) {
72 $p{$name} = [ $c->param($name) ];
77 sub get_cookie_domain ($$$) {
79 my $uri = new URI $r->_ch('get_url');
83 sub login_ok_password ($$) {
85 my $username_params = $r->{S}{username_param_names};
86 my $username = $r->_ch('get_param',$username_params->[0]);
87 my $password = $r->_rp('password_param_name');
88 return $r->_ch('username_password_ok', $username, $password);
91 sub do_redirect_cgi ($$$$) {
92 my ($c, $r, $new_url, $cookie) = @_;
93 my @ha = ('text/html',
94 -status => '303 See other',
95 -location => $new_url);
96 push @ha, (-cookie => $cookie) if defined $cookie;
97 $r->_print($c->header(@ha),
98 $r->_ch('gen_start_html',$r->_gt('Redirection')),
99 '<a href="'.escapeHTML($new_url).'">',
100 $r->_gt("If you aren't redirected, click to continue."),
102 $c->_ch('gen_end_html'));
105 sub gen_plain_login_form ($$) {
106 my ($c,$r, $params) = @_;
108 push @form, ('<form method="POST" action="'.
109 escapeHTML($r->_ch('get_url')).'>'.
111 my $sz = 'size="'.$r->{S}{form_entry_size}.'"';
112 foreach my $up (@{ $r->{S}{username_param_names}}) {
113 push @form, ('<tr><td>',$r->_gt(ucfirst $up),'</td>',
114 '<td><input type="text" ',$sz.
115 ' name=',$up,'></td></tr>');
117 push @form, ('<tr><td>'.$r->_gt('Password'),'</td>',
118 '<td><input type="password" '.$sz.
119 ' name="'.$r->{S}{password_param_name}.'"></td></tr>');
120 push @form, ('<tr><td colspan="2">',
121 '<input type="submit"'.
122 ' name="'.$r->{S}{login_submit_name}.'"'.
123 ' value="'.$r->_gt('Login').'"></td></tr>',
125 foreach my $n (keys %$params) {
126 push @form, ('<input type="hidden"'.
128 ' value="'.$params->{$n}.'">');
130 push @form, ('</form>');
131 return join "\n", @form;
134 sub gen_login_link ($$) {
135 my ($c,$r, $params) = @_;
136 my $url = $r->url_with_query_params($params);
137 return ('<a href="'.escapeHTML($url).'">'.
138 $r->_gt('Log in again to continue.').
142 #---------- verifier object methods ----------
148 assocdb_path => 'cah-assocs.db',
149 assocdb_dsn => undef,
151 assocdb_password => '',
152 assocdb_table => 'assocs',
153 random_source => '/dev/urandom',
154 associdlen => 128, # bits
155 login_timeout => 86400, # seconds
156 assoc_param_name => 'cah_associd',
157 password_param_name => 'password',
158 username_param_names => [qw(username)],
159 form_entry_size => 60,
160 logout_param_names => [qw(cah_logout)],
161 login_submit_name => [qw(cah_login)],
162 loggedout_param_names => [qw(cah_loggedout)],
163 promise_check_mutate => 0,
164 get_param => sub { $_[0]->param($_[2]) },
165 get_params => sub { $_[1]->get_params() },
166 get_cookie => sub { $_[0]->cookie($_[1]->{S}{cookie_name}) },
167 get_method => sub { $_[0]->request_method() },
168 get_url => sub { $_[0]->url(); },
169 is_login => sub { defined $_[1]->_rp('password_param_name') },
170 login_ok => \&login_ok_password,
171 username_password_ok => sub { die },
172 is_logout => sub { $_[1]->has_a_param('logout_param_names') },
173 is_loggedout => sub { $_[1]->has_a_param('loggedout_param_names') },
174 is_page => sub { return 1 },
175 handle_divert => sub { return 0 },
176 do_redirect => \&do_redirect_cgi, # this hook is allowed to throw
178 get_cookie_domain => \&get_cookie_domain,
180 gen_start_html => sub { $_[0]->start_html($_[2]); },
181 gen_end_html => sub { $_[0]->end_html(); },
182 gen_login_form => \&gen_plain_login_form,
183 gen_login_link => \&gen_plain_login_link,
184 gettext => sub { gettext($_[2]); },
189 while (($k,$v,@_) = @_) {
190 die "unknown setting $k" unless exists $verifier->{S}{$k};
191 $verifier->{S}{$k} = $v;
193 bless $verifier, $class;
194 $verifier->_dbopen();
203 $v->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=$v->{S}{assocdb_path}";
204 my $dsn = $v->{S}{assocdb_dsn};
207 $dbh = DBI->connect($dsn, $v->{S}{assocdb_user},
208 $v->{S}{assocdb_password}, {
211 ShowErrorStatement => 1,
213 die "$dsn $! ?" unless $dbh;
217 $v->_db_transaction(sub {
218 local ($dbh->{PrintError}) = 0;
219 $dbh->do("CREATE TABLE $v->{S}{assocdb_table} (".
220 " associd VARCHAR PRIMARY KEY,".
221 " username VARCHAR,".
222 " last INTEGER NOT NULL".
236 sub _db_transaction ($$) {
241 #print STDERR "DT entry\n";
243 #print STDERR "DT loop\n";
246 #print STDERR "DT fn ok\n";
249 #print STDERR "DT fn error\n";
250 { local ($@); $dbh->rollback(); }
251 #print STDERR "DT fn throwing\n";
254 #print STDERR "DT fn eval ok\n";
257 print STDERR "DT commit ok\n";
260 print STDERR "DT commit eval ok\n";
263 print STDERR "DT commit throw?\n";
264 die $@ if !--$retries;
265 print STDERR "DT loop again\n";
269 #---------- request object methods ----------
272 my ($classbase, $cgi, @extra) = @_;
273 if (!ref $classbase) {
274 $classbase = $classbase->new_verifier(@extra);
280 S => $classbase->{S},
281 Dbh => $classbase->{Dbh},
284 bless $r, ref $classbase;
287 sub _ch ($$@) { # calls an application hook
288 my ($r,$methname, @args) = @_;
289 my $methfunc = $r->{S}{$methname};
290 return $methfunc->($r->{Cgi}, $r, @args);
295 my $pn = $r->{S}{$pnvb};
296 my $p = scalar $r->_ch('get_param',$pn)
299 sub _gt ($$) { my ($r, $t) = @_; return $r->_ch('gettext',$t); }
300 sub _print ($$) { my ($r, @t) = @_; return $r->_ch('print', join '', @t); }
302 sub construct_cookie ($$$) {
303 my ($r, $cookv) = @_;
304 return undef unless $cookv;
306 my $cookt = $c->cookie(-name => $r->{S}{cookie_name},
308 -path => $r->{S}{cookie_path},
309 -domain => $r->_ch('get_cookie_domain'),
310 -expires => '+'.$r->{S}{login_timeout}.'s',
311 -secure => $r->{S}{encrypted_only});
312 print STDERR "CC $r $c $cookv $cookt\n";
316 # pages/param-sets are
317 # n normal non-mutating page
318 # r retrieval of information for JS, non-mutating
320 # u update of information by JS, mutating
323 # O "you have just logged out" page load
326 # a, aN anything including -
327 # t, tN temporary value (in our db, no logged in user yet)
328 # y, yN value corresponds to logged-in user
329 # n, nN value not in our db
331 # - no value supplied
332 # if N differs the case applies only when the two values differ
333 # (eg, a1 y2 does not apply when the logged-in value is supplied twice)
335 # "stale session" means request originates from a page from a login
336 # session which has been revoked (eg by logout); "cleared session"
337 # means request originates from a browser which has a different (or
340 # Case analysis, cookie mode, app promises re mutate:
341 # cook parm meth form
343 # any - POST nrmuoi bug or attack, fail
344 # any - GET rmuoi bug or attack, fail
345 # any any GET muoi bug or attack, fail
346 # any t any nrmu bug or attack, fail
348 # - - GET O "just logged out" page
349 # (any other) O bug or attack, fail
351 # a1 a2 POST o logout
352 # if a1 is valid, revoke it
353 # if a2 is valid, revoke it
355 # redirect to "just logged out" page
356 # (which contains link to login form)
358 # - t POST i complain about cookies being disabled
359 # (with link to login form)
361 # any n POST i complain about stale login form
362 # show new login form
364 # x1 t2 POST i login (or switch user)
366 # show new login form
368 # revoke x1 if it was valid and !=t2
369 # upgrade t2 to y2 in our db (setting username)
371 # redirect to GET of remaining params
373 # t1 a2 ANY nrmu treat as - a2 ANY
375 # y - GET n cross-site link
378 # y y GET nr fine, show page or send data
379 # y y POST nrmu mutation is OK, do operation
381 # y1 y2 GET nr request from stale page
382 # do not revoke y2 as not RESTful
385 # y1 y2 POST nrmu request from stale page
389 # y n GET n intra-site link from stale page,
390 # treat as cross-site link, show data
392 # y n POST n m intra-site form submission from stale page
393 # show "session interrupted"
394 # with link to main data page
396 # y n GET r intra-site request from stale page
399 # y n POST r u intra-site request from stale page
402 # -/n y2 GET nr intra-site link from cleared session
403 # do not revoke y2 as not RESTful
406 # -/n y2 POST nrmu request from cleared session
408 # treat as -/n n POST
410 # -/n n GET n cross-site link but user not logged in
411 # show login form with redirect to orig params
413 # -/n n GET rmu user not logged in
416 # -/n n POST n m user not logged in
419 # -/n n POST r u user not logged in
422 sub _check_divert_core ($) {
425 my $meth = $r->_ch('get_method');
426 my $cookv = $r->_ch('get_cookie');
427 my $parmv = $r->_rp('assoc_param_name');
429 my ($cookt,$cooku) = $r->_db_lookup($cookv);
430 my $parmt = $r->_db_lookup($parmv);
432 if ($r->_ch('is_logout')) {
435 $r->_db_revoke($cookv);
436 $r->_db_revoke($parmv);
437 return ({ Kind => 'REDIRECT-LOGGEDOUT',
438 Message => "Logging out...",
442 if ($r->_ch('is_loggedout')) {
443 die unless $meth eq 'GET';
446 return ({ Kind => 'SMALLPAGE-LOGGEDOUT',
447 Message => "You have been logged out.",
451 if ($r->_ch('is_login')) {
453 return ({ Kind => 'LOGIN-STALE',
454 Message => "Stale session; you need to log in again.",
455 CookieVal => $r->_fresh_cookie(),
458 die unless $parmt eq 't' || $parmt eq 'y';
459 return ({ Kind => 'SMALLPAGE-NOCOOKIE',
460 Message => "You do not seem to have cookies enabled. ".
461 "You must enable cookies as we use them for login.",
462 CookieVal => $r->_fresh_cookie(),
463 Params => $r->_chain_params() })
464 if !$cookt && $parmt eq 't';
465 my $username = $r->_ch('login_ok');
466 return ({ Kind => 'LOGIN-BAD',
467 Message => "Incorrect username/password.",
469 Params => $r->_chain_params() })
470 unless defined $username && length $username;
471 $r->_db_revoke($cookv)
472 if defined $cookv && !(defined $parmv && $cookv eq $parmv);
473 $r->_db_record_login_ok($parmv,$username);
474 return ({ Kind => 'REDIRECT-LOGGEDIN',
475 Message => "Logging in...",
477 Params => $r->_chain_params() });
482 die if $parmt eq 't';
484 if ($cookt eq 'y' && $parmt eq 'y' && $cookv ne $parmv) {
485 $r->_db_revoke($parmv) if $meth eq 'POST';
490 die unless !$cookt || $cookt eq 'n';
491 die unless !$parmt || $parmt eq 'n' || $parmt eq 'y';
492 if ($meth eq 'GET') {
493 return ({ Kind => 'LOGIN-INCOMINGLINK',
494 Message => "You need to log in again.",
496 Params => $r->_chain_params() });
498 return ({ Kind => 'LOGIN-FRESH',
499 Message => "You need to log in again.",
505 if (!$r->{S}{promise_check_mutate}) {
506 if ($meth ne 'POST') {
507 return ({ Kind => 'MAINPAGEONLY',
508 Message => 'Entering via cross-site link.',
511 # NB caller must then ignore params & path!
512 # if this is too hard they can spit out a small form
513 # with a "click to continue"
517 die unless $cookt eq 'y';
518 die unless $parmt eq 'y';
519 die unless $cookv eq $parmv;
520 $r->{Assoc} = $cookv;
521 $r->{UserOK} = $cooku;
525 sub _chain_params ($) {
527 my %p = %{ $r->_ch('get_params') };
528 foreach my $pncn (keys %{ $r->{S} }) {
530 if ($pncn =~ m/_param_name$/) {
531 my $name = $r->{S}{$pncn};
532 die "$pncn ?" if ref $name;
534 } elsif ($pncn =~ m/_param_names$/) {
535 $names = $r->{S}{$pncn};
539 foreach my $name (@$names) {
546 sub _db_lookup ($$) {
548 # returns ($t,$username)
549 # where $t is one of "t" "y" "n", or "" (for -)
553 my $row = $dbh->selectrow_arrayref("SELECT username, last".
554 " FROM $r->{S}{assocdb_table}".
555 " WHERE associd = ?", {}, $v);
556 return ('') unless defined $row;
558 my ($nusername, $nlast) = @$row;
560 my $timeout = $r->{S}{login_timeout};
561 return ('n') unless !defined $timeout || time <= $nlast + $timeout;
563 return ('t') unless defined $nusername;
566 return ('y', $nusername);
569 sub _db_revoke ($$) {
570 # revokes $v if it's valid; no-op if it's not
575 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
576 " WHERE associd = ?", {}, $v);
579 sub _db_record_login_ok ($$$) {
580 my ($r,$v,$user) = @_;
583 $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
584 " (associd, username, last) VALUES (?,?,?)", {},
588 sub check_divert ($) {
591 if (exists $r->{Divert}) {
595 $r->{Divert} = $r->_db_transaction(sub { $r->_check_divert_core(); });
602 die "unchecked" unless exists $r->{Divert};
606 sub get_username ($) {
608 my $divert = $r->get_divert();
609 return undef if $divert;
613 sub url_with_query_params ($$) {
614 my ($r, $params) = @_;
615 my $uri = URI->new($r->_ch('get_url'));
616 $uri->query_form(flatten_params($params));
617 return $uri->as_string();
623 my ($divert) = $r->check_divert();
624 return 1 if !$divert;
626 my $handled = $r->_ch('handle_divert',$divert);
627 return 0 if $handled;
629 my $kind = $divert->{Kind};
630 my $cookieval = $divert->{CookieVal};
631 my $params = $divert->{Params};
633 if ($kind =~ m/^REDIRECT-/) {
634 # for redirects, we honour stored NextParams and SetCookie,
635 # as we would for non-divert
636 if ($kind eq 'REDIRECT-LOGGEDOUT') {
637 $params->{$r->{S}{loggedout_param_names}[0]} = 1;
638 } elsif ($kind eq 'REDIRECT-LOGOUT') {
639 $params->{$r->{S}{logout_param_names}[0]} = 1;
640 } elsif ($kind eq 'REDIRECT-LOGGEDIN') {
644 my $new_url = $r->url_with_query_params($params);
645 my $cookie = $r->construct_cookie($r, $cookieval);
646 $r->_ch('do_redirect',$new_url, $cookie);
651 if ($kind =~ m/^LOGIN-/) {
652 $title = $r->_gt('Login');
653 push @body, $r->_gt($divert->{Message});
654 push @body, $r->_ch('gen_login_form', $params);
655 } elsif ($kind =~ m/^SMALLPAGE-/) {
656 $title = $r->_gt('Not logged in');
657 push @body, $r->_gt($divert->{Message});
658 push @body, $r->_ch('gen_login_link');
663 $r->_print($r->_ch('start_html',$title),
665 $r->_ch('end_html'));
670 my ($r, $bytes) = @_;
672 my $rsf = $v->{RandomHandle};
673 my $rsp = $r->{S}{random_source};
675 $v->{RandomHandle} = $rsf = new IO::File $rsp, '<' or die "$rsp $!";
679 read($rsf,$bin,$bytes) == $bytes or die "$rsp $!";
681 return unpack "H*", $bin;
684 sub _fresh_cookie ($) {
686 my $bytes = ($r->{S}{associdlen} + 7) >> 3;
687 return $r->_random($bytes);
690 sub _assert_checked ($) {
692 die "unchecked" unless exists $r->{Divert};
695 sub check_mutate ($) {
697 $r->_assert_checked();
699 my $meth = $r->_ch('get_method');
700 die "mutating non-POST" if $meth ne 'POST';
703 #---------- output ----------
707 $r->_assert_checked();
708 return defined $r->{Assoc} ? $r->{Assoc} : '';
711 sub secret_hidden_html ($) {
713 return $r->{Cgi}->hidden(-name => $r->{S}{assoc_param_name},
714 -default => $r->secret_val());
717 sub secret_cookie ($) {
720 my $cookv = $r->construct_cookie($r->secret_val());
721 print STDERR "SC=$cookv\n";
729 CGI::Auth::Hybrid - web authentication optionally using cookies
733 my $verifier = CGI::Auth::Hybrid->new_verifier(setting => value,...);
734 my $authreq = $verifier->new_request($cgi_request_object);
736 my $authreq = CGI::Auth::Hybrid->new_request($cgi_request_object,
737 setting => value,...);
739 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
741 $authreq->check_ok() or return;
744 $authreq->check_mutate();
747 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
749 my $divert_kind = $authreq->check_divert();
751 if ($divert_kind eq 'LOGGEDOUT') {
752 print "goodbye you are now logged out" and quit
753 } elsif ($divert_kind eq 'NOCOOKIES') {
754 print "you need cookies" and quit
760 $authreq->check_mutate();