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 #---------- verifier object methods ----------
62 assocdb_path => 'cah-assocs.db';
65 assocdb_password => '',
66 assocdb_table => 'assocs',
67 random_source => '/dev/urandom',
68 associdlen => 128, # bits
69 login_timeout => 86400, # seconds
70 assoc_param_name => 'cah_associd',
71 password_param_name => 'password',
72 logout_param_names => [qw(cah_logout)],
73 loggedout_param_names => [qw(cah_loggedout)],
74 promise_check_mutate => 0,
75 get_param => sub { $_[0]->param($_[2]) },
76 get_param_list => sub { $_[1]->get_param_list() },
77 get_cah_cookie => sub { $_[0]->cookie($s->{S}{cookie_name}) },
78 get_method => sub { $_[0]->request_method() },
79 get_url => sub { $_[0]->url(); },
80 is_login => sub { defined $_[1]->_rp('password_param_name') },
81 login_ok => sub { die },
82 is_logout => sub { $_[1]->has_a_param('logout_param_names') },
83 is_loggedout => sub { $_[1]->has_a_param('loggedout_param_names') },
84 is_page => sub { return 1 },
89 while (($k,$v,@_) = @_) {
90 die "unknown setting $k" unless exists $s->{S}{$k};
103 $s->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=$s->{S}{assocdb_path}";
106 $dbh = DBI->open($s->{S}{assocdb_dsn}, $s->{S}{assocdb_user},
107 $s->{S}{assocdb_password}, {
108 AutoCommit => 0, RaiseError => 1,
110 die "${assocdb_dsn} $! ?" unless $dbh;
116 $dbh->do("CREATE TABLE $s->{S}{assocdb_table} (".
117 " associdh VARCHAR PRIMARY KEY,".
118 " username VARCHAR,".
119 " last INTEGER NOT NULL"
125 #---------- request object methods ----------
128 my ($classbase, $cgi, @extra) = @_;
129 if (!ref $classbase) {
130 $classbase = $classbase->new_verifier(@extra);
135 S => $classbase->{S},
136 Dbh => $classbase->{Dbh},
139 bless $r, ref $classbase;
142 sub _ch ($$@) { # calls an application hook
143 my ($r,$methname, @args) = @_;
144 my $methfunc = $r->{S}{$methname};
145 return $methfunc->($r->{Cgi}, $r, @args);
150 my $pn = $r->{S}{$pnvb};
151 my $p = scalar $r->_ch('get_param',$pn)
154 # pages/param-sets are
155 # n normal non-mutating page
156 # r retrieval of information for JS, non-mutating
158 # u update of information by JS, mutating
161 # O "you have just logged out" page load
164 # a, aN anything including -
165 # t, tN temporary value (in our db, no logged in user yet)
166 # y, yN value corresponds to logged-in user
167 # n, nN value not in our db
169 # - no value supplied
170 # if N differs the case applies only when the two values differ
171 # (eg, a1 y2 does not apply when the logged-in value is supplied twice)
173 # "stale session" means request originates from a page from a login
174 # session which has been revoked (eg by logout); "cleared session"
175 # means request originates from a browser which has a different (or
178 # Case analysis, cookie mode, app promises re mutate:
179 # cook parm meth form
181 # any - POST nrmuoi bug or attack, fail
182 # any - GET rmuoi bug or attack, fail
183 # any any GET muoi bug or attack, fail
184 # any t any nrmu bug or attack, fail
186 # - - GET O "just logged out" page
187 # (any other) O bug or attack, fail
189 # a1 a2 POST o logout
190 # if a1 is valid, revoke it
191 # if a2 is valid, revoke it
193 # redirect to "just logged out" page
194 # (which contains link to login form)
196 # - t POST i complain about cookies being disabled
197 # (with link to login form)
199 # any n POST i complain about stale login form
200 # show new login form
202 # x1 t2 POST i login (or switch user)
204 # show new login form
206 # revoke x1 if it was valid and !=t2
207 # upgrade t2 to y2 in our db (setting username)
209 # redirect to GET of remaining params
211 # t1 a2 ANY nrmu treat as - a2 ANY
213 # y - GET n cross-site link
216 # y y GET nr fine, show page or send data
217 # y y POST nrmu mutation is OK, do operation
219 # y1 y2 GET nr request from stale page
220 # do not revoke y2 as not RESTful
223 # y1 y2 POST nrmu request from stale page
227 # y n GET n intra-site link from stale page,
228 # treat as cross-site link, show data
230 # y n POST n m intra-site form submission from stale page
231 # show "session interrupted"
232 # with link to main data page
234 # y n GET r intra-site request from stale page
237 # y n POST r u intra-site request from stale page
240 # -/n y2 GET nr intra-site link from cleared session
241 # do not revoke y2 as not RESTful
244 # -/n y2 POST nrmu request from cleared session
246 # treat as -/n n POST
248 # -/n n GET n cross-site link but user not logged in
249 # show login form with redirect to orig params
251 # -/n n GET rmu user not logged in
254 # -/n n POST n m user not logged in
257 # -/n n POST r u user not logged in
260 sub _check_divert_core ($) {
261 fixme needs wrapping with something to make and commit a transaction
264 my $meth = $r->_ch('get_method');
265 my $cookv = $r->_ch('get_cah_cookie');
266 my $parmv = $r->_rp('assoc_param_name');
268 my ($cookt,$cooku) = $r->_db_lookup($cookv);
269 my $parmt = $r->_db_lookup($parmv);
271 if ($r->_ch('is_logout')) {
274 $r->_db_revoke($cookv);
275 $r->_db_revoke($parmv);
276 return ({ Kind => 'REDIRECT/LOGGEDOUT',
277 Message => "Logging out...",
281 if ($r->_ch('is_loggedout')) {
282 die unless $meth eq 'GET';
285 return ({ Kind => 'SMALLPAGE/LOGGEDOUT',
286 Message => "You have been logged out.",
290 if ($r->_ch('is_login')) {
292 return ({ Kind => 'LOGIN-STALE',
293 Message => "Stale session; you need to log in again.",
294 Cookie => $r->_fresh_cookie(),
297 die unless $parmt eq 't' || $parmt eq 'y';
298 return ({ Kind => 'SMALLPAGE-NOCOOKIE',
299 Message => "You do not seem to have cookies enabled. ".
300 "You must enable cookies as we use them for login.",
301 Cookie => $r->_fresh_cookie(),
302 Params => $r->_chain_params() })
303 if !$cookt && $parmt eq 't';
304 return ({ Kind => 'LOGIN-BAD',
305 Message => "Incorrect username/password.",
307 Params => $r->_chain_params() })
308 unless defined $username && length $username;
309 $r->_db_revoke($cookv)
310 if defined $cookv && !(defined $parmv && $cookv eq $parmv);
311 my $username = $r->_ch('login_ok');
312 $r->_db_record_login_ok($parmv,$username);
313 return ({ Kind => 'REDIRECT-LOGGEDIN',
314 Message => "Logging in...",
316 Params => $r->_chain_params() });
321 die if $parmt eq 't';
323 if ($cookt eq 'y' && $parmt eq 'y' && $cookv ne $parmv) {
324 $r->_db_revoke($parmv) if $meth eq 'POST';
329 die unless !$cookt || $cookt eq 'n';
330 die unless !$parmt || $parmt eq 'n' || $parmt eq 'y';
331 if ($meth eq 'GET') {
332 return ({ Kind => 'LOGIN-INCOMINGLINK',
333 Message => "You need to log in again.",
335 Params => $r->_chain_params() });
337 return ((Kind => 'LOGIN-FRESH',
338 Message => "You need to log in again.",
344 if (!$r->{S}{promise_check_mutate}) {
345 if ($meth ne 'POST') {
346 return ({ Kind => 'MAINPAGEONLY',
347 Message => 'Entering via cross-site link.',
350 # NB caller must then ignore params & path!
351 # if this is too hard they can spit out a small form
352 # with a "click to continue"
356 die unless $cookt eq 'y';
357 die unless $parmt eq 'y';
358 die unless $cookv eq $parmv;
359 $r->{UserOK} = $cooku;
363 sub _chain_params ($) {
366 foreach my $pncn (keys %{ $r->{S} }) {
367 if ($pncn =~ m/_param_name$/) {
368 my $name = $r->{S}{$pncn};
369 die "$pncn ?" if ref $name;
371 } elsif ($pncn =~ m/_param_names$/) {
372 $names = $r->{S}{$pncn};
376 foreach my $param (@$names) {
380 my @p = $r->_ch('get_param_list');
384 ($name,$val,@p) = @p;
385 next if $elim{$name};
386 push @q, $name, $val;
391 sub _db_lookup ($$) {
392 # returns ($t,$username)
393 # where $t is one of "t" "y" "n", or "" (for -)
398 my ($nusername, $nlast) =
399 $dbh->selectrow_array("SELECT username, last".
400 " FROM $r->{S}{assocdb_table}".
401 " WHERE associd = ?", {}, $nassoc);
402 return ('') unless defined $nusername;
404 my $timeout = $r->{S}{login_timeout};
405 return ('n') unless !defined $timeout || time <= $nlast + $timeout;
407 return ('t') unless defined $nusername;
410 return ('y', $nusername);
413 sub _db_revoke ($$) {
414 # revokes $v if it's valid; no-op if it's not
419 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
420 " WHERE associd = ?", {}, $v);
423 sub _db_record_login_ok ($$$) {
424 my ($r,$v,$user) = @_;
426 $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
427 " (associd, username, last) VALUES (?,?,?)", {},
431 sub url_with_query_params ($@) {
432 my ($r, @params) = @_;
433 my $uri = URI->new($r->_ch('get_url'));
434 $uri->query_form(\@params);
435 return $uri->as_string();
441 my ($divert) = $authreq->check_divert();
444 my $kind = $divert->{Kind};
445 my $cookie = $divert->{Cookie};
446 my $params = $divert->{Params};
448 if (defined $cookie) {
449 $r->_ch('header_out')($cookie);
451 if ($kind =~ m/^REDIRECT-/) {
452 # for redirects, we honour stored NextParams and SetCookie,
453 # as we would for non-divert
454 my $new_url = $r->_ch('get_url');
455 if ($divert_kind eq 'REDIRECT-LOGGEDOUT') {
456 push @$params, $r->{S}{cah_loggedout}[0], 1;
457 } elsif ($divert_kind eq 'REDIRECT-LOGOUT') {
458 push @$params, $r->{S}{cah_logout}[0], 1;
459 } elsif ($divert_kind eq 'REDIRECT-LOGGEDIN') {
464 sub record_login ($$) {
465 my ($r,$nusername) = @_;
466 my $rsp = $r->{S}{random_source};
467 my $rsf = new IO::File $rsp, '<' or die "$rsp $!";
468 my $bytes = ($r->{S}{associdlen} + 7) >> 3;
471 read($rsf,$nassocbin,$bytes) == $bytes or die "$rsp $!";
473 my $nassoc = unpack "H*", $nassocbin;
475 $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
476 " (associd, username, last) VALUES (?,?,?)", {},
477 $nassoc, $nusername, time);
479 $r->{U} = $nusername;
486 return if exists $r->{Username};
487 ($r->{Username}, $r->{Assoc}, $r->{Mutate}) = $r->_check();
489 if (defined $r->{Assoc}) {
490 $dbh->do("UPDATE $r->{S}{assocdb_table}".
492 " WHERE associd = ?", {}, time, $nassoc);
500 my ($nusername, $nassoc, $nmutate) = $r->_check();
501 return undef unless $nmutate;
502 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
503 " WHERE associd = ?", {}, $nassoc);
511 return !!defined $r->{Username};
514 sub check_mutate ($) {
523 return $r->{Username};
528 return defined $r->{Assoc} ? $r->{Assoc} : '';
531 #---------- simple wrappers ----------
533 sub hidden_hargs ($) {
535 return (-name => $r->{S}{param_name},
536 -default => $r->hidden_val());
539 sub hidden_html ($) {
541 return hidden($r->hidden_hargs());
544 sub cookiea_cargs ($) {
546 return (-name => $r->{S}{cookie_name},
547 -value => hidden_val());
554 CGI::Auth::Hybrid - web authentication optionally using cookies
558 my $verifier = CGI::Auth::Hybrid->new_verifier(setting => value,...);
559 my $authreq = $verifier->new_request($cgi_request_object);
561 my $authreq = CGI::Auth::Hybrid->new_request($cgi_request_object,
562 setting => value,...);
564 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
566 $authreq->check_ok() or return;
569 $authreq->mutating();
572 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
574 my $divert_kind = $authreq->check_divert();
576 if ($divert_kind eq 'LOGGEDOUT') {
577 print "goodbye you are now logged out" and quit
578 } elsif ($divert_kind eq 'NOCOOKIES') {
579 print "you need cookies" and quit