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);
43 #---------- public utilities ----------
45 sub flatten_params ($) {
48 foreach my $k (keys %$p) {
49 foreach my $v (@{ $p->{$k} }) {
56 #---------- default callbacks ----------
58 sub has_a_param ($$) {
60 foreach my $pn (@{ $r->{S}{$cn} }) {
61 return 1 if $r->_cm('get_param',$pn);
69 foreach my $name ($c->param()) {
70 $p{$name} = [ $c->param($name) ];
75 sub get_cookie_domain ($$$) {
77 my $uri = new URI $r->_ch('get_url');
81 sub login_ok_password ($$) {
83 my $username_params = $r->{S}{username_param_names};
84 my $username = $r->_ch('get_param',$username_params->[0]);
85 my $password = $r->_rp('password_param_name');
86 return $r->_ch('username_password_ok', $username, $password);
89 sub do_redirect_cgi ($$$$) {
90 my ($c, $r, $new_url, $cookie) = @_;
91 my @ha = ('text/html',
92 -status => '303 See other',
93 -location => $new_url);
94 push @ha, (-cookie => $cookie) if defined $cookie;
95 $r->_print($c->header(@ha),
96 $r->_ch('gen_start_html',$r->_gt('Redirection')),
97 '<a href="'.escapeHTML($new_url).'">',
98 $r->_gt("If you aren't redirected, click to continue."),
100 $c->_ch('gen_end_html'));
103 sub gen_plain_login_form ($$) {
104 my ($c,$r, $params) = @_;
106 push @form, ('<form method="POST" action="'.
107 escapeHTML($r->_ch('get_url')).'>'.
109 my $sz = 'size="'.$r->{S}{form_entry_size}.'"';
110 foreach my $up (@{ $r->{S}{username_param_names}}) {
111 push @form, ('<tr><td>',$r->_gt(ucfirst $up),'</td>',
112 '<td><input type="text" ',$sz.
113 ' name=',$up,'></td></tr>');
115 push @form, ('<tr><td>'.$r->_gt('Password'),'</td>',
116 '<td><input type="password" '.$sz.
117 ' name="'.$r->{S}{password_param_name}.'"></td></tr>');
118 push @form, ('<tr><td colspan="2">',
119 '<input type="submit"'.
120 ' name="'.$r->{S}{login_submit_name}.'"'.
121 ' value="'.$r->_gt('Login').'"></td></tr>',
123 foreach my $n (keys %$params) {
124 push @form, ('<input type="hidden"'.
126 ' value="'.$params->{$n}.'">');
128 push @form, ('</form>');
129 return join "\n", @form;
132 sub gen_login_link ($$) {
133 my ($c,$r, $params) = @_;
134 my $url = $r->url_with_query_params($params);
135 return ('<a href="'.escapeHTML($url).'">'.
136 $r->_gt('Log in again to continue.').
140 #---------- verifier object methods ----------
146 assocdb_path => 'cah-assocs.db',
147 assocdb_dsn => undef,
149 assocdb_password => '',
150 assocdb_table => 'assocs',
151 random_source => '/dev/urandom',
152 associdlen => 128, # bits
153 login_timeout => 86400, # seconds
154 assoc_param_name => 'cah_associd',
155 password_param_name => 'password',
156 username_param_names => [qw(username)],
157 form_entry_size => 60,
158 logout_param_names => [qw(cah_logout)],
159 login_submit_name => [qw(cah_login)],
160 loggedout_param_names => [qw(cah_loggedout)],
161 promise_check_mutate => 0,
162 get_param => sub { $_[0]->param($_[2]) },
163 get_params => sub { $_[1]->get_params() },
164 get_cookie => sub { $_[0]->cookie($_[1]->{S}{cookie_name}) },
165 get_method => sub { $_[0]->request_method() },
166 get_url => sub { $_[0]->url(); },
167 is_login => sub { defined $_[1]->_rp('password_param_name') },
168 login_ok => \&login_ok_password,
169 username_password_ok => sub { die },
170 is_logout => sub { $_[1]->has_a_param('logout_param_names') },
171 is_loggedout => sub { $_[1]->has_a_param('loggedout_param_names') },
172 is_page => sub { return 1 },
173 handle_divert => sub { return 0 },
174 do_redirect => \&do_redirect_cgi, # this hook is allowed to throw
176 get_cookie_domain => \&get_cookie_domain,
178 gen_start_html => sub { $_[0]->start_html($_[2]); },
179 gen_end_html => sub { $_[0]->end_html(); },
180 gen_login_form => \&gen_plain_login_form,
181 gen_login_link => \&gen_plain_login_link,
182 gettext => sub { gettext($_[2]); },
187 while (($k,$v,@_) = @_) {
188 die "unknown setting $k" unless exists $verifier->{S}{$k};
189 $verifier->{S}{$k} = $v;
191 bless $verifier, $class;
192 $verifier->_dbopen();
201 $v->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=$v->{S}{assocdb_path}";
202 my $dsn = $v->{S}{assocdb_dsn};
205 $dbh = DBI->connect($dsn, $v->{S}{assocdb_user},
206 $v->{S}{assocdb_password}, {
207 AutoCommit => 0, RaiseError => 1,
209 die "$dsn $! ?" unless $dbh;
213 $r->_db_transaction(sub {
214 $dbh->do("CREATE TABLE $v->{S}{assocdb_table} (".
215 " associdh VARCHAR PRIMARY KEY,".
216 " username VARCHAR,".
217 " last INTEGER NOT NULL".
231 sub _db_transaction ($$) {
241 { local ($@); $dbh->rollback(); }
250 die $@ if !--$retries;
254 #---------- request object methods ----------
257 my ($classbase, $cgi, @extra) = @_;
258 if (!ref $classbase) {
259 $classbase = $classbase->new_verifier(@extra);
265 S => $classbase->{S},
266 Dbh => $classbase->{Dbh},
269 bless $r, ref $classbase;
272 sub _ch ($$@) { # calls an application hook
273 my ($r,$methname, @args) = @_;
274 my $methfunc = $r->{S}{$methname};
275 return $methfunc->($r->{Cgi}, $r, @args);
280 my $pn = $r->{S}{$pnvb};
281 my $p = scalar $r->_ch('get_param',$pn)
284 sub _gt ($$) { my ($r, $t) = @_; return $r->_ch('gettext',$t); }
285 sub _print ($$) { my ($r, @t) = @_; return $r->_ch('print', join '', @t); }
287 sub construct_cookie ($$$) {
288 my ($r, $cookv) = @_;
289 return $r->{Cgi}->cookie(-name => $r->{S}{cookie_name},
291 -path => $r->{S}{cookie_path},
292 -domain => $r->_ch('get_cookie_domain'),
293 -expires => '+'.$r->{S}{login_timeout}.'s',
294 -secure => $r->{S}{encrypted_only});
297 # pages/param-sets are
298 # n normal non-mutating page
299 # r retrieval of information for JS, non-mutating
301 # u update of information by JS, mutating
304 # O "you have just logged out" page load
307 # a, aN anything including -
308 # t, tN temporary value (in our db, no logged in user yet)
309 # y, yN value corresponds to logged-in user
310 # n, nN value not in our db
312 # - no value supplied
313 # if N differs the case applies only when the two values differ
314 # (eg, a1 y2 does not apply when the logged-in value is supplied twice)
316 # "stale session" means request originates from a page from a login
317 # session which has been revoked (eg by logout); "cleared session"
318 # means request originates from a browser which has a different (or
321 # Case analysis, cookie mode, app promises re mutate:
322 # cook parm meth form
324 # any - POST nrmuoi bug or attack, fail
325 # any - GET rmuoi bug or attack, fail
326 # any any GET muoi bug or attack, fail
327 # any t any nrmu bug or attack, fail
329 # - - GET O "just logged out" page
330 # (any other) O bug or attack, fail
332 # a1 a2 POST o logout
333 # if a1 is valid, revoke it
334 # if a2 is valid, revoke it
336 # redirect to "just logged out" page
337 # (which contains link to login form)
339 # - t POST i complain about cookies being disabled
340 # (with link to login form)
342 # any n POST i complain about stale login form
343 # show new login form
345 # x1 t2 POST i login (or switch user)
347 # show new login form
349 # revoke x1 if it was valid and !=t2
350 # upgrade t2 to y2 in our db (setting username)
352 # redirect to GET of remaining params
354 # t1 a2 ANY nrmu treat as - a2 ANY
356 # y - GET n cross-site link
359 # y y GET nr fine, show page or send data
360 # y y POST nrmu mutation is OK, do operation
362 # y1 y2 GET nr request from stale page
363 # do not revoke y2 as not RESTful
366 # y1 y2 POST nrmu request from stale page
370 # y n GET n intra-site link from stale page,
371 # treat as cross-site link, show data
373 # y n POST n m intra-site form submission from stale page
374 # show "session interrupted"
375 # with link to main data page
377 # y n GET r intra-site request from stale page
380 # y n POST r u intra-site request from stale page
383 # -/n y2 GET nr intra-site link from cleared session
384 # do not revoke y2 as not RESTful
387 # -/n y2 POST nrmu request from cleared session
389 # treat as -/n n POST
391 # -/n n GET n cross-site link but user not logged in
392 # show login form with redirect to orig params
394 # -/n n GET rmu user not logged in
397 # -/n n POST n m user not logged in
400 # -/n n POST r u user not logged in
403 sub _check_divert_core ($) {
406 my $meth = $r->_ch('get_method');
407 my $cookv = $r->_ch('get_cookie');
408 my $parmv = $r->_rp('assoc_param_name');
410 my ($cookt,$cooku) = $r->_db_lookup($cookv);
411 my $parmt = $r->_db_lookup($parmv);
413 if ($r->_ch('is_logout')) {
416 $r->_db_revoke($cookv);
417 $r->_db_revoke($parmv);
418 return ({ Kind => 'REDIRECT-LOGGEDOUT',
419 Message => "Logging out...",
423 if ($r->_ch('is_loggedout')) {
424 die unless $meth eq 'GET';
427 return ({ Kind => 'SMALLPAGE-LOGGEDOUT',
428 Message => "You have been logged out.",
432 if ($r->_ch('is_login')) {
434 return ({ Kind => 'LOGIN-STALE',
435 Message => "Stale session; you need to log in again.",
436 CookieVal => $r->_fresh_cookie(),
439 die unless $parmt eq 't' || $parmt eq 'y';
440 return ({ Kind => 'SMALLPAGE-NOCOOKIE',
441 Message => "You do not seem to have cookies enabled. ".
442 "You must enable cookies as we use them for login.",
443 CookieVal => $r->_fresh_cookie(),
444 Params => $r->_chain_params() })
445 if !$cookt && $parmt eq 't';
446 my $username = $r->_ch('login_ok');
447 return ({ Kind => 'LOGIN-BAD',
448 Message => "Incorrect username/password.",
450 Params => $r->_chain_params() })
451 unless defined $username && length $username;
452 $r->_db_revoke($cookv)
453 if defined $cookv && !(defined $parmv && $cookv eq $parmv);
454 $r->_db_record_login_ok($parmv,$username);
455 return ({ Kind => 'REDIRECT-LOGGEDIN',
456 Message => "Logging in...",
458 Params => $r->_chain_params() });
463 die if $parmt eq 't';
465 if ($cookt eq 'y' && $parmt eq 'y' && $cookv ne $parmv) {
466 $r->_db_revoke($parmv) if $meth eq 'POST';
471 die unless !$cookt || $cookt eq 'n';
472 die unless !$parmt || $parmt eq 'n' || $parmt eq 'y';
473 if ($meth eq 'GET') {
474 return ({ Kind => 'LOGIN-INCOMINGLINK',
475 Message => "You need to log in again.",
477 Params => $r->_chain_params() });
479 return ({ Kind => 'LOGIN-FRESH',
480 Message => "You need to log in again.",
486 if (!$r->{S}{promise_check_mutate}) {
487 if ($meth ne 'POST') {
488 return ({ Kind => 'MAINPAGEONLY',
489 Message => 'Entering via cross-site link.',
492 # NB caller must then ignore params & path!
493 # if this is too hard they can spit out a small form
494 # with a "click to continue"
498 die unless $cookt eq 'y';
499 die unless $parmt eq 'y';
500 die unless $cookv eq $parmv;
501 $r->{Assoc} = $cookv;
502 $r->{UserOK} = $cooku;
506 sub _chain_params ($) {
508 my %p = %{ $r->_ch('get_params') };
509 foreach my $pncn (keys %{ $r->{S} }) {
511 if ($pncn =~ m/_param_name$/) {
512 my $name = $r->{S}{$pncn};
513 die "$pncn ?" if ref $name;
515 } elsif ($pncn =~ m/_param_names$/) {
516 $names = $r->{S}{$pncn};
520 foreach my $name (@$names) {
527 sub _db_lookup ($$) {
529 # returns ($t,$username)
530 # where $t is one of "t" "y" "n", or "" (for -)
534 my $row = $dbh->selectrow_arrayref("SELECT username, last".
535 " FROM $r->{S}{assocdb_table}".
536 " WHERE associd = ?", {}, $v);
537 return ('') unless defined $row;
539 my ($nusername, $nlast) = @$row;
541 my $timeout = $r->{S}{login_timeout};
542 return ('n') unless !defined $timeout || time <= $nlast + $timeout;
544 return ('t') unless defined $nusername;
547 return ('y', $nusername);
550 sub _db_revoke ($$) {
551 # revokes $v if it's valid; no-op if it's not
556 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
557 " WHERE associd = ?", {}, $v);
560 sub _db_record_login_ok ($$$) {
561 my ($r,$v,$user) = @_;
564 $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
565 " (associd, username, last) VALUES (?,?,?)", {},
569 sub check_divert ($) {
572 if (exists $r->{Divert}) {
576 $r->{Divert} = $r->_db_transaction(sub { $r->_check_divert_core(); });
583 die "unchecked" unless exists $r->{Divert};
587 sub get_username ($) {
589 my $divert = $r->get_divert();
590 return undef if $divert;
594 sub url_with_query_params ($$) {
595 my ($r, $params) = @_;
596 my $uri = URI->new($r->_ch('get_url'));
597 $uri->query_form(flatten_params($params));
598 return $uri->as_string();
604 my ($divert) = $r->check_divert();
607 my $handled = $r->_ch('handle_divert',$divert);
608 return 0 if $handled;
610 my $kind = $divert->{Kind};
611 my $cookieval = $divert->{CookieVal};
612 my $params = $divert->{Params};
614 if ($kind =~ m/^REDIRECT-/) {
615 # for redirects, we honour stored NextParams and SetCookie,
616 # as we would for non-divert
617 if ($kind eq 'REDIRECT-LOGGEDOUT') {
618 $params->{$r->{S}{loggedout_param_names}[0]} = 1;
619 } elsif ($kind eq 'REDIRECT-LOGOUT') {
620 $params->{$r->{S}{logout_param_names}[0]} = 1;
621 } elsif ($kind eq 'REDIRECT-LOGGEDIN') {
625 my $new_url = $r->url_with_query_params($params);
626 my $cookie = $r->construct_cookie($r, $cookieval);
627 $r->_ch('do_redirect',$new_url, $cookie);
632 if ($kind =~ m/^LOGIN-/) {
633 $title = $r->_gt('Login');
634 push @body, $r->_gt($divert->{Message});
635 push @body, $r->_ch('gen_login_form', $params);
636 } elsif ($kind =~ m/^SMALLPAGE-/) {
637 $title = $r->_gt('Not logged in');
638 push @body, $r->_gt($divert->{Message});
639 push @body, $r->_ch('gen_login_link');
644 $r->_print($r->_ch('start_html',$title),
646 $r->_ch('end_html'));
651 my ($r, $bytes) = @_;
653 my $rsf = $v->{RandomHandle};
654 my $rsp = $r->{S}{random_source};
656 $v->{RandomHandle} = $rsf = new IO::File $rsp, '<' or die "$rsp $!";
660 read($rsf,$bin,$bytes) == $bytes or die "$rsp $!";
662 return unpack "H*", $bin;
665 sub _fresh_cookie ($) {
667 my $bytes = ($r->{S}{associdlen} + 7) >> 3;
668 return $r->_random($bytes);
671 sub check_mutate ($) {
673 die "unchecked" unless exists $r->{Divert};
675 my $meth = $r->_ch('get_method');
676 die "mutating non-POST" if $meth ne 'POST';
679 #---------- output ----------
684 return defined $r->{Assoc} ? $r->{Assoc} : '';
687 sub secret_hidden_html ($) {
689 return $r->{Cgi}->hidden(-name => $r->{S}{assoc_param_name},
690 -default => $r->secret_val());
693 sub secret_cookie ($) {
695 return $r->construct_cookie($r->secret_val());
702 CGI::Auth::Hybrid - web authentication optionally using cookies
706 my $verifier = CGI::Auth::Hybrid->new_verifier(setting => value,...);
707 my $authreq = $verifier->new_request($cgi_request_object);
709 my $authreq = CGI::Auth::Hybrid->new_request($cgi_request_object,
710 setting => value,...);
712 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
714 $authreq->check_ok() or return;
717 $authreq->check_mutate();
720 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
722 my $divert_kind = $authreq->check_divert();
724 if ($divert_kind eq 'LOGGEDOUT') {
725 print "goodbye you are now logged out" and quit
726 } elsif ($divert_kind eq 'NOCOOKIES') {
727 print "you need cookies" and quit
733 $authreq->check_mutate();