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/>.
22 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
27 %EXPORT_TAGS = ( ); # eg: TAG => [ qw!name1 name2! ],
29 @EXPORT_OK = qw(setup);
37 #---------- public utilities ----------
39 sub flatten_params ($) {
42 foreach my $k (keys %$p) {
43 foreach my $v (@{ $p->{$k} }) {
50 #---------- default callbacks ----------
52 sub has_a_param ($$) {
54 foreach my $pn (@{ $r->{S}{$cn} }) {
55 return 1 if $r->_cm('get_param')($pn);
63 foreach my $name ($c->param()) {
64 $p{$name} = [ $c->param($name) ];
69 sub get_cookie_domain ($$$) {
71 my $uri = new URI $r->_ch('get_url');
75 sub construct_cookie ($$$) {
77 return $r->{Cgi}->cookie(-name => $r->{S}{cookie_name},
79 -path => $r->{S}{cookie_path},
80 -domain => $r->_ch('get_cookie_domain'),
81 -expires => '+'.$r->{S}{login_timeout}.'s',
82 -secure => $r->{S}{encrypted_only});
85 sub do_redirect_cgi ($$$$) {
86 my ($c, $r, $new_url, $cookie) = @_;
87 my @ha = ('text/html',
88 -status => '303 See other',
89 -location => $new_url);
90 push @ha, (-cookie => $cookie) if defined $cookie;
91 $r->_print($c->header(@ha),
92 $r->_ch('gen_start_html')($r->_gt('Redirection')),
93 '<a href="'.escapeHTML($new_url).'">',
94 $r->_gt("If you aren't redirected, click to continue."),
96 $c->_ch('gen_end_html'));
99 sub gen_plain_login_form ($$) {
100 my ($c,$r, $params) = @_;
102 push @form, ('<form method="POST" action="'.
103 escapeHTML($r->_ch('get_url')).'>'.
105 my $sz = 'size="'.$r->{S}{form_entry_size}.'"';
106 foreach my $up (@{ $r->{S}{username_param_names}}) {
107 push @form, ('<tr><td>',$r->_gt(ucfirst $up),'</td>',
108 '<td><input type="text" ',$sz.
109 ' name=',$up,'></td></tr>');
111 push @form, ('<tr><td>'.$r->_gt('Password'),'</td>',
112 '<td><input type="password" '.$sz.
113 ' name="'.$r->{S}{password_param_name}.'"></td></tr>');
114 push @form, ('<tr><td colspan="2">',
115 '<input type="submit"'.
116 ' name="'.$r->{S}{login_submit_name}.'"'.
117 ' value="'.$r->_gt('Login').'"></td></tr>',
119 foreach my $n (keys %$params) {
120 push @form, ('<input type="hidden"'.
122 ' value="'.$params->{$n}.'">');
124 push @form, ('</form>');
125 return join "\n", @form;
128 sub gen_login_link ($$) {
129 my ($c,$r, $params) = @_;
130 my $url = $r->url_with_query_params($params);
131 return ('<a href="'.escapeHTML($url).'">'.
132 $r->_gt('Log in again to continue.').
136 #---------- verifier object methods ----------
142 assocdb_path => 'cah-assocs.db';
143 assocdb_dsn => undef,
145 assocdb_password => '',
146 assocdb_table => 'assocs',
147 random_source => '/dev/urandom',
148 associdlen => 128, # bits
149 login_timeout => 86400, # seconds
150 assoc_param_name => 'cah_associd',
151 password_param_name => 'password',
152 username_param_names => [qw(username)],
153 form_entry_size => 60,
154 logout_param_names => [qw(cah_logout)],
155 login_submit_name => [qw(cah_login)],
156 loggedout_param_names => [qw(cah_loggedout)],
157 promise_check_mutate => 0,
158 get_param => sub { $_[0]->param($_[2]) },
159 get_params => sub { $_[1]->get_params() },
160 get_cookie => sub { $_[0]->cookie($s->{S}{cookie_name}) },
161 get_method => sub { $_[0]->request_method() },
162 get_url => sub { $_[0]->url(); },
163 is_login => sub { defined $_[1]->_rp('password_param_name') },
164 login_ok => sub { die },
165 is_logout => sub { $_[1]->has_a_param('logout_param_names') },
166 is_loggedout => sub { $_[1]->has_a_param('loggedout_param_names') },
167 is_page => sub { return 1 },
168 handle_divert => sub { return 0 },
169 do_redirect => \&do_redirect_cgi, # this hook is allowed to throw
171 get_cookie_domain => \&get_cookie_domain,
173 gen_start_html => sub { $_[0]->start_html($_[2]); },
174 gen_end_html => sub { $_[0]->end_html(); },
175 gen_login_form => \&gen_plain_login_form,
176 gen_login_link => \&gen_plain_login_link,
177 gettext => sub { gettext($_[2]); },
183 while (($k,$v,@_) = @_) {
184 die "unknown setting $k" unless exists $s->{S}{$k};
197 $s->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=$s->{S}{assocdb_path}";
200 $dbh = DBI->open($s->{S}{assocdb_dsn}, $s->{S}{assocdb_user},
201 $s->{S}{assocdb_password}, {
202 AutoCommit => 0, RaiseError => 1,
204 die "${assocdb_dsn} $! ?" unless $dbh;
210 $dbh->do("CREATE TABLE $s->{S}{assocdb_table} (".
211 " associdh VARCHAR PRIMARY KEY,".
212 " username VARCHAR,".
213 " last INTEGER NOT NULL"
219 #---------- request object methods ----------
222 my ($classbase, $cgi, @extra) = @_;
223 if (!ref $classbase) {
224 $classbase = $classbase->new_verifier(@extra);
230 S => $classbase->{S},
231 Dbh => $classbase->{Dbh},
234 bless $r, ref $classbase;
237 sub _ch ($$@) { # calls an application hook
238 my ($r,$methname, @args) = @_;
239 my $methfunc = $r->{S}{$methname};
240 return $methfunc->($r->{Cgi}, $r, @args);
245 my $pn = $r->{S}{$pnvb};
246 my $p = scalar $r->_ch('get_param',$pn)
249 sub _gt ($$) { my ($r, $t) = @_; return $r->_ch('gettext')($t); }
250 sub _print ($$) { my ($r, @t) = @_; return $r->_ch('print')(join '', @t); }
252 # pages/param-sets are
253 # n normal non-mutating page
254 # r retrieval of information for JS, non-mutating
256 # u update of information by JS, mutating
259 # O "you have just logged out" page load
262 # a, aN anything including -
263 # t, tN temporary value (in our db, no logged in user yet)
264 # y, yN value corresponds to logged-in user
265 # n, nN value not in our db
267 # - no value supplied
268 # if N differs the case applies only when the two values differ
269 # (eg, a1 y2 does not apply when the logged-in value is supplied twice)
271 # "stale session" means request originates from a page from a login
272 # session which has been revoked (eg by logout); "cleared session"
273 # means request originates from a browser which has a different (or
276 # Case analysis, cookie mode, app promises re mutate:
277 # cook parm meth form
279 # any - POST nrmuoi bug or attack, fail
280 # any - GET rmuoi bug or attack, fail
281 # any any GET muoi bug or attack, fail
282 # any t any nrmu bug or attack, fail
284 # - - GET O "just logged out" page
285 # (any other) O bug or attack, fail
287 # a1 a2 POST o logout
288 # if a1 is valid, revoke it
289 # if a2 is valid, revoke it
291 # redirect to "just logged out" page
292 # (which contains link to login form)
294 # - t POST i complain about cookies being disabled
295 # (with link to login form)
297 # any n POST i complain about stale login form
298 # show new login form
300 # x1 t2 POST i login (or switch user)
302 # show new login form
304 # revoke x1 if it was valid and !=t2
305 # upgrade t2 to y2 in our db (setting username)
307 # redirect to GET of remaining params
309 # t1 a2 ANY nrmu treat as - a2 ANY
311 # y - GET n cross-site link
314 # y y GET nr fine, show page or send data
315 # y y POST nrmu mutation is OK, do operation
317 # y1 y2 GET nr request from stale page
318 # do not revoke y2 as not RESTful
321 # y1 y2 POST nrmu request from stale page
325 # y n GET n intra-site link from stale page,
326 # treat as cross-site link, show data
328 # y n POST n m intra-site form submission from stale page
329 # show "session interrupted"
330 # with link to main data page
332 # y n GET r intra-site request from stale page
335 # y n POST r u intra-site request from stale page
338 # -/n y2 GET nr intra-site link from cleared session
339 # do not revoke y2 as not RESTful
342 # -/n y2 POST nrmu request from cleared session
344 # treat as -/n n POST
346 # -/n n GET n cross-site link but user not logged in
347 # show login form with redirect to orig params
349 # -/n n GET rmu user not logged in
352 # -/n n POST n m user not logged in
355 # -/n n POST r u user not logged in
358 sub _check_divert_core ($) {
359 fixme needs wrapping with something to make and commit a transaction
360 wrapper should also store answers in the $r object for later retrieval
363 my $meth = $r->_ch('get_method');
364 my $cookv = $r->_ch('get_cookie');
365 my $parmv = $r->_rp('assoc_param_name');
367 my ($cookt,$cooku) = $r->_db_lookup($cookv);
368 my $parmt = $r->_db_lookup($parmv);
370 if ($r->_ch('is_logout')) {
373 $r->_db_revoke($cookv);
374 $r->_db_revoke($parmv);
375 return ({ Kind => 'REDIRECT-LOGGEDOUT',
376 Message => "Logging out...",
380 if ($r->_ch('is_loggedout')) {
381 die unless $meth eq 'GET';
384 return ({ Kind => 'SMALLPAGE-LOGGEDOUT',
385 Message => "You have been logged out.",
389 if ($r->_ch('is_login')) {
391 return ({ Kind => 'LOGIN-STALE',
392 Message => "Stale session; you need to log in again.",
393 CookieVal => $r->_fresh_cookie(),
396 die unless $parmt eq 't' || $parmt eq 'y';
397 return ({ Kind => 'SMALLPAGE-NOCOOKIE',
398 Message => "You do not seem to have cookies enabled. ".
399 "You must enable cookies as we use them for login.",
400 CookieVal => $r->_fresh_cookie(),
401 Params => $r->_chain_params() })
402 if !$cookt && $parmt eq 't';
403 my $username = $r->_ch('login_ok');
404 return ({ Kind => 'LOGIN-BAD',
405 Message => "Incorrect username/password.",
407 Params => $r->_chain_params() })
408 unless defined $username && length $username;
409 $r->_db_revoke($cookv)
410 if defined $cookv && !(defined $parmv && $cookv eq $parmv);
411 $r->_db_record_login_ok($parmv,$username);
412 return ({ Kind => 'REDIRECT-LOGGEDIN',
413 Message => "Logging in...",
415 Params => $r->_chain_params() });
420 die if $parmt eq 't';
422 if ($cookt eq 'y' && $parmt eq 'y' && $cookv ne $parmv) {
423 $r->_db_revoke($parmv) if $meth eq 'POST';
428 die unless !$cookt || $cookt eq 'n';
429 die unless !$parmt || $parmt eq 'n' || $parmt eq 'y';
430 if ($meth eq 'GET') {
431 return ({ Kind => 'LOGIN-INCOMINGLINK',
432 Message => "You need to log in again.",
434 Params => $r->_chain_params() });
436 return ((Kind => 'LOGIN-FRESH',
437 Message => "You need to log in again.",
443 if (!$r->{S}{promise_check_mutate}) {
444 if ($meth ne 'POST') {
445 return ({ Kind => 'MAINPAGEONLY',
446 Message => 'Entering via cross-site link.',
449 # NB caller must then ignore params & path!
450 # if this is too hard they can spit out a small form
451 # with a "click to continue"
455 die unless $cookt eq 'y';
456 die unless $parmt eq 'y';
457 die unless $cookv eq $parmv;
458 $r->{Assoc} = $cookv;
459 $r->{UserOK} = $cooku;
463 sub _chain_params ($) {
465 my %p = %{ $r->_ch('get_params') };
466 foreach my $pncn (keys %{ $r->{S} }) {
467 if ($pncn =~ m/_param_name$/) {
468 my $name = $r->{S}{$pncn};
469 die "$pncn ?" if ref $name;
471 } elsif ($pncn =~ m/_param_names$/) {
472 $names = $r->{S}{$pncn};
476 foreach my $param (@$names) {
483 sub _db_lookup ($$) {
484 # returns ($t,$username)
485 # where $t is one of "t" "y" "n", or "" (for -)
490 my ($nusername, $nlast) =
491 $dbh->selectrow_array("SELECT username, last".
492 " FROM $r->{S}{assocdb_table}".
493 " WHERE associd = ?", {}, $nassoc);
494 return ('') unless defined $nusername;
496 my $timeout = $r->{S}{login_timeout};
497 return ('n') unless !defined $timeout || time <= $nlast + $timeout;
499 return ('t') unless defined $nusername;
502 return ('y', $nusername);
505 sub _db_revoke ($$) {
506 # revokes $v if it's valid; no-op if it's not
511 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
512 " WHERE associd = ?", {}, $v);
515 sub _db_record_login_ok ($$$) {
516 my ($r,$v,$user) = @_;
518 $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
519 " (associd, username, last) VALUES (?,?,?)", {},
523 sub check_divert ($) {
526 if (exists $r->{Divert}) {
531 $divert = $r->_check_divert_core();
537 $r->{Divert} = $divert;
544 die "unchecked" unless exists $r->{Divert};
548 sub get_username ($) {
550 my $divert = $r->get_divert();
551 return undef if $divert;
555 sub url_with_query_params ($$) {
556 my ($r, $params) = @_;
557 my $uri = URI->new($r->_ch('get_url'));
558 $uri->query_form(flatten_params($params));
559 return $uri->as_string();
565 my ($divert) = $authreq->check_divert();
568 my $handled = $r->_ch('handle_divert')($divert);
569 return 0 if $handled;
571 my $kind = $divert->{Kind};
572 my $cookieval = $divert->{CookieVal};
573 my $params = $divert->{Params};
575 if ($kind =~ m/^REDIRECT-/) {
576 # for redirects, we honour stored NextParams and SetCookie,
577 # as we would for non-divert
578 if ($divert_kind eq 'REDIRECT-LOGGEDOUT') {
579 $params{$r->{S}{loggedout_param_names}[0]} = 1;
580 } elsif ($divert_kind eq 'REDIRECT-LOGOUT') {
581 $params{$r->{S}{logout_param_names}[0]} = 1;
582 } elsif ($divert_kind eq 'REDIRECT-LOGGEDIN') {
586 my $new_url = $r->url_with_query_params($params);
587 my $cookie = $r->construct_cookie($r, $cookieval);
588 $r->_ch('do_redirect')($new_url, $cookie);
593 if ($kind =~ m/^LOGIN-/) {
594 $title = $r->_gt('Login');
595 push @body, $r->_gt($divert->{Message});
596 push @body, $r->_ch('gen_login_form', $params);
597 } elsif ($kind =~ m/^SMALLPAGE-/) {
598 $title = $r->_gt('Not logged in');
599 push @body, $r->_gt($divert->{Message});
600 push @body, $r->_ch('gen_login_link');
605 $r->_print($r->_ch('start_html')($title),
607 $r->_ch('end_html'));
612 my ($r, $bytes) = @_;
614 if (!$v->{RandomHandle}) {
615 my $rsp = $r->{S}{random_source};
616 my $rsf = new IO::File $rsp, '<' or die "$rsp $!";
617 $v->{RandomHandle} = $rsf;
621 read($rsf,$bin,$bytes) == $bytes or die "$rsp $!";
623 return unpack "H*", $bin;
626 sub _fresh_cookie ($) {
628 my $bytes = ($r->{S}{associdlen} + 7) >> 3;
629 return $r->_random($bytes);
632 sub check_mutate ($) {
634 die "unchecked" unless exists $r->{Divert};
636 my $meth = $r->_ch('get_method');
637 die "mutating non-POST" if $meth ne 'POST';
640 #---------- output ----------
645 return defined $r->{Assoc} ? $r->{Assoc} : '';
648 sub secret_hidden_html ($) {
650 return $r->{Cgi}->hidden(-name => $r->{S}{assoc_param_name},
651 -default => $r->secret_val());
654 sub secret_cookie ($) {
656 return $r->construct_cookie($r->secret_val());
663 CGI::Auth::Hybrid - web authentication optionally using cookies
667 my $verifier = CGI::Auth::Hybrid->new_verifier(setting => value,...);
668 my $authreq = $verifier->new_request($cgi_request_object);
670 my $authreq = CGI::Auth::Hybrid->new_request($cgi_request_object,
671 setting => value,...);
673 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
675 $authreq->check_ok() or return;
678 $authreq->check_mutate();
681 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
683 my $divert_kind = $authreq->check_divert();
685 if ($divert_kind eq 'LOGGEDOUT') {
686 print "goodbye you are now logged out" and quit
687 } elsif ($divert_kind eq 'NOCOOKIES') {
688 print "you need cookies" and quit
694 $authreq->check_mutate();