chiark / gitweb /
070603dd685096f5e182fdeaeb28689302b286f4
[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 _def_is_logout ($$) {
38     my ($c,$r) = @_;
39     foreach my $pn (@{ $r->{S}{logout_param_names} }) {
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(logout)],
62             promise_check_mutate => 0,
63             get_param => sub { $_[0]->param($_[2]) },
64             get_cah_cookie => sub { $_[0]->cookie($s->{S}{cookie_name}) },
65             get_method => sub { $_[0]->request_method() },
66             is_login => sub { defined $_[1]->_rp('password_param_name') },
67             login_ok => sub { die },
68             is_logout => \&_def_is_logout,
69             is_page => sub { return 1 },
70         },
71         Dbh => undef,
72     };
73     my ($k,$v);
74     while (($k,$v,@_) = @_) {
75         die "unknown setting $k" unless exists $s->{S}{$k};
76         $s->{S}{$k} = $v;
77     }
78     bless $s, $class;
79     $s->_dbopen();
80     return $s;
81 }
82
83 sub _dbopen ($) {
84     my ($s) = @_;
85     my $dbh = $s->{Dbh};
86     return $dbh if $dbh; 
87
88     $s->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=$s->{S}{assocdb_path}";
89
90     my $u = umask 077;
91     $dbh = DBI->open($s->{S}{assocdb_dsn}, $s->{S}{assocdb_user}, 
92                      $s->{S}{assocdb_password}, { 
93                          AutoCommit => 0, RaiseError => 1,
94                      });
95     die "${assocdb_dsn} $! ?" unless $dbh;
96     $s->{Dbh} = $dbh;
97
98     $dbh->do("BEGIN");
99
100     eval {
101         $dbh->do("CREATE TABLE $s->{S}{assocdb_table} (".
102                  " associdh VARCHAR PRIMARY KEY,".
103                  " username VARCHAR,".
104                  " last INTEGER NOT NULL"
105                  ")");
106     };
107     return $dbh;
108 }
109
110 #---------- request object methods ----------
111
112 sub new_request {
113     my ($classbase, $cgi, @extra) = @_;
114     if (!ref $classbase) {
115         $classbase = $classbase->new_verifier(@extra);
116     } else {
117         die if @extra;
118     }
119     my $r = {
120         S => $classbase->{S},
121         Dbh => $classbase->{Dbh},
122         Cgi => $cgi,
123     };
124     bless $r, ref $classbase;
125 }
126
127 sub _ch ($$@) { # calls an application hook
128     my ($r,$methname, @args) = @_;
129     my $methfunc = $r->{S}{$methname};
130     return $methfunc->($r->{Cgi}, $r, @args);
131 }
132
133 sub _rp ($$@) {
134     my ($r,$pnvb) = @_;
135     my $pn = $r->{S}{$pnvb};
136     my $p = $r->_ch('get_param',$pn)
137 }
138
139 # pages/param-sets are
140 #   n normal non-mutating page
141 #   r retrieval of information for JS, non-mutating
142 #   m mutating page
143 #   u update of information by JS, mutating
144 #   i login
145 #   o logout
146
147
148 # in cook and par,
149 #    a, aN     anything including -
150 #    t, tN     temporary value (in our db, no logged in user yet)
151 #    y, yN     value corresponds to logged-in user
152 #    n, nN     value not in our db
153 #    x, xN     t or y
154 #    -         no value supplied
155 # if N differs the case applies only when the two values differ
156 # (eg,   a1 y2   does not apply when the logged-in value is supplied twice)
157
158 # "stale session" means request originates from a page from a login
159 # session which has been revoked (eg by logout); "cleared session"
160 # means request originates from a browser which has a different (or
161 # no) cookie.
162
163     # Case analysis, cookie mode, app promises re mutate:
164     # cook parm meth form
165     #                      
166     #  any -   POST  nrmuoi   bug or attack, fail
167     #  any -   GET    rmuoi   bug or attack, fail
168     #  any any GET     muoi   bug or attack, fail
169     #  any t   any   nrmuo    bug or attack, fail
170     #
171     #  a1  a2  POST      o    logout
172     #                           if a1 is valid, revoke it
173     #                           if a2 is valid, revoke it
174     #                           delete cookie
175     #                           redirect to "just logged out" page
176     #                             (which contains link to login form)
177     #
178     #  -   t   POST       i   complain about cookies being disabled
179     #
180     #  any n   POST       i   complain about stale login form
181     #                           show new login form
182     #
183     #  x1  t2  POST       i   login (or switch user)
184     #                           revoke x1 if it was valid and !=t2
185     #                           upgrade t2 to y2 in our db (setting username)
186     #                           set cookie to t2
187     #                           redirect to GET of remaining params
188     #
189     #  t1  a2  ANY   nrmu     treat as  - a2 ANY
190     #
191     #  y   -   GET   n        cross-site link
192     #                           show data
193     #
194     #  y   y   GET   nr       fine, show page or send data
195     #  y   y   POST  nrmu     mutation is OK, do operation
196     #
197     #  y1  y2  GET   nr       request from stale page
198     #                           do not revoke y2 as not RESTful
199     #                           treat as   y1 n GET
200     #
201     #  y1  y2  POST  nrmu     request from stale page
202     #                           revoke y2
203     #                           treat as   y1 n POST
204     #
205     #  y   n   GET   n        intra-site link from stale page,
206     #                           treat as cross-site link, show data
207     #
208     #  y   n   POST  n m      intra-site form submission from stale page
209     #                           show "session interrupted"
210     #                           with link to main data page
211     #
212     #  y   n   GET    r       intra-site request from stale page
213     #                           fail
214     #
215     #  y   n   POST   r u     intra-site request from stale page
216     #                           fail
217     #
218     #  -/n y2  GET   nr       intra-site link from cleared session
219     #                           do not revoke y2 as not RESTful
220     #                           treat as   -/n n GET
221     #
222     #  -/n y2  POST  nrmu     request from cleared session
223     #                           revoke y2
224     #                           treat as   -/n n POST
225     #
226     #  -/n n   GET   n        cross-site link but user not logged in
227     #                           show login form with redirect to orig params
228     #
229     #  -/n n   GET    rmu     user not logged in
230     #                           fail
231     #
232     #  -/n n   POST  nrmu     user not logged in
233     #                           fail
234
235 sub check_divert ($) {
236     my ($r) = @_;
237
238     my $cookv = $r->_ch('get_cah_cookie');
239     my $parmv = $r->_rp('assoc_param_name');
240
241     my $cookt = $r->_db_lookup($cookv);
242     my $parmt = $r->_db_lookup($parmv);
243
244     if ($r->_ch('is_logout')) {
245         $r->_must_be_post();
246         die unless $parmt;
247         $r->_db_perhaps_revoke($cookv);
248         $r->_db_perhaps_revoke($parmv);
249         $r->_queue_set_cookie('');
250         return 'REDIRECT-LOGGEDOUT';
251     }
252     if ($r->_ch('is_login')) {
253         return 'NOCOOKIE' if !$cookt && $parmt eq 't';
254         return 'LOGIN-STALE' if $parmt eq 'n';
255         $r->_db_perhaps_revoke($cookv) 
256             if defined $cookv && !(defined $parmv && $cookv eq $parmv);
257         $r->_queue_set_cookie($parmv);
258         my $username = $r->_ch('login_ok');
259         return 'LOGIN-BAD' unless defined $username && length $username;
260         $r->_db_record_login_ok($parmv,$username);
261         return 'REDIRECT-LOGGEDIN';
262     }
263     if (!$r->{S}{promise_check_mutate}) {
264         something with method get, check parameter, etc.
265         return 'FRONTPAGE';
266     }
267     
268
269 UP TO HERE
270
271 sub _check_core ($) {
272     my ($r) = @_;
273     my $qassoc = $r->_ch('get_param');
274     my ($nassoc,$nmutate);
275     if (!defined $r->{S}{cookie_name}) {
276         # authentication is by hidden form parameter only
277         return undef unless defined $qassoc;
278         $nassoc = $qassoc;
279         $nmutate = 1;
280     } else {
281         # authentication is by cookie
282         # the cookie suffices for read-only GET requests
283         # for mutating and non-GET requests we require hidden param too
284         my $cassoc = $r->_ch('get_cookie');
285         return undef unless defined $cassoc;
286         $nassoc = $cassoc;
287         if (defined $qassoc && $qassoc eq $cassoc) {
288             $nmutate = 1;
289         } else {
290             return undef unless $r->{S}{promise_check_mutate};
291             return undef unless $r->_ch('get_method') eq 'GET';
292             $nmutate = 0;
293         }
294     }
295
296     my $dbh = $r->{Dbh};
297     my ($nusername, $nlast) =
298         $dbh->selectrow_array("SELECT username, last".
299                               " FROM $r->{S}{assocdb_table}".
300                               " WHERE associd = ?", {}, $nassoc);
301     return undef unless defined $nusername;
302     my $timeout = $r->{S}{login_timeout};
303     return undef unless !defined $timeout || time <= $nlast + $timeout;
304
305     # hooray
306     return ($nusername, $nassoc, $nmutate);
307 }
308
309 sub record_login ($$) {
310     my ($r,$nusername) = @_;
311     my $rsp = $r->{S}{random_source};
312     my $rsf = new IO::File $rsp, '<' or die "$rsp $!";
313     my $bytes = ($r->{S}{associdlen} + 7) >> 3;
314     my $nassocbin;
315     $!=0;
316     read($rsf,$nassocbin,$bytes) == $bytes or die "$rsp $!";
317     close $rsf;
318     my $nassoc = unpack "H*", $nassocbin;
319     my $dbh = $r->{Dbh};
320     $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
321              " (associd, username, last) VALUES (?,?,?)", {},
322              $nassoc, $nusername, time);
323     $dbh->do("COMMIT");
324     $r->{U} = $nusername;
325     $r->{A} = $nassoc;
326 }
327
328 sub _check ($) {
329     my ($r) = @_;
330
331     return if exists $r->{Username};
332     ($r->{Username}, $r->{Assoc}, $r->{Mutate}) = $r->_check();
333
334     if (defined $r->{Assoc}) {
335         $dbh->do("UPDATE $r->{S}{assocdb_table}".
336                  " SET last = ?".
337                  " WHERE associd = ?", {}, time, $nassoc);
338         $dbh->do("COMMIT");
339     }
340 }
341
342 sub logout ($) {
343     my ($r) = @_;
344
345     my ($nusername, $nassoc, $nmutate) = $r->_check();
346     return undef unless $nmutate;
347     $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
348              " WHERE associd = ?", {}, $nassoc);
349     $dbh->do("COMMIT");
350     return $nusername;
351 }
352
353 sub check ($) {
354     my ($r) = @_;
355     $r->_check();
356     return !!defined $r->{Username};
357 }
358
359 sub check_mutate ($) {
360     my ($r) = @_;
361     $r->check();
362     return $r->{Mutate};
363 }
364
365 sub username ($) {
366     my ($r) = @_;
367     $r->check();
368     return $r->{Username};
369
370 sub hidden_val ($) {
371     my ($r) = @_;
372     $r->check();
373     return defined $r->{Assoc} ? $r->{Assoc} : '';
374 }
375
376 #---------- simple wrappers ----------
377
378 sub hidden_hargs ($) {
379     my ($r) = @_;
380     return (-name => $r->{S}{param_name},
381             -default => $r->hidden_val());
382 }
383
384 sub hidden_html ($) {
385     my ($r) = @_;
386     return hidden($r->hidden_hargs());
387 }
388
389 sub cookiea_cargs ($) {
390     my ($r) = @_;
391     return (-name => $r->{S}{cookie_name},
392             -value => hidden_val());
393 }
394
395 __END__
396
397 =head1 NAME
398
399 CGI::Auth::Hybrid - web authentication optionally using cookies
400
401 =head1 SYNOPSYS
402
403  my $verifier = CGI::Auth::Hybrid->new_verifier(setting => value,...);
404  my $authreq = $verifier->new_request($cgi_request_object);
405
406  my $authreq = CGI::Auth::Hybrid->new_request($cgi_request_object,
407                                               setting => value,...);
408
409 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
410
411  $authreq->check_ok() or return;
412
413  blah blah blah
414  $authreq->mutating();
415  blah blah blah
416
417 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
418
419  my $divert_kind = $authreq->check_divert();
420  if ($divert_kind) {
421      if ($divert_kind eq 'LOGGEDOUT') {
422          print "goodbye you are now logged out" and quit
423      } elsif ($divert_kind eq 'NOCOOKIES') {
424          print "you need cookies" and quit
425      ... etc.
426      }
427  }
428