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