chiark / gitweb /
wip
[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 #---------- verifier object methods ----------
46
47 sub new_verifier {
48     my $class = shift;
49     my $s = {
50         S => {
51             assocdb_path => 'cah-assocs.db';
52             assocdb_dsn => undef,
53             assocdb_user => '',
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 },
72         },
73         Dbh => undef,
74     };
75     my ($k,$v);
76     while (($k,$v,@_) = @_) {
77         die "unknown setting $k" unless exists $s->{S}{$k};
78         $s->{S}{$k} = $v;
79     }
80     bless $s, $class;
81     $s->_dbopen();
82     return $s;
83 }
84
85 sub _dbopen ($) {
86     my ($s) = @_;
87     my $dbh = $s->{Dbh};
88     return $dbh if $dbh; 
89
90     $s->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=$s->{S}{assocdb_path}";
91
92     my $u = umask 077;
93     $dbh = DBI->open($s->{S}{assocdb_dsn}, $s->{S}{assocdb_user}, 
94                      $s->{S}{assocdb_password}, { 
95                          AutoCommit => 0, RaiseError => 1,
96                      });
97     die "${assocdb_dsn} $! ?" unless $dbh;
98     $s->{Dbh} = $dbh;
99
100     $dbh->do("BEGIN");
101
102     eval {
103         $dbh->do("CREATE TABLE $s->{S}{assocdb_table} (".
104                  " associdh VARCHAR PRIMARY KEY,".
105                  " username VARCHAR,".
106                  " last INTEGER NOT NULL"
107                  ")");
108     };
109     return $dbh;
110 }
111
112 #---------- request object methods ----------
113
114 sub new_request {
115     my ($classbase, $cgi, @extra) = @_;
116     if (!ref $classbase) {
117         $classbase = $classbase->new_verifier(@extra);
118     } else {
119         die if @extra;
120     }
121     my $r = {
122         S => $classbase->{S},
123         Dbh => $classbase->{Dbh},
124         Cgi => $cgi,
125     };
126     bless $r, ref $classbase;
127 }
128
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);
133 }
134
135 sub _rp ($$@) {
136     my ($r,$pnvb) = @_;
137     my $pn = $r->{S}{$pnvb};
138     my $p = $r->_ch('get_param',$pn)
139 }
140
141 # pages/param-sets are
142 #   n normal non-mutating page
143 #   r retrieval of information for JS, non-mutating
144 #   m mutating page
145 #   u update of information by JS, mutating
146 #   i login
147 #   o logout
148 #   O "you have just logged out" page load
149
150 # in cook and par,
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
155 #    x, xN     t or y
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)
159
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
163 # no) cookie.
164
165     # Case analysis, cookie mode, app promises re mutate:
166     # cook parm meth form
167     #                      
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
172     #
173     #  -   -   GET         O  "just logged out" page
174     #  (any other)         O  bug or attack, fail
175     #
176     #  a1  a2  POST      o    logout
177     #                           if a1 is valid, revoke it
178     #                           if a2 is valid, revoke it
179     #                           delete cookie
180     #                           redirect to "just logged out" page
181     #                             (which contains link to login form)
182     #
183     #  -   t   POST       i   complain about cookies being disabled
184     #                           (with link to login form)
185     #
186     #  any n   POST       i   complain about stale login form
187     #                           show new login form
188     #
189     #  x1  t2  POST       i   login (or switch user)
190     #                           if bad
191     #                             show new login form
192     #                           if good
193     #                             revoke x1 if it was valid and !=t2
194     #                             upgrade t2 to y2 in our db (setting username)
195     #                             set cookie to t2
196     #                             redirect to GET of remaining params
197     #
198     #  t1  a2  ANY   nrmu     treat as  - a2 ANY
199     #
200     #  y   -   GET   n        cross-site link
201     #                           show data
202     #
203     #  y   y   GET   nr       fine, show page or send data
204     #  y   y   POST  nrmu     mutation is OK, do operation
205     #
206     #  y1  y2  GET   nr       request from stale page
207     #                           do not revoke y2 as not RESTful
208     #                           treat as   y1 n GET
209     #
210     #  y1  y2  POST  nrmu     request from stale page
211     #                           revoke y2
212     #                           treat as   y1 n POST
213     #
214     #  y   n   GET   n        intra-site link from stale page,
215     #                           treat as cross-site link, show data
216     #
217     #  y   n   POST  n m      intra-site form submission from stale page
218     #                           show "session interrupted"
219     #                           with link to main data page
220     #
221     #  y   n   GET    r       intra-site request from stale page
222     #                           fail
223     #
224     #  y   n   POST   r u     intra-site request from stale page
225     #                           fail
226     #
227     #  -/n y2  GET   nr       intra-site link from cleared session
228     #                           do not revoke y2 as not RESTful
229     #                           treat as   -/n n GET
230     #
231     #  -/n y2  POST  nrmu     request from cleared session
232     #                           revoke y2
233     #                           treat as   -/n n POST
234     #
235     #  -/n n   GET   n        cross-site link but user not logged in
236     #                           show login form with redirect to orig params
237     #
238     #  -/n n   GET    rmu     user not logged in
239     #                           fail
240     #
241     #  -/n n   POST  n m      user not logged in
242     #                           show login form
243     #
244     #  -/n n   POST   r u     user not logged in
245     #                           fail
246
247 sub check_divert ($) {
248     my ($r) = @_;
249
250     my $meth = $r->_ch('get_method');
251     my $cookv = $r->_ch('get_cah_cookie');
252     my $parmv = $r->_rp('assoc_param_name');
253
254     my $cookt = $r->_db_lookup($cookv);
255     my $parmt = $r->_db_lookup($parmv);
256
257     if ($r->_ch('is_logout')) {
258         $r->_must_be_post();
259         die unless $parmt;
260         $r->_db_perhaps_revoke($cookv);
261         $r->_db_perhaps_revoke($parmv);
262         $r->_queue_set_cookie('');
263         return 'REDIRECT-LOGGEDOUT'
264     }
265     if ($r->_ch('is_loggedout')) {
266         die unless $meth eq 'GET';
267         die unless $cookt;
268         die unless $parmt;
269         return ('SMALLPAGE-LOGGEDOUT', "You have been logged out.");
270     }
271     if ($r->_ch('is_login')) {
272         $r->_must_be_post();
273         return ('LOGIN-STALE',
274                 "This session was stale and you need to log in again.")
275             if $parmt eq 'n';
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';
282         return ('LOGIN-BAD',
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';
291     }
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"
298         }
299     }
300     if ($cookt eq 't') {
301         $cookt = undef;
302     }
303     die if $parmt eq 't';
304
305     if ($cookt eq 'y' && $parmt eq 'y' && $cookv ne $parmv) {
306         $r->_db_perhaps_revoke($parmv) if $meth eq 'POST';
307         $parmt = 'n';
308     }
309
310     if ($cookt ne 'y') {
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.");
317         } else {
318             return ('LOGIN-FRESH',
319                     "You need to log in again.");
320         }
321     }
322
323     die unless $cookt eq 'y';
324     die unless $parmt eq 'y';
325     die unless $cookv eq $parmv;
326     return '';
327 }
328
329 UP TO HERE
330
331 sub _check_core ($) {
332     my ($r) = @_;
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;
338         $nassoc = $qassoc;
339         $nmutate = 1;
340     } else {
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;
346         $nassoc = $cassoc;
347         if (defined $qassoc && $qassoc eq $cassoc) {
348             $nmutate = 1;
349         } else {
350             return undef unless $r->{S}{promise_check_mutate};
351             return undef unless $r->_ch('get_method') eq 'GET';
352             $nmutate = 0;
353         }
354     }
355
356     my $dbh = $r->{Dbh};
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;
364
365     # hooray
366     return ($nusername, $nassoc, $nmutate);
367 }
368
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;
374     my $nassocbin;
375     $!=0;
376     read($rsf,$nassocbin,$bytes) == $bytes or die "$rsp $!";
377     close $rsf;
378     my $nassoc = unpack "H*", $nassocbin;
379     my $dbh = $r->{Dbh};
380     $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
381              " (associd, username, last) VALUES (?,?,?)", {},
382              $nassoc, $nusername, time);
383     $dbh->do("COMMIT");
384     $r->{U} = $nusername;
385     $r->{A} = $nassoc;
386 }
387
388 sub _check ($) {
389     my ($r) = @_;
390
391     return if exists $r->{Username};
392     ($r->{Username}, $r->{Assoc}, $r->{Mutate}) = $r->_check();
393
394     if (defined $r->{Assoc}) {
395         $dbh->do("UPDATE $r->{S}{assocdb_table}".
396                  " SET last = ?".
397                  " WHERE associd = ?", {}, time, $nassoc);
398         $dbh->do("COMMIT");
399     }
400 }
401
402 sub logout ($) {
403     my ($r) = @_;
404
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);
409     $dbh->do("COMMIT");
410     return $nusername;
411 }
412
413 sub check ($) {
414     my ($r) = @_;
415     $r->_check();
416     return !!defined $r->{Username};
417 }
418
419 sub check_mutate ($) {
420     my ($r) = @_;
421     $r->check();
422     return $r->{Mutate};
423 }
424
425 sub username ($) {
426     my ($r) = @_;
427     $r->check();
428     return $r->{Username};
429
430 sub hidden_val ($) {
431     my ($r) = @_;
432     $r->check();
433     return defined $r->{Assoc} ? $r->{Assoc} : '';
434 }
435
436 #---------- simple wrappers ----------
437
438 sub hidden_hargs ($) {
439     my ($r) = @_;
440     return (-name => $r->{S}{param_name},
441             -default => $r->hidden_val());
442 }
443
444 sub hidden_html ($) {
445     my ($r) = @_;
446     return hidden($r->hidden_hargs());
447 }
448
449 sub cookiea_cargs ($) {
450     my ($r) = @_;
451     return (-name => $r->{S}{cookie_name},
452             -value => hidden_val());
453 }
454
455 __END__
456
457 =head1 NAME
458
459 CGI::Auth::Hybrid - web authentication optionally using cookies
460
461 =head1 SYNOPSYS
462
463  my $verifier = CGI::Auth::Hybrid->new_verifier(setting => value,...);
464  my $authreq = $verifier->new_request($cgi_request_object);
465
466  my $authreq = CGI::Auth::Hybrid->new_request($cgi_request_object,
467                                               setting => value,...);
468
469 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
470
471  $authreq->check_ok() or return;
472
473  blah blah blah
474  $authreq->mutating();
475  blah blah blah
476
477 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
478
479  my $divert_kind = $authreq->check_divert();
480  if ($divert_kind) {
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
485      ... etc.
486      }
487  }
488