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 #---------- verifier object methods ----------
51 assocdb_path => 'cah-assocs.db';
54 assocdb_password => '',
55 assocdb_table => 'assocs',
56 random_source => '/dev/urandom',
57 associdlen => 128, # bits
58 login_timeout => 86400, # seconds
59 assoc_param_name => 'cah_associd',
60 password_param_name => 'password',
61 logout_param_names => [qw(cah_logout)],
62 loggedout_param_names => [qw(cah_loggedout)],
63 promise_check_mutate => 0,
64 get_param => sub { $_[0]->param($_[2]) },
65 get_cah_cookie => sub { $_[0]->cookie($s->{S}{cookie_name}) },
66 get_method => sub { $_[0]->request_method() },
67 is_login => sub { defined $_[1]->_rp('password_param_name') },
68 login_ok => sub { die },
69 is_logout => sub { $_[1]->has_a_param('logout_param_names') },
70 is_loggedout => sub { $_[1]->has_a_param('loggedout_param_names') },
71 is_page => sub { return 1 },
76 while (($k,$v,@_) = @_) {
77 die "unknown setting $k" unless exists $s->{S}{$k};
90 $s->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=$s->{S}{assocdb_path}";
93 $dbh = DBI->open($s->{S}{assocdb_dsn}, $s->{S}{assocdb_user},
94 $s->{S}{assocdb_password}, {
95 AutoCommit => 0, RaiseError => 1,
97 die "${assocdb_dsn} $! ?" unless $dbh;
103 $dbh->do("CREATE TABLE $s->{S}{assocdb_table} (".
104 " associdh VARCHAR PRIMARY KEY,".
105 " username VARCHAR,".
106 " last INTEGER NOT NULL"
112 #---------- request object methods ----------
115 my ($classbase, $cgi, @extra) = @_;
116 if (!ref $classbase) {
117 $classbase = $classbase->new_verifier(@extra);
122 S => $classbase->{S},
123 Dbh => $classbase->{Dbh},
126 bless $r, ref $classbase;
129 sub _ch ($$@) { # calls an application hook
130 my ($r,$methname, @args) = @_;
131 my $methfunc = $r->{S}{$methname};
132 return $methfunc->($r->{Cgi}, $r, @args);
137 my $pn = $r->{S}{$pnvb};
138 my $p = $r->_ch('get_param',$pn)
141 # pages/param-sets are
142 # n normal non-mutating page
143 # r retrieval of information for JS, non-mutating
145 # u update of information by JS, mutating
148 # O "you have just logged out" page load
151 # a, aN anything including -
152 # t, tN temporary value (in our db, no logged in user yet)
153 # y, yN value corresponds to logged-in user
154 # n, nN value not in our db
156 # - no value supplied
157 # if N differs the case applies only when the two values differ
158 # (eg, a1 y2 does not apply when the logged-in value is supplied twice)
160 # "stale session" means request originates from a page from a login
161 # session which has been revoked (eg by logout); "cleared session"
162 # means request originates from a browser which has a different (or
165 # Case analysis, cookie mode, app promises re mutate:
166 # cook parm meth form
168 # any - POST nrmuoi bug or attack, fail
169 # any - GET rmuoi bug or attack, fail
170 # any any GET muoi bug or attack, fail
171 # any t any nrmu bug or attack, fail
173 # - - GET O "just logged out" page
174 # (any other) O bug or attack, fail
176 # a1 a2 POST o logout
177 # if a1 is valid, revoke it
178 # if a2 is valid, revoke it
180 # redirect to "just logged out" page
181 # (which contains link to login form)
183 # - t POST i complain about cookies being disabled
184 # (with link to login form)
186 # any n POST i complain about stale login form
187 # show new login form
189 # x1 t2 POST i login (or switch user)
191 # show new login form
193 # revoke x1 if it was valid and !=t2
194 # upgrade t2 to y2 in our db (setting username)
196 # redirect to GET of remaining params
198 # t1 a2 ANY nrmu treat as - a2 ANY
200 # y - GET n cross-site link
203 # y y GET nr fine, show page or send data
204 # y y POST nrmu mutation is OK, do operation
206 # y1 y2 GET nr request from stale page
207 # do not revoke y2 as not RESTful
210 # y1 y2 POST nrmu request from stale page
214 # y n GET n intra-site link from stale page,
215 # treat as cross-site link, show data
217 # y n POST n m intra-site form submission from stale page
218 # show "session interrupted"
219 # with link to main data page
221 # y n GET r intra-site request from stale page
224 # y n POST r u intra-site request from stale page
227 # -/n y2 GET nr intra-site link from cleared session
228 # do not revoke y2 as not RESTful
231 # -/n y2 POST nrmu request from cleared session
233 # treat as -/n n POST
235 # -/n n GET n cross-site link but user not logged in
236 # show login form with redirect to orig params
238 # -/n n GET rmu user not logged in
241 # -/n n POST n m user not logged in
244 # -/n n POST r u user not logged in
247 sub check_divert ($) {
250 my $meth = $r->_ch('get_method');
251 my $cookv = $r->_ch('get_cah_cookie');
252 my $parmv = $r->_rp('assoc_param_name');
254 my $cookt = $r->_db_lookup($cookv);
255 my $parmt = $r->_db_lookup($parmv);
257 if ($r->_ch('is_logout')) {
260 $r->_db_perhaps_revoke($cookv);
261 $r->_db_perhaps_revoke($parmv);
262 $r->_queue_set_cookie('');
263 return 'REDIRECT-LOGGEDOUT'
265 if ($r->_ch('is_loggedout')) {
266 die unless $meth eq 'GET';
269 return ('SMALLPAGE-LOGGEDOUT', "You have been logged out.");
271 if ($r->_ch('is_login')) {
273 return ('LOGIN-STALE',
274 "This session was stale and you need to log in again.")
276 die unless $parmt eq 't' || $parmt eq 'y';
277 $r->_queue_preserve_params();
278 return ('SMALLPAGE-NOCOOKIE',
279 "You do not seem to have cookies enabled. ".
280 "You must enable cookies as we use them for login.")
281 if !$cookt && $parmt eq 't';
283 "Incorrect username/password.")
284 unless defined $username && length $username;
285 $r->_db_perhaps_revoke($cookv)
286 if defined $cookv && !(defined $parmv && $cookv eq $parmv);
287 $r->_queue_set_cookie($parmv);
288 my $username = $r->_ch('login_ok');
289 $r->_db_record_login_ok($parmv,$username);
290 return 'REDIRECT-LOGGEDIN';
292 if (!$r->{S}{promise_check_mutate}) {
293 if ($meth ne 'POST') {
294 return 'MAINPAGEONLY';
295 # NB caller must then ignore params & path!
296 # if this is too hard they can spit out a small form
297 # with a "click to continue"
303 die if $parmt eq 't';
305 if ($cookt eq 'y' && $parmt eq 'y' && $cookv ne $parmv) {
306 $r->_db_perhaps_revoke($parmv) if $meth eq 'POST';
311 die unless !$cookt || $cookt eq 'n';
312 die unless !$parmt || $parmt eq 'n' || $parmt eq 'y';
313 if ($meth eq 'GET') {
314 $r->_queue_preserve_params();
315 return ('LOGIN-INCOMINGLINK',
316 "You need to log in again.");
318 return ('LOGIN-FRESH',
319 "You need to log in again.");
323 die unless $cookt eq 'y';
324 die unless $parmt eq 'y';
325 die unless $cookv eq $parmv;
331 sub _check_core ($) {
333 my $qassoc = $r->_ch('get_param');
334 my ($nassoc,$nmutate);
335 if (!defined $r->{S}{cookie_name}) {
336 # authentication is by hidden form parameter only
337 return undef unless defined $qassoc;
341 # authentication is by cookie
342 # the cookie suffices for read-only GET requests
343 # for mutating and non-GET requests we require hidden param too
344 my $cassoc = $r->_ch('get_cookie');
345 return undef unless defined $cassoc;
347 if (defined $qassoc && $qassoc eq $cassoc) {
350 return undef unless $r->{S}{promise_check_mutate};
351 return undef unless $r->_ch('get_method') eq 'GET';
357 my ($nusername, $nlast) =
358 $dbh->selectrow_array("SELECT username, last".
359 " FROM $r->{S}{assocdb_table}".
360 " WHERE associd = ?", {}, $nassoc);
361 return undef unless defined $nusername;
362 my $timeout = $r->{S}{login_timeout};
363 return undef unless !defined $timeout || time <= $nlast + $timeout;
366 return ($nusername, $nassoc, $nmutate);
369 sub record_login ($$) {
370 my ($r,$nusername) = @_;
371 my $rsp = $r->{S}{random_source};
372 my $rsf = new IO::File $rsp, '<' or die "$rsp $!";
373 my $bytes = ($r->{S}{associdlen} + 7) >> 3;
376 read($rsf,$nassocbin,$bytes) == $bytes or die "$rsp $!";
378 my $nassoc = unpack "H*", $nassocbin;
380 $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
381 " (associd, username, last) VALUES (?,?,?)", {},
382 $nassoc, $nusername, time);
384 $r->{U} = $nusername;
391 return if exists $r->{Username};
392 ($r->{Username}, $r->{Assoc}, $r->{Mutate}) = $r->_check();
394 if (defined $r->{Assoc}) {
395 $dbh->do("UPDATE $r->{S}{assocdb_table}".
397 " WHERE associd = ?", {}, time, $nassoc);
405 my ($nusername, $nassoc, $nmutate) = $r->_check();
406 return undef unless $nmutate;
407 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
408 " WHERE associd = ?", {}, $nassoc);
416 return !!defined $r->{Username};
419 sub check_mutate ($) {
428 return $r->{Username};
433 return defined $r->{Assoc} ? $r->{Assoc} : '';
436 #---------- simple wrappers ----------
438 sub hidden_hargs ($) {
440 return (-name => $r->{S}{param_name},
441 -default => $r->hidden_val());
444 sub hidden_html ($) {
446 return hidden($r->hidden_hargs());
449 sub cookiea_cargs ($) {
451 return (-name => $r->{S}{cookie_name},
452 -value => hidden_val());
459 CGI::Auth::Hybrid - web authentication optionally using cookies
463 my $verifier = CGI::Auth::Hybrid->new_verifier(setting => value,...);
464 my $authreq = $verifier->new_request($cgi_request_object);
466 my $authreq = CGI::Auth::Hybrid->new_request($cgi_request_object,
467 setting => value,...);
469 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
471 $authreq->check_ok() or return;
474 $authreq->mutating();
477 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
479 my $divert_kind = $authreq->check_divert();
481 if ($divert_kind eq 'LOGGEDOUT') {
482 print "goodbye you are now logged out" and quit
483 } elsif ($divert_kind eq 'NOCOOKIES') {
484 print "you need cookies" and quit