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 ($$) {
246 { local ($@); $dbh->rollback(); }
255 die $@ if !--$retries;
259 #---------- request object methods ----------
262 my ($classbase, $cgi, @extra) = @_;
263 if (!ref $classbase) {
264 $classbase = $classbase->new_verifier(@extra);
270 S => $classbase->{S},
271 Dbh => $classbase->{Dbh},
274 bless $r, ref $classbase;
277 sub _ch ($$@) { # calls an application hook
278 my ($r,$methname, @args) = @_;
279 my $methfunc = $r->{S}{$methname};
280 return $methfunc->($r->{Cgi}, $r, @args);
285 my $pn = $r->{S}{$pnvb};
286 my $p = scalar $r->_ch('get_param',$pn)
289 sub _gt ($$) { my ($r, $t) = @_; return $r->_ch('gettext',$t); }
290 sub _print ($$) { my ($r, @t) = @_; return $r->_ch('print', join '', @t); }
292 sub construct_cookie ($$$) {
293 my ($r, $cookv) = @_;
294 return undef unless $cookv;
295 return $r->{Cgi}->cookie(-name => $r->{S}{cookie_name},
297 -path => $r->{S}{cookie_path},
298 -domain => $r->_ch('get_cookie_domain'),
299 -expires => '+'.$r->{S}{login_timeout}.'s',
300 -secure => $r->{S}{encrypted_only});
303 # pages/param-sets are
304 # n normal non-mutating page
305 # r retrieval of information for JS, non-mutating
307 # u update of information by JS, mutating
310 # O "you have just logged out" page load
313 # a, aN anything including -
314 # t, tN temporary value (in our db, no logged in user yet)
315 # y, yN value corresponds to logged-in user
316 # n, nN value not in our db
318 # - no value supplied
319 # if N differs the case applies only when the two values differ
320 # (eg, a1 y2 does not apply when the logged-in value is supplied twice)
322 # "stale session" means request originates from a page from a login
323 # session which has been revoked (eg by logout); "cleared session"
324 # means request originates from a browser which has a different (or
327 # Case analysis, cookie mode, app promises re mutate:
328 # cook parm meth form
330 # any - POST nrmuoi bug or attack, fail
331 # any - GET rmuoi bug or attack, fail
332 # any any GET muoi bug or attack, fail
333 # any t any nrmu bug or attack, fail
335 # - - GET O "just logged out" page
336 # (any other) O bug or attack, fail
338 # a1 a2 POST o logout
339 # if a1 is valid, revoke it
340 # if a2 is valid, revoke it
342 # redirect to "just logged out" page
343 # (which contains link to login form)
345 # - t POST i complain about cookies being disabled
346 # (with link to login form)
348 # any n POST i complain about stale login form
349 # show new login form
351 # x1 t2 POST i login (or switch user)
353 # show new login form
355 # revoke x1 if it was valid and !=t2
356 # upgrade t2 to y2 in our db (setting username)
358 # redirect to GET of remaining params
360 # t1 a2 ANY nrmu treat as - a2 ANY
362 # y - GET n cross-site link
365 # y y GET nr fine, show page or send data
366 # y y POST nrmu mutation is OK, do operation
368 # y1 y2 GET nr request from stale page
369 # do not revoke y2 as not RESTful
372 # y1 y2 POST nrmu request from stale page
376 # y n GET n intra-site link from stale page,
377 # treat as cross-site link, show data
379 # y n POST n m intra-site form submission from stale page
380 # show "session interrupted"
381 # with link to main data page
383 # y n GET r intra-site request from stale page
386 # y n POST r u intra-site request from stale page
389 # -/n y2 GET nr intra-site link from cleared session
390 # do not revoke y2 as not RESTful
393 # -/n y2 POST nrmu request from cleared session
395 # treat as -/n n POST
397 # -/n n GET n cross-site link but user not logged in
398 # show login form with redirect to orig params
400 # -/n n GET rmu user not logged in
403 # -/n n POST n m user not logged in
406 # -/n n POST r u user not logged in
409 sub _check_divert_core ($) {
412 my $meth = $r->_ch('get_method');
413 my $cookv = $r->_ch('get_cookie');
414 my $parmv = $r->_rp('assoc_param_name');
416 my ($cookt,$cooku) = $r->_db_lookup($cookv);
417 my $parmt = $r->_db_lookup($parmv);
419 if ($r->_ch('is_logout')) {
422 $r->_db_revoke($cookv);
423 $r->_db_revoke($parmv);
424 return ({ Kind => 'REDIRECT-LOGGEDOUT',
425 Message => "Logging out...",
429 if ($r->_ch('is_loggedout')) {
430 die unless $meth eq 'GET';
433 return ({ Kind => 'SMALLPAGE-LOGGEDOUT',
434 Message => "You have been logged out.",
438 if ($r->_ch('is_login')) {
440 return ({ Kind => 'LOGIN-STALE',
441 Message => "Stale session; you need to log in again.",
442 CookieVal => $r->_fresh_cookie(),
445 die unless $parmt eq 't' || $parmt eq 'y';
446 return ({ Kind => 'SMALLPAGE-NOCOOKIE',
447 Message => "You do not seem to have cookies enabled. ".
448 "You must enable cookies as we use them for login.",
449 CookieVal => $r->_fresh_cookie(),
450 Params => $r->_chain_params() })
451 if !$cookt && $parmt eq 't';
452 my $username = $r->_ch('login_ok');
453 return ({ Kind => 'LOGIN-BAD',
454 Message => "Incorrect username/password.",
456 Params => $r->_chain_params() })
457 unless defined $username && length $username;
458 $r->_db_revoke($cookv)
459 if defined $cookv && !(defined $parmv && $cookv eq $parmv);
460 $r->_db_record_login_ok($parmv,$username);
461 return ({ Kind => 'REDIRECT-LOGGEDIN',
462 Message => "Logging in...",
464 Params => $r->_chain_params() });
469 die if $parmt eq 't';
471 if ($cookt eq 'y' && $parmt eq 'y' && $cookv ne $parmv) {
472 $r->_db_revoke($parmv) if $meth eq 'POST';
477 die unless !$cookt || $cookt eq 'n';
478 die unless !$parmt || $parmt eq 'n' || $parmt eq 'y';
479 if ($meth eq 'GET') {
480 return ({ Kind => 'LOGIN-INCOMINGLINK',
481 Message => "You need to log in again.",
483 Params => $r->_chain_params() });
485 return ({ Kind => 'LOGIN-FRESH',
486 Message => "You need to log in again.",
492 if (!$r->{S}{promise_check_mutate}) {
493 if ($meth ne 'POST') {
494 return ({ Kind => 'MAINPAGEONLY',
495 Message => 'Entering via cross-site link.',
498 # NB caller must then ignore params & path!
499 # if this is too hard they can spit out a small form
500 # with a "click to continue"
504 die unless $cookt eq 'y';
505 die unless $parmt eq 'y';
506 die unless $cookv eq $parmv;
507 $r->{Assoc} = $cookv;
508 $r->{UserOK} = $cooku;
512 sub _chain_params ($) {
514 my %p = %{ $r->_ch('get_params') };
515 foreach my $pncn (keys %{ $r->{S} }) {
517 if ($pncn =~ m/_param_name$/) {
518 my $name = $r->{S}{$pncn};
519 die "$pncn ?" if ref $name;
521 } elsif ($pncn =~ m/_param_names$/) {
522 $names = $r->{S}{$pncn};
526 foreach my $name (@$names) {
533 sub _db_lookup ($$) {
535 # returns ($t,$username)
536 # where $t is one of "t" "y" "n", or "" (for -)
540 my $row = $dbh->selectrow_arrayref("SELECT username, last".
541 " FROM $r->{S}{assocdb_table}".
542 " WHERE associd = ?", {}, $v);
543 return ('') unless defined $row;
545 my ($nusername, $nlast) = @$row;
547 my $timeout = $r->{S}{login_timeout};
548 return ('n') unless !defined $timeout || time <= $nlast + $timeout;
550 return ('t') unless defined $nusername;
553 return ('y', $nusername);
556 sub _db_revoke ($$) {
557 # revokes $v if it's valid; no-op if it's not
562 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
563 " WHERE associd = ?", {}, $v);
566 sub _db_record_login_ok ($$$) {
567 my ($r,$v,$user) = @_;
570 $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
571 " (associd, username, last) VALUES (?,?,?)", {},
575 sub check_divert ($) {
578 if (exists $r->{Divert}) {
582 $r->{Divert} = $r->_db_transaction(sub { $r->_check_divert_core(); });
589 die "unchecked" unless exists $r->{Divert};
593 sub get_username ($) {
595 my $divert = $r->get_divert();
596 return undef if $divert;
600 sub url_with_query_params ($$) {
601 my ($r, $params) = @_;
602 my $uri = URI->new($r->_ch('get_url'));
603 $uri->query_form(flatten_params($params));
604 return $uri->as_string();
610 my ($divert) = $r->check_divert();
611 return 1 if !$divert;
613 my $handled = $r->_ch('handle_divert',$divert);
614 return 0 if $handled;
616 my $kind = $divert->{Kind};
617 my $cookieval = $divert->{CookieVal};
618 my $params = $divert->{Params};
620 if ($kind =~ m/^REDIRECT-/) {
621 # for redirects, we honour stored NextParams and SetCookie,
622 # as we would for non-divert
623 if ($kind eq 'REDIRECT-LOGGEDOUT') {
624 $params->{$r->{S}{loggedout_param_names}[0]} = 1;
625 } elsif ($kind eq 'REDIRECT-LOGOUT') {
626 $params->{$r->{S}{logout_param_names}[0]} = 1;
627 } elsif ($kind eq 'REDIRECT-LOGGEDIN') {
631 my $new_url = $r->url_with_query_params($params);
632 my $cookie = $r->construct_cookie($r, $cookieval);
633 $r->_ch('do_redirect',$new_url, $cookie);
638 if ($kind =~ m/^LOGIN-/) {
639 $title = $r->_gt('Login');
640 push @body, $r->_gt($divert->{Message});
641 push @body, $r->_ch('gen_login_form', $params);
642 } elsif ($kind =~ m/^SMALLPAGE-/) {
643 $title = $r->_gt('Not logged in');
644 push @body, $r->_gt($divert->{Message});
645 push @body, $r->_ch('gen_login_link');
650 $r->_print($r->_ch('start_html',$title),
652 $r->_ch('end_html'));
657 my ($r, $bytes) = @_;
659 my $rsf = $v->{RandomHandle};
660 my $rsp = $r->{S}{random_source};
662 $v->{RandomHandle} = $rsf = new IO::File $rsp, '<' or die "$rsp $!";
666 read($rsf,$bin,$bytes) == $bytes or die "$rsp $!";
668 return unpack "H*", $bin;
671 sub _fresh_cookie ($) {
673 my $bytes = ($r->{S}{associdlen} + 7) >> 3;
674 return $r->_random($bytes);
677 sub _assert_checked ($) {
679 die "unchecked" unless exists $r->{Divert};
682 sub check_mutate ($) {
684 $r->_assert_checked();
686 my $meth = $r->_ch('get_method');
687 die "mutating non-POST" if $meth ne 'POST';
690 #---------- output ----------
694 $r->_assert_checked();
695 return defined $r->{Assoc} ? $r->{Assoc} : '';
698 sub secret_hidden_html ($) {
700 return $r->{Cgi}->hidden(-name => $r->{S}{assoc_param_name},
701 -default => $r->secret_val());
704 sub secret_cookie ($) {
706 return $r->construct_cookie($r->secret_val());
713 CGI::Auth::Hybrid - web authentication optionally using cookies
717 my $verifier = CGI::Auth::Hybrid->new_verifier(setting => value,...);
718 my $authreq = $verifier->new_request($cgi_request_object);
720 my $authreq = CGI::Auth::Hybrid->new_request($cgi_request_object,
721 setting => value,...);
723 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
725 $authreq->check_ok() or return;
728 $authreq->check_mutate();
731 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
733 my $divert_kind = $authreq->check_divert();
735 if ($divert_kind eq 'LOGGEDOUT') {
736 print "goodbye you are now logged out" and quit
737 } elsif ($divert_kind eq 'NOCOOKIES') {
738 print "you need cookies" and quit
744 $authreq->check_mutate();