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 ($$) {
88 my ($c,$r, $params) = @_;
90 push @form, ('<form method="POST" action="',
91 escapeHTML($r->_ch('get_url')).'>',
93 my $sz = 'size="'.$r->{S}{form_entry_size}.'"';
94 foreach my $up (@{ $r->{S}{username_param_names}}) {
95 push @form, ('<tr><td>',$r->_gt(ucfirst $up),'</td>',
96 '<td><input type="text" ',$sz,
97 ' name=',$up,'></td></tr>');
99 push @form, ('<tr><td>'.$r->_gt('Password'),'</td>',
100 '<td><input type="password" ',$sz,
101 ' name="'.$r->{S}{password_param_name}.'"></td></tr>');
102 push @form, ('<tr><td colspan="2">',
103 '<input type="submit"'.
104 ' name="'.$r->{S}{login_submit_name}.'"',
105 ' value="'.$r->_gt('Login').'"></td></tr></table>');
106 foreach my $p (@$params) {
109 #---------- verifier object methods ----------
115 assocdb_path => 'cah-assocs.db';
116 assocdb_dsn => undef,
118 assocdb_password => '',
119 assocdb_table => 'assocs',
120 random_source => '/dev/urandom',
121 associdlen => 128, # bits
122 login_timeout => 86400, # seconds
123 assoc_param_name => 'cah_associd',
124 password_param_name => 'password',
125 username_param_names => [qw(username)],
126 form_entry_size => 60,
127 logout_param_names => [qw(cah_logout)],
128 login_submit_name => [qw(cah_login)],
129 loggedout_param_names => [qw(cah_loggedout)],
130 promise_check_mutate => 0,
131 get_param => sub { $_[0]->param($_[2]) },
132 get_param_list => sub { $_[1]->get_param_list() },
133 get_cookie => sub { $_[0]->cookie($s->{S}{cookie_name}) },
134 get_method => sub { $_[0]->request_method() },
135 get_url => sub { $_[0]->url(); },
136 is_login => sub { defined $_[1]->_rp('password_param_name') },
137 login_ok => sub { die },
138 is_logout => sub { $_[1]->has_a_param('logout_param_names') },
139 is_loggedout => sub { $_[1]->has_a_param('loggedout_param_names') },
140 is_page => sub { return 1 },
141 handle_divert => sub { return 0 },
142 do_redirect => \&do_redirect_cgi, # this hook is allowed to throw
144 get_cookie_domain => \&get_cookie_domain,
146 gen_start_html => sub { $_[0]->start_html($_[2]); },
147 gen_end_html => sub { $_[0]->end_html(); },
148 gen_login_form => \&gen_plain_login_form,
149 gettext => sub { gettext($_[2]); },
155 while (($k,$v,@_) = @_) {
156 die "unknown setting $k" unless exists $s->{S}{$k};
169 $s->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=$s->{S}{assocdb_path}";
172 $dbh = DBI->open($s->{S}{assocdb_dsn}, $s->{S}{assocdb_user},
173 $s->{S}{assocdb_password}, {
174 AutoCommit => 0, RaiseError => 1,
176 die "${assocdb_dsn} $! ?" unless $dbh;
182 $dbh->do("CREATE TABLE $s->{S}{assocdb_table} (".
183 " associdh VARCHAR PRIMARY KEY,".
184 " username VARCHAR,".
185 " last INTEGER NOT NULL"
191 #---------- request object methods ----------
194 my ($classbase, $cgi, @extra) = @_;
195 if (!ref $classbase) {
196 $classbase = $classbase->new_verifier(@extra);
201 S => $classbase->{S},
202 Dbh => $classbase->{Dbh},
205 bless $r, ref $classbase;
208 sub _ch ($$@) { # calls an application hook
209 my ($r,$methname, @args) = @_;
210 my $methfunc = $r->{S}{$methname};
211 return $methfunc->($r->{Cgi}, $r, @args);
216 my $pn = $r->{S}{$pnvb};
217 my $p = scalar $r->_ch('get_param',$pn)
220 sub _gt ($$) { my ($r, $t) = @_; return $r->_ch('gettext')($t); }
221 sub _print ($$) { my ($r, @t) = @_; return $r->_ch('print')(join '', @t); }
223 # pages/param-sets are
224 # n normal non-mutating page
225 # r retrieval of information for JS, non-mutating
227 # u update of information by JS, mutating
230 # O "you have just logged out" page load
233 # a, aN anything including -
234 # t, tN temporary value (in our db, no logged in user yet)
235 # y, yN value corresponds to logged-in user
236 # n, nN value not in our db
238 # - no value supplied
239 # if N differs the case applies only when the two values differ
240 # (eg, a1 y2 does not apply when the logged-in value is supplied twice)
242 # "stale session" means request originates from a page from a login
243 # session which has been revoked (eg by logout); "cleared session"
244 # means request originates from a browser which has a different (or
247 # Case analysis, cookie mode, app promises re mutate:
248 # cook parm meth form
250 # any - POST nrmuoi bug or attack, fail
251 # any - GET rmuoi bug or attack, fail
252 # any any GET muoi bug or attack, fail
253 # any t any nrmu bug or attack, fail
255 # - - GET O "just logged out" page
256 # (any other) O bug or attack, fail
258 # a1 a2 POST o logout
259 # if a1 is valid, revoke it
260 # if a2 is valid, revoke it
262 # redirect to "just logged out" page
263 # (which contains link to login form)
265 # - t POST i complain about cookies being disabled
266 # (with link to login form)
268 # any n POST i complain about stale login form
269 # show new login form
271 # x1 t2 POST i login (or switch user)
273 # show new login form
275 # revoke x1 if it was valid and !=t2
276 # upgrade t2 to y2 in our db (setting username)
278 # redirect to GET of remaining params
280 # t1 a2 ANY nrmu treat as - a2 ANY
282 # y - GET n cross-site link
285 # y y GET nr fine, show page or send data
286 # y y POST nrmu mutation is OK, do operation
288 # y1 y2 GET nr request from stale page
289 # do not revoke y2 as not RESTful
292 # y1 y2 POST nrmu request from stale page
296 # y n GET n intra-site link from stale page,
297 # treat as cross-site link, show data
299 # y n POST n m intra-site form submission from stale page
300 # show "session interrupted"
301 # with link to main data page
303 # y n GET r intra-site request from stale page
306 # y n POST r u intra-site request from stale page
309 # -/n y2 GET nr intra-site link from cleared session
310 # do not revoke y2 as not RESTful
313 # -/n y2 POST nrmu request from cleared session
315 # treat as -/n n POST
317 # -/n n GET n cross-site link but user not logged in
318 # show login form with redirect to orig params
320 # -/n n GET rmu user not logged in
323 # -/n n POST n m user not logged in
326 # -/n n POST r u user not logged in
329 sub _check_divert_core ($) {
330 fixme needs wrapping with something to make and commit a transaction
333 my $meth = $r->_ch('get_method');
334 my $cookv = $r->_ch('get_cookie');
335 my $parmv = $r->_rp('assoc_param_name');
337 my ($cookt,$cooku) = $r->_db_lookup($cookv);
338 my $parmt = $r->_db_lookup($parmv);
340 if ($r->_ch('is_logout')) {
343 $r->_db_revoke($cookv);
344 $r->_db_revoke($parmv);
345 return ({ Kind => 'REDIRECT-LOGGEDOUT',
346 Message => "Logging out...",
350 if ($r->_ch('is_loggedout')) {
351 die unless $meth eq 'GET';
354 return ({ Kind => 'SMALLPAGE-LOGGEDOUT',
355 Message => "You have been logged out.",
359 if ($r->_ch('is_login')) {
361 return ({ Kind => 'LOGIN-STALE',
362 Message => "Stale session; you need to log in again.",
363 Cookie => $r->_fresh_cookie(),
366 die unless $parmt eq 't' || $parmt eq 'y';
367 return ({ Kind => 'SMALLPAGE-NOCOOKIE',
368 Message => "You do not seem to have cookies enabled. ".
369 "You must enable cookies as we use them for login.",
370 Cookie => $r->_fresh_cookie(),
371 Params => $r->_chain_params() })
372 if !$cookt && $parmt eq 't';
373 return ({ Kind => 'LOGIN-BAD',
374 Message => "Incorrect username/password.",
376 Params => $r->_chain_params() })
377 unless defined $username && length $username;
378 $r->_db_revoke($cookv)
379 if defined $cookv && !(defined $parmv && $cookv eq $parmv);
380 my $username = $r->_ch('login_ok');
381 $r->_db_record_login_ok($parmv,$username);
382 return ({ Kind => 'REDIRECT-LOGGEDIN',
383 Message => "Logging in...",
385 Params => $r->_chain_params() });
390 die if $parmt eq 't';
392 if ($cookt eq 'y' && $parmt eq 'y' && $cookv ne $parmv) {
393 $r->_db_revoke($parmv) if $meth eq 'POST';
398 die unless !$cookt || $cookt eq 'n';
399 die unless !$parmt || $parmt eq 'n' || $parmt eq 'y';
400 if ($meth eq 'GET') {
401 return ({ Kind => 'LOGIN-INCOMINGLINK',
402 Message => "You need to log in again.",
404 Params => $r->_chain_params() });
406 return ((Kind => 'LOGIN-FRESH',
407 Message => "You need to log in again.",
413 if (!$r->{S}{promise_check_mutate}) {
414 if ($meth ne 'POST') {
415 return ({ Kind => 'MAINPAGEONLY',
416 Message => 'Entering via cross-site link.',
419 # NB caller must then ignore params & path!
420 # if this is too hard they can spit out a small form
421 # with a "click to continue"
425 die unless $cookt eq 'y';
426 die unless $parmt eq 'y';
427 die unless $cookv eq $parmv;
428 $r->{UserOK} = $cooku;
432 sub _chain_params ($) {
435 foreach my $pncn (keys %{ $r->{S} }) {
436 if ($pncn =~ m/_param_name$/) {
437 my $name = $r->{S}{$pncn};
438 die "$pncn ?" if ref $name;
440 } elsif ($pncn =~ m/_param_names$/) {
441 $names = $r->{S}{$pncn};
445 foreach my $param (@$names) {
449 my @p = $r->_ch('get_param_list');
453 ($name,$val,@p) = @p;
454 next if $elim{$name};
455 push @q, $name, $val;
460 sub _db_lookup ($$) {
461 # returns ($t,$username)
462 # where $t is one of "t" "y" "n", or "" (for -)
467 my ($nusername, $nlast) =
468 $dbh->selectrow_array("SELECT username, last".
469 " FROM $r->{S}{assocdb_table}".
470 " WHERE associd = ?", {}, $nassoc);
471 return ('') unless defined $nusername;
473 my $timeout = $r->{S}{login_timeout};
474 return ('n') unless !defined $timeout || time <= $nlast + $timeout;
476 return ('t') unless defined $nusername;
479 return ('y', $nusername);
482 sub _db_revoke ($$) {
483 # revokes $v if it's valid; no-op if it's not
488 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
489 " WHERE associd = ?", {}, $v);
492 sub _db_record_login_ok ($$$) {
493 my ($r,$v,$user) = @_;
495 $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
496 " (associd, username, last) VALUES (?,?,?)", {},
500 sub url_with_query_params ($@) {
501 my ($r, @params) = @_;
502 my $uri = URI->new($r->_ch('get_url'));
503 $uri->query_form(\@params);
504 return $uri->as_string();
510 my ($divert) = $authreq->check_divert();
513 my $handled = $r->_ch('handle_divert')($divert);
514 return 0 if $handled;
516 my $kind = $divert->{Kind};
517 my $cookie = $divert->{Cookie};
518 my $params = $divert->{Params};
520 if ($kind =~ m/^REDIRECT-/) {
521 # for redirects, we honour stored NextParams and SetCookie,
522 # as we would for non-divert
523 if ($divert_kind eq 'REDIRECT-LOGGEDOUT') {
524 push @$params, $r->{S}{cah_loggedout}[0], 1;
525 } elsif ($divert_kind eq 'REDIRECT-LOGOUT') {
526 push @$params, $r->{S}{cah_logout}[0], 1;
527 } elsif ($divert_kind eq 'REDIRECT-LOGGEDIN') {
531 my $new_url = $r->url_with_query_params(@$params);
532 $r->_ch('do_redirect')($new_url, $cookie);
535 $kind =~ m/^SMALLPAGE|^LOGIN/ or die;
538 if ($kind =~ m/^LOGIN-/) {
539 $title = $r->_gt('Login');
540 push @body, $r->_gt($divert->{Message});
541 push @body, $r->_ch('gen_login_form', $params);
545 $r->_ch('start_html')($title),
549 if ($kind =~ m/^SMALLPAGE
551 if (defined $cookie) {
552 $r->_ch('header_out')($cookie);
557 sub record_login ($$) {
558 my ($r,$nusername) = @_;
559 my $rsp = $r->{S}{random_source};
560 my $rsf = new IO::File $rsp, '<' or die "$rsp $!";
561 my $bytes = ($r->{S}{associdlen} + 7) >> 3;
564 read($rsf,$nassocbin,$bytes) == $bytes or die "$rsp $!";
566 my $nassoc = unpack "H*", $nassocbin;
568 $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
569 " (associd, username, last) VALUES (?,?,?)", {},
570 $nassoc, $nusername, time);
572 $r->{U} = $nusername;
579 return if exists $r->{Username};
580 ($r->{Username}, $r->{Assoc}, $r->{Mutate}) = $r->_check();
582 if (defined $r->{Assoc}) {
583 $dbh->do("UPDATE $r->{S}{assocdb_table}".
585 " WHERE associd = ?", {}, time, $nassoc);
593 my ($nusername, $nassoc, $nmutate) = $r->_check();
594 return undef unless $nmutate;
595 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
596 " WHERE associd = ?", {}, $nassoc);
604 return !!defined $r->{Username};
607 sub check_mutate ($) {
616 return $r->{Username};
621 return defined $r->{Assoc} ? $r->{Assoc} : '';
624 #---------- simple wrappers ----------
626 sub hidden_hargs ($) {
628 return (-name => $r->{S}{param_name},
629 -default => $r->hidden_val());
632 sub hidden_html ($) {
634 return hidden($r->hidden_hargs());
637 sub cookiea_cargs ($) {
639 return (-name => $r->{S}{cookie_name},
640 -value => hidden_val());
647 CGI::Auth::Hybrid - web authentication optionally using cookies
651 my $verifier = CGI::Auth::Hybrid->new_verifier(setting => value,...);
652 my $authreq = $verifier->new_request($cgi_request_object);
654 my $authreq = CGI::Auth::Hybrid->new_request($cgi_request_object,
655 setting => value,...);
657 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
659 $authreq->check_ok() or return;
662 $authreq->mutating();
665 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
667 my $divert_kind = $authreq->check_divert();
669 if ($divert_kind eq 'LOGGEDOUT') {
670 print "goodbye you are now logged out" and quit
671 } elsif ($divert_kind eq 'NOCOOKIES') {
672 print "you need cookies" and quit