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 _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         return 'LOGOUT';
250     }
251     if ($r->_ch('is_login')) {
252         return 'NOCOOKIE' if !$cookt && $parmt eq 't';
253         return 'LOGIN-STALE' if $parmt eq 'n';
254         $r->_db_perhpa
255         my $username = $r->_ch('login_ok');
256         return 'LOGIN-BAD' unless defined $username && length $username;
257         $r->_db_
258
259         }
260         
261
262         $r->_will_set_cookie('');
263         
264     }
265
266
267 UP TO HERE
268
269 sub _check_core ($) {
270     my ($r) = @_;
271     my $qassoc = $r->_ch('get_param');
272     my ($nassoc,$nmutate);
273     if (!defined $r->{S}{cookie_name}) {
274         # authentication is by hidden form parameter only
275         return undef unless defined $qassoc;
276         $nassoc = $qassoc;
277         $nmutate = 1;
278     } else {
279         # authentication is by cookie
280         # the cookie suffices for read-only GET requests
281         # for mutating and non-GET requests we require hidden param too
282         my $cassoc = $r->_ch('get_cookie');
283         return undef unless defined $cassoc;
284         $nassoc = $cassoc;
285         if (defined $qassoc && $qassoc eq $cassoc) {
286             $nmutate = 1;
287         } else {
288             return undef unless $r->{S}{promise_check_mutate};
289             return undef unless $r->_ch('get_method') eq 'GET';
290             $nmutate = 0;
291         }
292     }
293
294     my $dbh = $r->{Dbh};
295     my ($nusername, $nlast) =
296         $dbh->selectrow_array("SELECT username, last".
297                               " FROM $r->{S}{assocdb_table}".
298                               " WHERE associd = ?", {}, $nassoc);
299     return undef unless defined $nusername;
300     my $timeout = $r->{S}{login_timeout};
301     return undef unless !defined $timeout || time <= $nlast + $timeout;
302
303     # hooray
304     return ($nusername, $nassoc, $nmutate);
305 }
306
307 sub record_login ($$) {
308     my ($r,$nusername) = @_;
309     my $rsp = $r->{S}{random_source};
310     my $rsf = new IO::File $rsp, '<' or die "$rsp $!";
311     my $bytes = ($r->{S}{associdlen} + 7) >> 3;
312     my $nassocbin;
313     $!=0;
314     read($rsf,$nassocbin,$bytes) == $bytes or die "$rsp $!";
315     close $rsf;
316     my $nassoc = unpack "H*", $nassocbin;
317     my $dbh = $r->{Dbh};
318     $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
319              " (associd, username, last) VALUES (?,?,?)", {},
320              $nassoc, $nusername, time);
321     $dbh->do("COMMIT");
322     $r->{U} = $nusername;
323     $r->{A} = $nassoc;
324 }
325
326 sub _check ($) {
327     my ($r) = @_;
328
329     return if exists $r->{Username};
330     ($r->{Username}, $r->{Assoc}, $r->{Mutate}) = $r->_check();
331
332     if (defined $r->{Assoc}) {
333         $dbh->do("UPDATE $r->{S}{assocdb_table}".
334                  " SET last = ?".
335                  " WHERE associd = ?", {}, time, $nassoc);
336         $dbh->do("COMMIT");
337     }
338 }
339
340 sub logout ($) {
341     my ($r) = @_;
342
343     my ($nusername, $nassoc, $nmutate) = $r->_check();
344     return undef unless $nmutate;
345     $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
346              " WHERE associd = ?", {}, $nassoc);
347     $dbh->do("COMMIT");
348     return $nusername;
349 }
350
351 sub check ($) {
352     my ($r) = @_;
353     $r->_check();
354     return !!defined $r->{Username};
355 }
356
357 sub check_mutate ($) {
358     my ($r) = @_;
359     $r->check();
360     return $r->{Mutate};
361 }
362
363 sub username ($) {
364     my ($r) = @_;
365     $r->check();
366     return $r->{Username};
367
368 sub hidden_val ($) {
369     my ($r) = @_;
370     $r->check();
371     return defined $r->{Assoc} ? $r->{Assoc} : '';
372 }
373
374 #---------- simple wrappers ----------
375
376 sub hidden_hargs ($) {
377     my ($r) = @_;
378     return (-name => $r->{S}{param_name},
379             -default => $r->hidden_val());
380 }
381
382 sub hidden_html ($) {
383     my ($r) = @_;
384     return hidden($r->hidden_hargs());
385 }
386
387 sub cookiea_cargs ($) {
388     my ($r) = @_;
389     return (-name => $r->{S}{cookie_name},
390             -value => hidden_val());
391 }
392
393 __END__
394
395 =head1 NAME
396
397 CGI::Auth::Hybrid - web authentication optionally using cookies
398
399 =head1 SYNOPSYS
400
401  my $verifier = CGI::Auth::Hybrid->new_verifier(setting => value,...);
402  my $authreq = $verifier->new_request($cgi_request_object);
403
404  my $authreq = CGI::Auth::Hybrid->new_request($cgi_request_object,
405                                               setting => value,...);
406
407 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
408
409  $authreq->check_ok() or return;
410
411  blah blah blah
412  $authreq->mutating();
413  blah blah blah
414
415 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
416
417  my $divert_kind = $authreq->check_divert();
418  if ($divert_kind) {
419      if ($divert_kind eq 'LOGGEDOUT') {
420          print "goodbye you are now logged out" and quit
421      } elsif ($divert_kind eq 'NOCOOKIES') {
422          print "you need cookies" and quit
423      ... etc.
424      }
425  }
426