3 # This is part of CGI::Auth::Hybrid, a perl CGI authentication module.
4 # Copyright (C) 2012 Ian Jackson.
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU Affero General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU Affero General Public License for more details.
16 # You should have received a copy of the GNU Affero General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
26 %EXPORT_TAGS = ( ); # eg: TAG => [ qw!name1 name2! ],
28 @EXPORT_OK = qw(setup);
35 #---------- default callbacks ----------
37 sub has_a_param ($$) {
39 foreach my $pn (@{ $r->{S}{$cn} }) {
40 return 1 if $r->_cm('get_param')($pn);
45 sub get_param_list ($$) {
48 foreach my $name ($c->param()) {
49 foreach my $val ($c->param($name)) {
56 sub get_cookie_domain ($$$) {
58 my $uri = new URI $r->_ch('get_url');
62 sub construct_cookie ($$$) {
63 my ($c, $r, $cookv) = @_;
64 return $c->cookie(-name => $r->{S}{cookie_name},
66 -path => $r->{S}{cookie_path},
67 -domain => $r->_ch('get_cookie_domain'),
68 -expires => '+'.$r->{S}{login_timeout}.'s',
69 -secure => $r->{S}{encrypted_only});
72 sub do_redirect_cgi ($$$$) {
73 my ($c, $r, $new_url, $cookie) = @_;
74 my @ha = ('text/html',
75 -status => '303 See other',
76 -location => $new_url);
77 push @ha, (-cookie => $cookie) if defined $cookie;
78 $r->_ch('print')($c->header(@ha).
79 $c->start_html('Redirection').
80 $c->a({href=>$new_url},
81 "If you aren't redirected, click to continue.").
85 #---------- verifier object methods ----------
91 assocdb_path => 'cah-assocs.db';
94 assocdb_password => '',
95 assocdb_table => 'assocs',
96 random_source => '/dev/urandom',
97 associdlen => 128, # bits
98 login_timeout => 86400, # seconds
99 assoc_param_name => 'cah_associd',
100 password_param_name => 'password',
101 logout_param_names => [qw(cah_logout)],
102 loggedout_param_names => [qw(cah_loggedout)],
103 promise_check_mutate => 0,
104 get_param => sub { $_[0]->param($_[2]) },
105 get_param_list => sub { $_[1]->get_param_list() },
106 get_cookie => sub { $_[0]->cookie($s->{S}{cookie_name}) },
107 get_method => sub { $_[0]->request_method() },
108 get_url => sub { $_[0]->url(); },
109 is_login => sub { defined $_[1]->_rp('password_param_name') },
110 login_ok => sub { die },
111 is_logout => sub { $_[1]->has_a_param('logout_param_names') },
112 is_loggedout => sub { $_[1]->has_a_param('loggedout_param_names') },
113 is_page => sub { return 1 },
114 handle_divert => sub { return 0 },
115 do_redirect => \&do_redirect_cgi, # this hook is allowed to throw
117 get_cookie_domain => \&get_cookie_domain,
124 while (($k,$v,@_) = @_) {
125 die "unknown setting $k" unless exists $s->{S}{$k};
138 $s->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=$s->{S}{assocdb_path}";
141 $dbh = DBI->open($s->{S}{assocdb_dsn}, $s->{S}{assocdb_user},
142 $s->{S}{assocdb_password}, {
143 AutoCommit => 0, RaiseError => 1,
145 die "${assocdb_dsn} $! ?" unless $dbh;
151 $dbh->do("CREATE TABLE $s->{S}{assocdb_table} (".
152 " associdh VARCHAR PRIMARY KEY,".
153 " username VARCHAR,".
154 " last INTEGER NOT NULL"
160 #---------- request object methods ----------
163 my ($classbase, $cgi, @extra) = @_;
164 if (!ref $classbase) {
165 $classbase = $classbase->new_verifier(@extra);
170 S => $classbase->{S},
171 Dbh => $classbase->{Dbh},
174 bless $r, ref $classbase;
177 sub _ch ($$@) { # calls an application hook
178 my ($r,$methname, @args) = @_;
179 my $methfunc = $r->{S}{$methname};
180 return $methfunc->($r->{Cgi}, $r, @args);
185 my $pn = $r->{S}{$pnvb};
186 my $p = scalar $r->_ch('get_param',$pn)
189 # pages/param-sets are
190 # n normal non-mutating page
191 # r retrieval of information for JS, non-mutating
193 # u update of information by JS, mutating
196 # O "you have just logged out" page load
199 # a, aN anything including -
200 # t, tN temporary value (in our db, no logged in user yet)
201 # y, yN value corresponds to logged-in user
202 # n, nN value not in our db
204 # - no value supplied
205 # if N differs the case applies only when the two values differ
206 # (eg, a1 y2 does not apply when the logged-in value is supplied twice)
208 # "stale session" means request originates from a page from a login
209 # session which has been revoked (eg by logout); "cleared session"
210 # means request originates from a browser which has a different (or
213 # Case analysis, cookie mode, app promises re mutate:
214 # cook parm meth form
216 # any - POST nrmuoi bug or attack, fail
217 # any - GET rmuoi bug or attack, fail
218 # any any GET muoi bug or attack, fail
219 # any t any nrmu bug or attack, fail
221 # - - GET O "just logged out" page
222 # (any other) O bug or attack, fail
224 # a1 a2 POST o logout
225 # if a1 is valid, revoke it
226 # if a2 is valid, revoke it
228 # redirect to "just logged out" page
229 # (which contains link to login form)
231 # - t POST i complain about cookies being disabled
232 # (with link to login form)
234 # any n POST i complain about stale login form
235 # show new login form
237 # x1 t2 POST i login (or switch user)
239 # show new login form
241 # revoke x1 if it was valid and !=t2
242 # upgrade t2 to y2 in our db (setting username)
244 # redirect to GET of remaining params
246 # t1 a2 ANY nrmu treat as - a2 ANY
248 # y - GET n cross-site link
251 # y y GET nr fine, show page or send data
252 # y y POST nrmu mutation is OK, do operation
254 # y1 y2 GET nr request from stale page
255 # do not revoke y2 as not RESTful
258 # y1 y2 POST nrmu request from stale page
262 # y n GET n intra-site link from stale page,
263 # treat as cross-site link, show data
265 # y n POST n m intra-site form submission from stale page
266 # show "session interrupted"
267 # with link to main data page
269 # y n GET r intra-site request from stale page
272 # y n POST r u intra-site request from stale page
275 # -/n y2 GET nr intra-site link from cleared session
276 # do not revoke y2 as not RESTful
279 # -/n y2 POST nrmu request from cleared session
281 # treat as -/n n POST
283 # -/n n GET n cross-site link but user not logged in
284 # show login form with redirect to orig params
286 # -/n n GET rmu user not logged in
289 # -/n n POST n m user not logged in
292 # -/n n POST r u user not logged in
295 sub _check_divert_core ($) {
296 fixme needs wrapping with something to make and commit a transaction
299 my $meth = $r->_ch('get_method');
300 my $cookv = $r->_ch('get_cookie');
301 my $parmv = $r->_rp('assoc_param_name');
303 my ($cookt,$cooku) = $r->_db_lookup($cookv);
304 my $parmt = $r->_db_lookup($parmv);
306 if ($r->_ch('is_logout')) {
309 $r->_db_revoke($cookv);
310 $r->_db_revoke($parmv);
311 return ({ Kind => 'REDIRECT/LOGGEDOUT',
312 Message => "Logging out...",
316 if ($r->_ch('is_loggedout')) {
317 die unless $meth eq 'GET';
320 return ({ Kind => 'SMALLPAGE/LOGGEDOUT',
321 Message => "You have been logged out.",
325 if ($r->_ch('is_login')) {
327 return ({ Kind => 'LOGIN-STALE',
328 Message => "Stale session; you need to log in again.",
329 Cookie => $r->_fresh_cookie(),
332 die unless $parmt eq 't' || $parmt eq 'y';
333 return ({ Kind => 'SMALLPAGE-NOCOOKIE',
334 Message => "You do not seem to have cookies enabled. ".
335 "You must enable cookies as we use them for login.",
336 Cookie => $r->_fresh_cookie(),
337 Params => $r->_chain_params() })
338 if !$cookt && $parmt eq 't';
339 return ({ Kind => 'LOGIN-BAD',
340 Message => "Incorrect username/password.",
342 Params => $r->_chain_params() })
343 unless defined $username && length $username;
344 $r->_db_revoke($cookv)
345 if defined $cookv && !(defined $parmv && $cookv eq $parmv);
346 my $username = $r->_ch('login_ok');
347 $r->_db_record_login_ok($parmv,$username);
348 return ({ Kind => 'REDIRECT-LOGGEDIN',
349 Message => "Logging in...",
351 Params => $r->_chain_params() });
356 die if $parmt eq 't';
358 if ($cookt eq 'y' && $parmt eq 'y' && $cookv ne $parmv) {
359 $r->_db_revoke($parmv) if $meth eq 'POST';
364 die unless !$cookt || $cookt eq 'n';
365 die unless !$parmt || $parmt eq 'n' || $parmt eq 'y';
366 if ($meth eq 'GET') {
367 return ({ Kind => 'LOGIN-INCOMINGLINK',
368 Message => "You need to log in again.",
370 Params => $r->_chain_params() });
372 return ((Kind => 'LOGIN-FRESH',
373 Message => "You need to log in again.",
379 if (!$r->{S}{promise_check_mutate}) {
380 if ($meth ne 'POST') {
381 return ({ Kind => 'MAINPAGEONLY',
382 Message => 'Entering via cross-site link.',
385 # NB caller must then ignore params & path!
386 # if this is too hard they can spit out a small form
387 # with a "click to continue"
391 die unless $cookt eq 'y';
392 die unless $parmt eq 'y';
393 die unless $cookv eq $parmv;
394 $r->{UserOK} = $cooku;
398 sub _chain_params ($) {
401 foreach my $pncn (keys %{ $r->{S} }) {
402 if ($pncn =~ m/_param_name$/) {
403 my $name = $r->{S}{$pncn};
404 die "$pncn ?" if ref $name;
406 } elsif ($pncn =~ m/_param_names$/) {
407 $names = $r->{S}{$pncn};
411 foreach my $param (@$names) {
415 my @p = $r->_ch('get_param_list');
419 ($name,$val,@p) = @p;
420 next if $elim{$name};
421 push @q, $name, $val;
426 sub _db_lookup ($$) {
427 # returns ($t,$username)
428 # where $t is one of "t" "y" "n", or "" (for -)
433 my ($nusername, $nlast) =
434 $dbh->selectrow_array("SELECT username, last".
435 " FROM $r->{S}{assocdb_table}".
436 " WHERE associd = ?", {}, $nassoc);
437 return ('') unless defined $nusername;
439 my $timeout = $r->{S}{login_timeout};
440 return ('n') unless !defined $timeout || time <= $nlast + $timeout;
442 return ('t') unless defined $nusername;
445 return ('y', $nusername);
448 sub _db_revoke ($$) {
449 # revokes $v if it's valid; no-op if it's not
454 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
455 " WHERE associd = ?", {}, $v);
458 sub _db_record_login_ok ($$$) {
459 my ($r,$v,$user) = @_;
461 $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
462 " (associd, username, last) VALUES (?,?,?)", {},
466 sub url_with_query_params ($@) {
467 my ($r, @params) = @_;
468 my $uri = URI->new($r->_ch('get_url'));
469 $uri->query_form(\@params);
470 return $uri->as_string();
476 my ($divert) = $authreq->check_divert();
479 my $handled = $r->_ch('handle_divert')($divert);
480 return 0 if $handled;
482 my $kind = $divert->{Kind};
483 my $cookie = $divert->{Cookie};
484 my $params = $divert->{Params};
486 if ($kind =~ m#^REDIRECT/#) {
487 # for redirects, we honour stored NextParams and SetCookie,
488 # as we would for non-divert
489 if ($divert_kind eq 'REDIRECT-LOGGEDOUT') {
490 push @$params, $r->{S}{cah_loggedout}[0], 1;
491 } elsif ($divert_kind eq 'REDIRECT-LOGOUT') {
492 push @$params, $r->{S}{cah_logout}[0], 1;
493 } elsif ($divert_kind eq 'REDIRECT-LOGGEDIN') {
497 my $new_url = $r->url_with_query_params(@$params);
498 $r->_ch('do_redirect')($new_url, $cookie);
503 if (defined $cookie) {
504 $r->_ch('header_out')($cookie);
509 sub record_login ($$) {
510 my ($r,$nusername) = @_;
511 my $rsp = $r->{S}{random_source};
512 my $rsf = new IO::File $rsp, '<' or die "$rsp $!";
513 my $bytes = ($r->{S}{associdlen} + 7) >> 3;
516 read($rsf,$nassocbin,$bytes) == $bytes or die "$rsp $!";
518 my $nassoc = unpack "H*", $nassocbin;
520 $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
521 " (associd, username, last) VALUES (?,?,?)", {},
522 $nassoc, $nusername, time);
524 $r->{U} = $nusername;
531 return if exists $r->{Username};
532 ($r->{Username}, $r->{Assoc}, $r->{Mutate}) = $r->_check();
534 if (defined $r->{Assoc}) {
535 $dbh->do("UPDATE $r->{S}{assocdb_table}".
537 " WHERE associd = ?", {}, time, $nassoc);
545 my ($nusername, $nassoc, $nmutate) = $r->_check();
546 return undef unless $nmutate;
547 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
548 " WHERE associd = ?", {}, $nassoc);
556 return !!defined $r->{Username};
559 sub check_mutate ($) {
568 return $r->{Username};
573 return defined $r->{Assoc} ? $r->{Assoc} : '';
576 #---------- simple wrappers ----------
578 sub hidden_hargs ($) {
580 return (-name => $r->{S}{param_name},
581 -default => $r->hidden_val());
584 sub hidden_html ($) {
586 return hidden($r->hidden_hargs());
589 sub cookiea_cargs ($) {
591 return (-name => $r->{S}{cookie_name},
592 -value => hidden_val());
599 CGI::Auth::Hybrid - web authentication optionally using cookies
603 my $verifier = CGI::Auth::Hybrid->new_verifier(setting => value,...);
604 my $authreq = $verifier->new_request($cgi_request_object);
606 my $authreq = CGI::Auth::Hybrid->new_request($cgi_request_object,
607 setting => value,...);
609 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
611 $authreq->check_ok() or return;
614 $authreq->mutating();
617 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
619 my $divert_kind = $authreq->check_divert();
621 if ($divert_kind eq 'LOGGEDOUT') {
622 print "goodbye you are now logged out" and quit
623 } elsif ($divert_kind eq 'NOCOOKIES') {
624 print "you need cookies" and quit