chiark / gitweb /
wip, before sort out response handling
[cgi-auth-flexible.git] / cgi-auth-hybrid.pm
1 # -*- perl -*-
2
3 # This is part of CGI::Auth::Hybrid, a perl CGI authentication module.
4 # Copyright (C) 2012 Ian Jackson.
5
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.
10
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.
15
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/>.
18
19 BEGIN {
20     use Exporter   ();
21     our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
22
23     $VERSION     = 1.00;
24     @ISA         = qw(Exporter);
25     @EXPORT      = qw();
26     %EXPORT_TAGS = ( );     # eg: TAG => [ qw!name1 name2! ],
27
28     @EXPORT_OK   = qw(setup);
29 }
30 our @EXPORT_OK;
31
32 use DBI;
33 use CGI;
34
35 #---------- default callbacks ----------
36
37 sub has_a_param ($$) {
38     my ($c,$cn) = @_;
39     foreach my $pn (@{ $r->{S}{$cn} }) {
40         return 1 if $r->_cm('get_param')($pn);
41     }
42     return 0;
43 }
44
45 sub get_param_list ($$) {
46     my ($c) = @_;
47     my @p = ( );
48     foreach my $name ($c->param()) {
49         foreach my $val ($c->param($name)) {
50             push @p, $name, $val;
51         }
52     }
53     return @p;
54 }
55
56 #---------- verifier object methods ----------
57
58 sub new_verifier {
59     my $class = shift;
60     my $s = {
61         S => {
62             assocdb_path => 'cah-assocs.db';
63             assocdb_dsn => undef,
64             assocdb_user => '',
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 },
85         },
86         Dbh => undef,
87     };
88     my ($k,$v);
89     while (($k,$v,@_) = @_) {
90         die "unknown setting $k" unless exists $s->{S}{$k};
91         $s->{S}{$k} = $v;
92     }
93     bless $s, $class;
94     $s->_dbopen();
95     return $s;
96 }
97
98 sub _dbopen ($) {
99     my ($s) = @_;
100     my $dbh = $s->{Dbh};
101     return $dbh if $dbh; 
102
103     $s->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=$s->{S}{assocdb_path}";
104
105     my $u = umask 077;
106     $dbh = DBI->open($s->{S}{assocdb_dsn}, $s->{S}{assocdb_user}, 
107                      $s->{S}{assocdb_password}, { 
108                          AutoCommit => 0, RaiseError => 1,
109                      });
110     die "${assocdb_dsn} $! ?" unless $dbh;
111     $s->{Dbh} = $dbh;
112
113     $dbh->do("BEGIN");
114
115     eval {
116         $dbh->do("CREATE TABLE $s->{S}{assocdb_table} (".
117                  " associdh VARCHAR PRIMARY KEY,".
118                  " username VARCHAR,".
119                  " last INTEGER NOT NULL"
120                  ")");
121     };
122     return $dbh;
123 }
124
125 #---------- request object methods ----------
126
127 sub new_request {
128     my ($classbase, $cgi, @extra) = @_;
129     if (!ref $classbase) {
130         $classbase = $classbase->new_verifier(@extra);
131     } else {
132         die if @extra;
133     }
134     my $r = {
135         S => $classbase->{S},
136         Dbh => $classbase->{Dbh},
137         Cgi => $cgi,
138     };
139     bless $r, ref $classbase;
140 }
141
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);
146 }
147
148 sub _rp ($$@) {
149     my ($r,$pnvb) = @_;
150     my $pn = $r->{S}{$pnvb};
151     my $p = scalar $r->_ch('get_param',$pn)
152 }
153
154 # pages/param-sets are
155 #   n normal non-mutating page
156 #   r retrieval of information for JS, non-mutating
157 #   m mutating page
158 #   u update of information by JS, mutating
159 #   i login
160 #   o logout
161 #   O "you have just logged out" page load
162
163 # in cook and par,
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
168 #    x, xN     t or y
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)
172
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
176 # no) cookie.
177
178     # Case analysis, cookie mode, app promises re mutate:
179     # cook parm meth form
180     #                      
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
185     #
186     #  -   -   GET         O  "just logged out" page
187     #  (any other)         O  bug or attack, fail
188     #
189     #  a1  a2  POST      o    logout
190     #                           if a1 is valid, revoke it
191     #                           if a2 is valid, revoke it
192     #                           delete cookie
193     #                           redirect to "just logged out" page
194     #                             (which contains link to login form)
195     #
196     #  -   t   POST       i   complain about cookies being disabled
197     #                           (with link to login form)
198     #
199     #  any n   POST       i   complain about stale login form
200     #                           show new login form
201     #
202     #  x1  t2  POST       i   login (or switch user)
203     #                           if bad
204     #                             show new login form
205     #                           if good
206     #                             revoke x1 if it was valid and !=t2
207     #                             upgrade t2 to y2 in our db (setting username)
208     #                             set cookie to t2
209     #                             redirect to GET of remaining params
210     #
211     #  t1  a2  ANY   nrmu     treat as  - a2 ANY
212     #
213     #  y   -   GET   n        cross-site link
214     #                           show data
215     #
216     #  y   y   GET   nr       fine, show page or send data
217     #  y   y   POST  nrmu     mutation is OK, do operation
218     #
219     #  y1  y2  GET   nr       request from stale page
220     #                           do not revoke y2 as not RESTful
221     #                           treat as   y1 n GET
222     #
223     #  y1  y2  POST  nrmu     request from stale page
224     #                           revoke y2
225     #                           treat as   y1 n POST
226     #
227     #  y   n   GET   n        intra-site link from stale page,
228     #                           treat as cross-site link, show data
229     #
230     #  y   n   POST  n m      intra-site form submission from stale page
231     #                           show "session interrupted"
232     #                           with link to main data page
233     #
234     #  y   n   GET    r       intra-site request from stale page
235     #                           fail
236     #
237     #  y   n   POST   r u     intra-site request from stale page
238     #                           fail
239     #
240     #  -/n y2  GET   nr       intra-site link from cleared session
241     #                           do not revoke y2 as not RESTful
242     #                           treat as   -/n n GET
243     #
244     #  -/n y2  POST  nrmu     request from cleared session
245     #                           revoke y2
246     #                           treat as   -/n n POST
247     #
248     #  -/n n   GET   n        cross-site link but user not logged in
249     #                           show login form with redirect to orig params
250     #
251     #  -/n n   GET    rmu     user not logged in
252     #                           fail
253     #
254     #  -/n n   POST  n m      user not logged in
255     #                           show login form
256     #
257     #  -/n n   POST   r u     user not logged in
258     #                           fail
259
260 sub _check_divert_core ($) {
261 fixme needs wrapping with something to make and commit a transaction
262     my ($r) = @_;
263
264     my $meth = $r->_ch('get_method');
265     my $cookv = $r->_ch('get_cah_cookie');
266     my $parmv = $r->_rp('assoc_param_name');
267
268     my ($cookt,$cooku) = $r->_db_lookup($cookv);
269     my $parmt = $r->_db_lookup($parmv);
270
271     if ($r->_ch('is_logout')) {
272         $r->_must_be_post();
273         die unless $parmt;
274         $r->_db_revoke($cookv);
275         $r->_db_revoke($parmv);
276         return ({ Kind => 'REDIRECT/LOGGEDOUT',
277                   Message => "Logging out...",
278                   Cookie => '',
279                   Params => [ ] });
280     }
281     if ($r->_ch('is_loggedout')) {
282         die unless $meth eq 'GET';
283         die unless $cookt;
284         die unless $parmt;
285         return ({ Kind => 'SMALLPAGE/LOGGEDOUT',
286                   Message => "You have been logged out.",
287                   Cookie => '',
288                   Params => [ ] });
289     }
290     if ($r->_ch('is_login')) {
291         $r->_must_be_post();
292         return ({ Kind => 'LOGIN-STALE',
293                   Message => "Stale session; you need to log in again.",
294                   Cookie => $r->_fresh_cookie(),
295                   Params => [ ] })
296             if $parmt eq 'n';
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.",
306                   Cookie => $cookv,
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...",
315                   Cookie => $parmv,
316                   Params => $r->_chain_params() });
317     }
318     if ($cookt eq 't') {
319         $cookt = '';
320     }
321     die if $parmt eq 't';
322
323     if ($cookt eq 'y' && $parmt eq 'y' && $cookv ne $parmv) {
324         $r->_db_revoke($parmv) if $meth eq 'POST';
325         $parmt = 'n';
326     }
327
328     if ($cookt ne 'y') {
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.",
334                       Cookie => $parmv,
335                       Params => $r->_chain_params() });
336         } else {
337             return ((Kind => 'LOGIN-FRESH',
338                      Message => "You need to log in again.",
339                      Cookie => $parmv,
340                      Params => [ ]);
341         }
342     }
343
344     if (!$r->{S}{promise_check_mutate}) {
345         if ($meth ne 'POST') {
346             return ({ Kind => 'MAINPAGEONLY',
347                       Message => 'Entering via cross-site link.',
348                       Cookie => $cookv,
349                       Params => [ ] });
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"
353         }
354     }
355
356     die unless $cookt eq 'y';
357     die unless $parmt eq 'y';
358     die unless $cookv eq $parmv;
359     $r->{UserOK} = $cooku;
360     return undef;
361 }
362
363 sub _chain_params ($) {
364     my ($r) = @_;
365     my %elim = { };
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;
370             $names = [ $name ];
371         } elsif ($pncn =~ m/_param_names$/) {
372             $names = $r->{S}{$pncn};
373         } else {
374             next;
375         }
376         foreach my $param (@$names) {
377             $elim{$name} = 1;
378         }
379     }
380     my @p = $r->_ch('get_param_list');
381     my ($name,$val);
382     my @q = ();
383     while (@p) {
384         ($name,$val,@p) = @p;
385         next if $elim{$name};
386         push @q, $name, $val;
387     }
388     return @q;
389 }
390
391 sub _db_lookup ($$) {
392     # returns ($t,$username)
393     # where $t is one of "t" "y" "n", or "" (for -)
394     my ($r,$v) = @_;
395
396     my $dbh = $r->{Dbh};
397
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;
403
404     my $timeout = $r->{S}{login_timeout};
405     return ('n') unless !defined $timeout || time <= $nlast + $timeout;
406
407     return ('t') unless defined $nusername;
408
409     # hooray
410     return ('y', $nusername);
411 }
412
413 sub _db_revoke ($$) {
414     # revokes $v if it's valid; no-op if it's not
415     my ($r,$v) = @_;
416
417     my $dbh = $r->{Dbh};
418
419     $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
420              " WHERE associd = ?", {}, $v);
421 }
422
423 sub _db_record_login_ok ($$$) {
424     my ($r,$v,$user) = @_;
425     $r->_db_revoke($v);
426     $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
427              " (associd, username, last) VALUES (?,?,?)", {},
428              $v, $user, time);
429 }
430
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();
436 }
437
438 sub check_ok ($) {
439     my ($r) = @_;
440
441     my ($divert) = $authreq->check_divert();
442     return 1 if $divert;
443
444     my $kind = $divert->{Kind};
445     my $cookie = $divert->{Cookie};
446     my $params = $divert->{Params};
447
448     if (defined $cookie) {
449         $r->_ch('header_out')($cookie);
450     }
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') {
460         }
461
462 UP TO HERE
463
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;
469     my $nassocbin;
470     $!=0;
471     read($rsf,$nassocbin,$bytes) == $bytes or die "$rsp $!";
472     close $rsf;
473     my $nassoc = unpack "H*", $nassocbin;
474     my $dbh = $r->{Dbh};
475     $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
476              " (associd, username, last) VALUES (?,?,?)", {},
477              $nassoc, $nusername, time);
478     $dbh->do("COMMIT");
479     $r->{U} = $nusername;
480     $r->{A} = $nassoc;
481 }
482
483 sub _check ($) {
484     my ($r) = @_;
485
486     return if exists $r->{Username};
487     ($r->{Username}, $r->{Assoc}, $r->{Mutate}) = $r->_check();
488
489     if (defined $r->{Assoc}) {
490         $dbh->do("UPDATE $r->{S}{assocdb_table}".
491                  " SET last = ?".
492                  " WHERE associd = ?", {}, time, $nassoc);
493         $dbh->do("COMMIT");
494     }
495 }
496
497 sub logout ($) {
498     my ($r) = @_;
499
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);
504     $dbh->do("COMMIT");
505     return $nusername;
506 }
507
508 sub check ($) {
509     my ($r) = @_;
510     $r->_check();
511     return !!defined $r->{Username};
512 }
513
514 sub check_mutate ($) {
515     my ($r) = @_;
516     $r->check();
517     return $r->{Mutate};
518 }
519
520 sub username ($) {
521     my ($r) = @_;
522     $r->check();
523     return $r->{Username};
524
525 sub hidden_val ($) {
526     my ($r) = @_;
527     $r->check();
528     return defined $r->{Assoc} ? $r->{Assoc} : '';
529 }
530
531 #---------- simple wrappers ----------
532
533 sub hidden_hargs ($) {
534     my ($r) = @_;
535     return (-name => $r->{S}{param_name},
536             -default => $r->hidden_val());
537 }
538
539 sub hidden_html ($) {
540     my ($r) = @_;
541     return hidden($r->hidden_hargs());
542 }
543
544 sub cookiea_cargs ($) {
545     my ($r) = @_;
546     return (-name => $r->{S}{cookie_name},
547             -value => hidden_val());
548 }
549
550 __END__
551
552 =head1 NAME
553
554 CGI::Auth::Hybrid - web authentication optionally using cookies
555
556 =head1 SYNOPSYS
557
558  my $verifier = CGI::Auth::Hybrid->new_verifier(setting => value,...);
559  my $authreq = $verifier->new_request($cgi_request_object);
560
561  my $authreq = CGI::Auth::Hybrid->new_request($cgi_request_object,
562                                               setting => value,...);
563
564 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
565
566  $authreq->check_ok() or return;
567
568  blah blah blah
569  $authreq->mutating();
570  blah blah blah
571
572 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
573
574  my $divert_kind = $authreq->check_divert();
575  if ($divert_kind) {
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
580      ... etc.
581      }
582  }
583