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 construct_cookie ($$$) {
83 return $r->{Cgi}->cookie(-name => $r->{S}{cookie_name},
85 -path => $r->{S}{cookie_path},
86 -domain => $r->_ch('get_cookie_domain'),
87 -expires => '+'.$r->{S}{login_timeout}.'s',
88 -secure => $r->{S}{encrypted_only});
91 sub login_ok_password ($$) {
93 my $username_params = $r->{S}{username_param_names};
94 my $username = $r->_ch('get_param',$username_params->[0]);
95 my $password = $r->_rp('password_param_name');
96 return $r->_ch('username_password_ok', $username, $password);
99 sub do_redirect_cgi ($$$$) {
100 my ($c, $r, $new_url, $cookie) = @_;
101 my @ha = ('text/html',
102 -status => '303 See other',
103 -location => $new_url);
104 push @ha, (-cookie => $cookie) if defined $cookie;
105 $r->_print($c->header(@ha),
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 $c->_ch('gen_end_html'));
113 sub gen_plain_login_form ($$) {
114 my ($c,$r, $params) = @_;
116 push @form, ('<form method="POST" action="'.
117 escapeHTML($r->_ch('get_url')).'>'.
119 my $sz = 'size="'.$r->{S}{form_entry_size}.'"';
120 foreach my $up (@{ $r->{S}{username_param_names}}) {
121 push @form, ('<tr><td>',$r->_gt(ucfirst $up),'</td>',
122 '<td><input type="text" ',$sz.
123 ' name=',$up,'></td></tr>');
125 push @form, ('<tr><td>'.$r->_gt('Password'),'</td>',
126 '<td><input type="password" '.$sz.
127 ' name="'.$r->{S}{password_param_name}.'"></td></tr>');
128 push @form, ('<tr><td colspan="2">',
129 '<input type="submit"'.
130 ' name="'.$r->{S}{login_submit_name}.'"'.
131 ' value="'.$r->_gt('Login').'"></td></tr>',
133 foreach my $n (keys %$params) {
134 push @form, ('<input type="hidden"'.
136 ' value="'.$params->{$n}.'">');
138 push @form, ('</form>');
139 return join "\n", @form;
142 sub gen_login_link ($$) {
143 my ($c,$r, $params) = @_;
144 my $url = $r->url_with_query_params($params);
145 return ('<a href="'.escapeHTML($url).'">'.
146 $r->_gt('Log in again to continue.').
150 #---------- verifier object methods ----------
156 assocdb_path => 'cah-assocs.db',
157 assocdb_dsn => undef,
159 assocdb_password => '',
160 assocdb_table => 'assocs',
161 random_source => '/dev/urandom',
162 associdlen => 128, # bits
163 login_timeout => 86400, # seconds
164 assoc_param_name => 'cah_associd',
165 password_param_name => 'password',
166 username_param_names => [qw(username)],
167 form_entry_size => 60,
168 logout_param_names => [qw(cah_logout)],
169 login_submit_name => [qw(cah_login)],
170 loggedout_param_names => [qw(cah_loggedout)],
171 promise_check_mutate => 0,
172 get_param => sub { $_[0]->param($_[2]) },
173 get_params => sub { $_[1]->get_params() },
174 get_cookie => sub { $_[0]->cookie($s->{S}{cookie_name}) },
175 get_method => sub { $_[0]->request_method() },
176 get_url => sub { $_[0]->url(); },
177 is_login => sub { defined $_[1]->_rp('password_param_name') },
178 login_ok => \&login_ok_password,
179 username_password_ok => sub { die },
180 is_logout => sub { $_[1]->has_a_param('logout_param_names') },
181 is_loggedout => sub { $_[1]->has_a_param('loggedout_param_names') },
182 is_page => sub { return 1 },
183 handle_divert => sub { return 0 },
184 do_redirect => \&do_redirect_cgi, # this hook is allowed to throw
186 get_cookie_domain => \&get_cookie_domain,
188 gen_start_html => sub { $_[0]->start_html($_[2]); },
189 gen_end_html => sub { $_[0]->end_html(); },
190 gen_login_form => \&gen_plain_login_form,
191 gen_login_link => \&gen_plain_login_link,
192 gettext => sub { gettext($_[2]); },
197 while (($k,$v,@_) = @_) {
198 die "unknown setting $k" unless exists $s->{S}{$k};
201 bless $verifier, $class;
202 $verifier->_dbopen();
211 $v->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=$v->{S}{assocdb_path}";
214 $dbh = DBI->connect($v->{S}{assocdb_dsn}, $v->{S}{assocdb_user},
215 $v->{S}{assocdb_password}, {
216 AutoCommit => 0, RaiseError => 1,
218 die "${assocdb_dsn} $! ?" unless $dbh;
224 $dbh->do("CREATE TABLE $v->{S}{assocdb_table} (".
225 " associdh VARCHAR PRIMARY KEY,".
226 " username VARCHAR,".
227 " last INTEGER NOT NULL".
240 #---------- request object methods ----------
243 my ($classbase, $cgi, @extra) = @_;
244 if (!ref $classbase) {
245 $classbase = $classbase->new_verifier(@extra);
251 S => $classbase->{S},
252 Dbh => $classbase->{Dbh},
255 bless $r, ref $classbase;
258 sub _ch ($$@) { # calls an application hook
259 my ($r,$methname, @args) = @_;
260 my $methfunc = $r->{S}{$methname};
261 return $methfunc->($r->{Cgi}, $r, @args);
266 my $pn = $r->{S}{$pnvb};
267 my $p = scalar $r->_ch('get_param',$pn)
270 sub _gt ($$) { my ($r, $t) = @_; return $r->_ch('gettext',$t); }
271 sub _print ($$) { my ($r, @t) = @_; return $r->_ch('print', join '', @t); }
273 # pages/param-sets are
274 # n normal non-mutating page
275 # r retrieval of information for JS, non-mutating
277 # u update of information by JS, mutating
280 # O "you have just logged out" page load
283 # a, aN anything including -
284 # t, tN temporary value (in our db, no logged in user yet)
285 # y, yN value corresponds to logged-in user
286 # n, nN value not in our db
288 # - no value supplied
289 # if N differs the case applies only when the two values differ
290 # (eg, a1 y2 does not apply when the logged-in value is supplied twice)
292 # "stale session" means request originates from a page from a login
293 # session which has been revoked (eg by logout); "cleared session"
294 # means request originates from a browser which has a different (or
297 # Case analysis, cookie mode, app promises re mutate:
298 # cook parm meth form
300 # any - POST nrmuoi bug or attack, fail
301 # any - GET rmuoi bug or attack, fail
302 # any any GET muoi bug or attack, fail
303 # any t any nrmu bug or attack, fail
305 # - - GET O "just logged out" page
306 # (any other) O bug or attack, fail
308 # a1 a2 POST o logout
309 # if a1 is valid, revoke it
310 # if a2 is valid, revoke it
312 # redirect to "just logged out" page
313 # (which contains link to login form)
315 # - t POST i complain about cookies being disabled
316 # (with link to login form)
318 # any n POST i complain about stale login form
319 # show new login form
321 # x1 t2 POST i login (or switch user)
323 # show new login form
325 # revoke x1 if it was valid and !=t2
326 # upgrade t2 to y2 in our db (setting username)
328 # redirect to GET of remaining params
330 # t1 a2 ANY nrmu treat as - a2 ANY
332 # y - GET n cross-site link
335 # y y GET nr fine, show page or send data
336 # y y POST nrmu mutation is OK, do operation
338 # y1 y2 GET nr request from stale page
339 # do not revoke y2 as not RESTful
342 # y1 y2 POST nrmu request from stale page
346 # y n GET n intra-site link from stale page,
347 # treat as cross-site link, show data
349 # y n POST n m intra-site form submission from stale page
350 # show "session interrupted"
351 # with link to main data page
353 # y n GET r intra-site request from stale page
356 # y n POST r u intra-site request from stale page
359 # -/n y2 GET nr intra-site link from cleared session
360 # do not revoke y2 as not RESTful
363 # -/n y2 POST nrmu request from cleared session
365 # treat as -/n n POST
367 # -/n n GET n cross-site link but user not logged in
368 # show login form with redirect to orig params
370 # -/n n GET rmu user not logged in
373 # -/n n POST n m user not logged in
376 # -/n n POST r u user not logged in
379 sub _check_divert_core ($) {
382 my $meth = $r->_ch('get_method');
383 my $cookv = $r->_ch('get_cookie');
384 my $parmv = $r->_rp('assoc_param_name');
386 my ($cookt,$cooku) = $r->_db_lookup($cookv);
387 my $parmt = $r->_db_lookup($parmv);
389 if ($r->_ch('is_logout')) {
392 $r->_db_revoke($cookv);
393 $r->_db_revoke($parmv);
394 return ({ Kind => 'REDIRECT-LOGGEDOUT',
395 Message => "Logging out...",
399 if ($r->_ch('is_loggedout')) {
400 die unless $meth eq 'GET';
403 return ({ Kind => 'SMALLPAGE-LOGGEDOUT',
404 Message => "You have been logged out.",
408 if ($r->_ch('is_login')) {
410 return ({ Kind => 'LOGIN-STALE',
411 Message => "Stale session; you need to log in again.",
412 CookieVal => $r->_fresh_cookie(),
415 die unless $parmt eq 't' || $parmt eq 'y';
416 return ({ Kind => 'SMALLPAGE-NOCOOKIE',
417 Message => "You do not seem to have cookies enabled. ".
418 "You must enable cookies as we use them for login.",
419 CookieVal => $r->_fresh_cookie(),
420 Params => $r->_chain_params() })
421 if !$cookt && $parmt eq 't';
422 my $username = $r->_ch('login_ok');
423 return ({ Kind => 'LOGIN-BAD',
424 Message => "Incorrect username/password.",
426 Params => $r->_chain_params() })
427 unless defined $username && length $username;
428 $r->_db_revoke($cookv)
429 if defined $cookv && !(defined $parmv && $cookv eq $parmv);
430 $r->_db_record_login_ok($parmv,$username);
431 return ({ Kind => 'REDIRECT-LOGGEDIN',
432 Message => "Logging in...",
434 Params => $r->_chain_params() });
439 die if $parmt eq 't';
441 if ($cookt eq 'y' && $parmt eq 'y' && $cookv ne $parmv) {
442 $r->_db_revoke($parmv) if $meth eq 'POST';
447 die unless !$cookt || $cookt eq 'n';
448 die unless !$parmt || $parmt eq 'n' || $parmt eq 'y';
449 if ($meth eq 'GET') {
450 return ({ Kind => 'LOGIN-INCOMINGLINK',
451 Message => "You need to log in again.",
453 Params => $r->_chain_params() });
455 return ({ Kind => 'LOGIN-FRESH',
456 Message => "You need to log in again.",
462 if (!$r->{S}{promise_check_mutate}) {
463 if ($meth ne 'POST') {
464 return ({ Kind => 'MAINPAGEONLY',
465 Message => 'Entering via cross-site link.',
468 # NB caller must then ignore params & path!
469 # if this is too hard they can spit out a small form
470 # with a "click to continue"
474 die unless $cookt eq 'y';
475 die unless $parmt eq 'y';
476 die unless $cookv eq $parmv;
477 $r->{Assoc} = $cookv;
478 $r->{UserOK} = $cooku;
482 sub _chain_params ($) {
484 my %p = %{ $r->_ch('get_params') };
485 foreach my $pncn (keys %{ $r->{S} }) {
486 if ($pncn =~ m/_param_name$/) {
487 my $name = $r->{S}{$pncn};
488 die "$pncn ?" if ref $name;
490 } elsif ($pncn =~ m/_param_names$/) {
491 $names = $r->{S}{$pncn};
495 foreach my $param (@$names) {
502 sub _db_lookup ($$) {
503 # returns ($t,$username)
504 # where $t is one of "t" "y" "n", or "" (for -)
509 my ($nusername, $nlast) =
510 $dbh->selectrow_array("SELECT username, last".
511 " FROM $r->{S}{assocdb_table}".
512 " WHERE associd = ?", {}, $nassoc);
513 return ('') unless defined $nusername;
515 my $timeout = $r->{S}{login_timeout};
516 return ('n') unless !defined $timeout || time <= $nlast + $timeout;
518 return ('t') unless defined $nusername;
521 return ('y', $nusername);
524 sub _db_revoke ($$) {
525 # revokes $v if it's valid; no-op if it's not
530 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
531 " WHERE associd = ?", {}, $v);
534 sub _db_record_login_ok ($$$) {
535 my ($r,$v,$user) = @_;
537 $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
538 " (associd, username, last) VALUES (?,?,?)", {},
542 sub check_divert ($) {
545 if (exists $r->{Divert}) {
550 $divert = $r->_check_divert_core();
556 $r->{Divert} = $divert;
563 die "unchecked" unless exists $r->{Divert};
567 sub get_username ($) {
569 my $divert = $r->get_divert();
570 return undef if $divert;
574 sub url_with_query_params ($$) {
575 my ($r, $params) = @_;
576 my $uri = URI->new($r->_ch('get_url'));
577 $uri->query_form(flatten_params($params));
578 return $uri->as_string();
584 my ($divert) = $r->check_divert();
587 my $handled = $r->_ch('handle_divert',$divert);
588 return 0 if $handled;
590 my $kind = $divert->{Kind};
591 my $cookieval = $divert->{CookieVal};
592 my $params = $divert->{Params};
594 if ($kind =~ m/^REDIRECT-/) {
595 # for redirects, we honour stored NextParams and SetCookie,
596 # as we would for non-divert
597 if ($divert_kind eq 'REDIRECT-LOGGEDOUT') {
598 $params{$r->{S}{loggedout_param_names}[0]} = 1;
599 } elsif ($divert_kind eq 'REDIRECT-LOGOUT') {
600 $params{$r->{S}{logout_param_names}[0]} = 1;
601 } elsif ($divert_kind eq 'REDIRECT-LOGGEDIN') {
605 my $new_url = $r->url_with_query_params($params);
606 my $cookie = $r->construct_cookie($r, $cookieval);
607 $r->_ch('do_redirect',$new_url, $cookie);
612 if ($kind =~ m/^LOGIN-/) {
613 $title = $r->_gt('Login');
614 push @body, $r->_gt($divert->{Message});
615 push @body, $r->_ch('gen_login_form', $params);
616 } elsif ($kind =~ m/^SMALLPAGE-/) {
617 $title = $r->_gt('Not logged in');
618 push @body, $r->_gt($divert->{Message});
619 push @body, $r->_ch('gen_login_link');
624 $r->_print($r->_ch('start_html',$title),
626 $r->_ch('end_html'));
631 my ($r, $bytes) = @_;
633 if (!$v->{RandomHandle}) {
634 my $rsp = $r->{S}{random_source};
635 my $rsf = new IO::File $rsp, '<' or die "$rsp $!";
636 $v->{RandomHandle} = $rsf;
640 read($rsf,$bin,$bytes) == $bytes or die "$rsp $!";
642 return unpack "H*", $bin;
645 sub _fresh_cookie ($) {
647 my $bytes = ($r->{S}{associdlen} + 7) >> 3;
648 return $r->_random($bytes);
651 sub check_mutate ($) {
653 die "unchecked" unless exists $r->{Divert};
655 my $meth = $r->_ch('get_method');
656 die "mutating non-POST" if $meth ne 'POST';
659 #---------- output ----------
664 return defined $r->{Assoc} ? $r->{Assoc} : '';
667 sub secret_hidden_html ($) {
669 return $r->{Cgi}->hidden(-name => $r->{S}{assoc_param_name},
670 -default => $r->secret_val());
673 sub secret_cookie ($) {
675 return $r->construct_cookie($r->secret_val());
682 CGI::Auth::Hybrid - web authentication optionally using cookies
686 my $verifier = CGI::Auth::Hybrid->new_verifier(setting => value,...);
687 my $authreq = $verifier->new_request($cgi_request_object);
689 my $authreq = CGI::Auth::Hybrid->new_request($cgi_request_object,
690 setting => value,...);
692 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
694 $authreq->check_ok() or return;
697 $authreq->check_mutate();
700 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
702 my $divert_kind = $authreq->check_divert();
704 if ($divert_kind eq 'LOGGEDOUT') {
705 print "goodbye you are now logged out" and quit
706 } elsif ($divert_kind eq 'NOCOOKIES') {
707 print "you need cookies" and quit
713 $authreq->check_mutate();