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);
36 #---------- default callbacks ----------
38 sub has_a_param ($$) {
40 foreach my $pn (@{ $r->{S}{$cn} }) {
41 return 1 if $r->_cm('get_param')($pn);
46 sub get_param_list ($$) {
49 foreach my $name ($c->param()) {
50 foreach my $val ($c->param($name)) {
57 sub get_cookie_domain ($$$) {
59 my $uri = new URI $r->_ch('get_url');
63 sub construct_cookie ($$$) {
64 my ($c, $r, $cookv) = @_;
65 return $c->cookie(-name => $r->{S}{cookie_name},
67 -path => $r->{S}{cookie_path},
68 -domain => $r->_ch('get_cookie_domain'),
69 -expires => '+'.$r->{S}{login_timeout}.'s',
70 -secure => $r->{S}{encrypted_only});
73 sub do_redirect_cgi ($$$$) {
74 my ($c, $r, $new_url, $cookie) = @_;
75 my @ha = ('text/html',
76 -status => '303 See other',
77 -location => $new_url);
78 push @ha, (-cookie => $cookie) if defined $cookie;
79 $r->_print($c->header(@ha),
80 $r->_ch('gen_start_html')($r->_gt('Redirection')),
81 '<a href="'.escapeHTML($new_url).'">',
82 $r->_gt("If you aren't redirected, click to continue."),
84 $c->_ch('gen_end_html'));
87 sub gen_plain_login_form ($$) {
90 push @form, ('<form method="POST" action="',
91 escapeHTML($r->_ch('get_url')).'>',
93 foreach my $up (@{ $r->{S}{username_param_names}}) {
94 push @form, '<tr><td>'.$r->
98 '<input type="text" name="'
99 '<input type="text" name="'.$r->{S}{password_param_name}.'">'.
101 #---------- verifier object methods ----------
107 assocdb_path => 'cah-assocs.db';
108 assocdb_dsn => undef,
110 assocdb_password => '',
111 assocdb_table => 'assocs',
112 random_source => '/dev/urandom',
113 associdlen => 128, # bits
114 login_timeout => 86400, # seconds
115 assoc_param_name => 'cah_associd',
116 password_param_name => 'password',
117 username_param_names => [qw(username)],
118 form_entry_size => 60,
119 logout_param_names => [qw(cah_logout)],
120 loggedout_param_names => [qw(cah_loggedout)],
121 promise_check_mutate => 0,
122 get_param => sub { $_[0]->param($_[2]) },
123 get_param_list => sub { $_[1]->get_param_list() },
124 get_cookie => sub { $_[0]->cookie($s->{S}{cookie_name}) },
125 get_method => sub { $_[0]->request_method() },
126 get_url => sub { $_[0]->url(); },
127 is_login => sub { defined $_[1]->_rp('password_param_name') },
128 login_ok => sub { die },
129 is_logout => sub { $_[1]->has_a_param('logout_param_names') },
130 is_loggedout => sub { $_[1]->has_a_param('loggedout_param_names') },
131 is_page => sub { return 1 },
132 handle_divert => sub { return 0 },
133 do_redirect => \&do_redirect_cgi, # this hook is allowed to throw
135 get_cookie_domain => \&get_cookie_domain,
137 gen_start_html => sub { $_[0]->start_html($_[2]); },
138 gen_end_html => sub { $_[0]->end_html(); },
139 gen_login_form => \&gen_plain_login_form,
140 gettext => sub { gettext($_[2]); },
146 while (($k,$v,@_) = @_) {
147 die "unknown setting $k" unless exists $s->{S}{$k};
160 $s->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=$s->{S}{assocdb_path}";
163 $dbh = DBI->open($s->{S}{assocdb_dsn}, $s->{S}{assocdb_user},
164 $s->{S}{assocdb_password}, {
165 AutoCommit => 0, RaiseError => 1,
167 die "${assocdb_dsn} $! ?" unless $dbh;
173 $dbh->do("CREATE TABLE $s->{S}{assocdb_table} (".
174 " associdh VARCHAR PRIMARY KEY,".
175 " username VARCHAR,".
176 " last INTEGER NOT NULL"
182 #---------- request object methods ----------
185 my ($classbase, $cgi, @extra) = @_;
186 if (!ref $classbase) {
187 $classbase = $classbase->new_verifier(@extra);
192 S => $classbase->{S},
193 Dbh => $classbase->{Dbh},
196 bless $r, ref $classbase;
199 sub _ch ($$@) { # calls an application hook
200 my ($r,$methname, @args) = @_;
201 my $methfunc = $r->{S}{$methname};
202 return $methfunc->($r->{Cgi}, $r, @args);
207 my $pn = $r->{S}{$pnvb};
208 my $p = scalar $r->_ch('get_param',$pn)
211 sub _gt ($$) { my ($r, $t) = @_; return $r->_ch('gettext')($t); }
212 sub _print ($$) { my ($r, @t) = @_; return $r->_ch('print')(join '', @t); }
214 # pages/param-sets are
215 # n normal non-mutating page
216 # r retrieval of information for JS, non-mutating
218 # u update of information by JS, mutating
221 # O "you have just logged out" page load
224 # a, aN anything including -
225 # t, tN temporary value (in our db, no logged in user yet)
226 # y, yN value corresponds to logged-in user
227 # n, nN value not in our db
229 # - no value supplied
230 # if N differs the case applies only when the two values differ
231 # (eg, a1 y2 does not apply when the logged-in value is supplied twice)
233 # "stale session" means request originates from a page from a login
234 # session which has been revoked (eg by logout); "cleared session"
235 # means request originates from a browser which has a different (or
238 # Case analysis, cookie mode, app promises re mutate:
239 # cook parm meth form
241 # any - POST nrmuoi bug or attack, fail
242 # any - GET rmuoi bug or attack, fail
243 # any any GET muoi bug or attack, fail
244 # any t any nrmu bug or attack, fail
246 # - - GET O "just logged out" page
247 # (any other) O bug or attack, fail
249 # a1 a2 POST o logout
250 # if a1 is valid, revoke it
251 # if a2 is valid, revoke it
253 # redirect to "just logged out" page
254 # (which contains link to login form)
256 # - t POST i complain about cookies being disabled
257 # (with link to login form)
259 # any n POST i complain about stale login form
260 # show new login form
262 # x1 t2 POST i login (or switch user)
264 # show new login form
266 # revoke x1 if it was valid and !=t2
267 # upgrade t2 to y2 in our db (setting username)
269 # redirect to GET of remaining params
271 # t1 a2 ANY nrmu treat as - a2 ANY
273 # y - GET n cross-site link
276 # y y GET nr fine, show page or send data
277 # y y POST nrmu mutation is OK, do operation
279 # y1 y2 GET nr request from stale page
280 # do not revoke y2 as not RESTful
283 # y1 y2 POST nrmu request from stale page
287 # y n GET n intra-site link from stale page,
288 # treat as cross-site link, show data
290 # y n POST n m intra-site form submission from stale page
291 # show "session interrupted"
292 # with link to main data page
294 # y n GET r intra-site request from stale page
297 # y n POST r u intra-site request from stale page
300 # -/n y2 GET nr intra-site link from cleared session
301 # do not revoke y2 as not RESTful
304 # -/n y2 POST nrmu request from cleared session
306 # treat as -/n n POST
308 # -/n n GET n cross-site link but user not logged in
309 # show login form with redirect to orig params
311 # -/n n GET rmu user not logged in
314 # -/n n POST n m user not logged in
317 # -/n n POST r u user not logged in
320 sub _check_divert_core ($) {
321 fixme needs wrapping with something to make and commit a transaction
324 my $meth = $r->_ch('get_method');
325 my $cookv = $r->_ch('get_cookie');
326 my $parmv = $r->_rp('assoc_param_name');
328 my ($cookt,$cooku) = $r->_db_lookup($cookv);
329 my $parmt = $r->_db_lookup($parmv);
331 if ($r->_ch('is_logout')) {
334 $r->_db_revoke($cookv);
335 $r->_db_revoke($parmv);
336 return ({ Kind => 'REDIRECT-LOGGEDOUT',
337 Message => "Logging out...",
341 if ($r->_ch('is_loggedout')) {
342 die unless $meth eq 'GET';
345 return ({ Kind => 'SMALLPAGE-LOGGEDOUT',
346 Message => "You have been logged out.",
350 if ($r->_ch('is_login')) {
352 return ({ Kind => 'LOGIN-STALE',
353 Message => "Stale session; you need to log in again.",
354 Cookie => $r->_fresh_cookie(),
357 die unless $parmt eq 't' || $parmt eq 'y';
358 return ({ Kind => 'SMALLPAGE-NOCOOKIE',
359 Message => "You do not seem to have cookies enabled. ".
360 "You must enable cookies as we use them for login.",
361 Cookie => $r->_fresh_cookie(),
362 Params => $r->_chain_params() })
363 if !$cookt && $parmt eq 't';
364 return ({ Kind => 'LOGIN-BAD',
365 Message => "Incorrect username/password.",
367 Params => $r->_chain_params() })
368 unless defined $username && length $username;
369 $r->_db_revoke($cookv)
370 if defined $cookv && !(defined $parmv && $cookv eq $parmv);
371 my $username = $r->_ch('login_ok');
372 $r->_db_record_login_ok($parmv,$username);
373 return ({ Kind => 'REDIRECT-LOGGEDIN',
374 Message => "Logging in...",
376 Params => $r->_chain_params() });
381 die if $parmt eq 't';
383 if ($cookt eq 'y' && $parmt eq 'y' && $cookv ne $parmv) {
384 $r->_db_revoke($parmv) if $meth eq 'POST';
389 die unless !$cookt || $cookt eq 'n';
390 die unless !$parmt || $parmt eq 'n' || $parmt eq 'y';
391 if ($meth eq 'GET') {
392 return ({ Kind => 'LOGIN-INCOMINGLINK',
393 Message => "You need to log in again.",
395 Params => $r->_chain_params() });
397 return ((Kind => 'LOGIN-FRESH',
398 Message => "You need to log in again.",
404 if (!$r->{S}{promise_check_mutate}) {
405 if ($meth ne 'POST') {
406 return ({ Kind => 'MAINPAGEONLY',
407 Message => 'Entering via cross-site link.',
410 # NB caller must then ignore params & path!
411 # if this is too hard they can spit out a small form
412 # with a "click to continue"
416 die unless $cookt eq 'y';
417 die unless $parmt eq 'y';
418 die unless $cookv eq $parmv;
419 $r->{UserOK} = $cooku;
423 sub _chain_params ($) {
426 foreach my $pncn (keys %{ $r->{S} }) {
427 if ($pncn =~ m/_param_name$/) {
428 my $name = $r->{S}{$pncn};
429 die "$pncn ?" if ref $name;
431 } elsif ($pncn =~ m/_param_names$/) {
432 $names = $r->{S}{$pncn};
436 foreach my $param (@$names) {
440 my @p = $r->_ch('get_param_list');
444 ($name,$val,@p) = @p;
445 next if $elim{$name};
446 push @q, $name, $val;
451 sub _db_lookup ($$) {
452 # returns ($t,$username)
453 # where $t is one of "t" "y" "n", or "" (for -)
458 my ($nusername, $nlast) =
459 $dbh->selectrow_array("SELECT username, last".
460 " FROM $r->{S}{assocdb_table}".
461 " WHERE associd = ?", {}, $nassoc);
462 return ('') unless defined $nusername;
464 my $timeout = $r->{S}{login_timeout};
465 return ('n') unless !defined $timeout || time <= $nlast + $timeout;
467 return ('t') unless defined $nusername;
470 return ('y', $nusername);
473 sub _db_revoke ($$) {
474 # revokes $v if it's valid; no-op if it's not
479 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
480 " WHERE associd = ?", {}, $v);
483 sub _db_record_login_ok ($$$) {
484 my ($r,$v,$user) = @_;
486 $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
487 " (associd, username, last) VALUES (?,?,?)", {},
491 sub url_with_query_params ($@) {
492 my ($r, @params) = @_;
493 my $uri = URI->new($r->_ch('get_url'));
494 $uri->query_form(\@params);
495 return $uri->as_string();
501 my ($divert) = $authreq->check_divert();
504 my $handled = $r->_ch('handle_divert')($divert);
505 return 0 if $handled;
507 my $kind = $divert->{Kind};
508 my $cookie = $divert->{Cookie};
509 my $params = $divert->{Params};
511 if ($kind =~ m/^REDIRECT-/) {
512 # for redirects, we honour stored NextParams and SetCookie,
513 # as we would for non-divert
514 if ($divert_kind eq 'REDIRECT-LOGGEDOUT') {
515 push @$params, $r->{S}{cah_loggedout}[0], 1;
516 } elsif ($divert_kind eq 'REDIRECT-LOGOUT') {
517 push @$params, $r->{S}{cah_logout}[0], 1;
518 } elsif ($divert_kind eq 'REDIRECT-LOGGEDIN') {
522 my $new_url = $r->url_with_query_params(@$params);
523 $r->_ch('do_redirect')($new_url, $cookie);
526 $kind =~ m/^SMALLPAGE|^LOGIN/ or die;
529 if ($kind =~ m/^LOGIN-/) {
530 $title = $r->_gt('Login');
531 push @body, $r->_gt($divert->{Message});
532 push @body, $r->_ch('gen_login_form');
536 $r->_ch('start_html')($title),
540 if ($kind =~ m/^SMALLPAGE
542 if (defined $cookie) {
543 $r->_ch('header_out')($cookie);
548 sub record_login ($$) {
549 my ($r,$nusername) = @_;
550 my $rsp = $r->{S}{random_source};
551 my $rsf = new IO::File $rsp, '<' or die "$rsp $!";
552 my $bytes = ($r->{S}{associdlen} + 7) >> 3;
555 read($rsf,$nassocbin,$bytes) == $bytes or die "$rsp $!";
557 my $nassoc = unpack "H*", $nassocbin;
559 $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
560 " (associd, username, last) VALUES (?,?,?)", {},
561 $nassoc, $nusername, time);
563 $r->{U} = $nusername;
570 return if exists $r->{Username};
571 ($r->{Username}, $r->{Assoc}, $r->{Mutate}) = $r->_check();
573 if (defined $r->{Assoc}) {
574 $dbh->do("UPDATE $r->{S}{assocdb_table}".
576 " WHERE associd = ?", {}, time, $nassoc);
584 my ($nusername, $nassoc, $nmutate) = $r->_check();
585 return undef unless $nmutate;
586 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
587 " WHERE associd = ?", {}, $nassoc);
595 return !!defined $r->{Username};
598 sub check_mutate ($) {
607 return $r->{Username};
612 return defined $r->{Assoc} ? $r->{Assoc} : '';
615 #---------- simple wrappers ----------
617 sub hidden_hargs ($) {
619 return (-name => $r->{S}{param_name},
620 -default => $r->hidden_val());
623 sub hidden_html ($) {
625 return hidden($r->hidden_hargs());
628 sub cookiea_cargs ($) {
630 return (-name => $r->{S}{cookie_name},
631 -value => hidden_val());
638 CGI::Auth::Hybrid - web authentication optionally using cookies
642 my $verifier = CGI::Auth::Hybrid->new_verifier(setting => value,...);
643 my $authreq = $verifier->new_request($cgi_request_object);
645 my $authreq = CGI::Auth::Hybrid->new_request($cgi_request_object,
646 setting => value,...);
648 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
650 $authreq->check_ok() or return;
653 $authreq->mutating();
656 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
658 my $divert_kind = $authreq->check_divert();
660 if ($divert_kind eq 'LOGGEDOUT') {
661 print "goodbye you are now logged out" and quit
662 } elsif ($divert_kind eq 'NOCOOKIES') {
663 print "you need cookies" and quit