chiark / gitweb /
77454c229b56b52399c630392e31453dc94c7a13
[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     # Case analysis, cookie mode, app promises re mutate:
173     # cook par meth  form
174     #                      
175     #  y   y   GET   nr       fine, show page or send data
176     #
177     #  y   -   GET   n        cross-site link
178     #                           show data
179     #  y1  y2  GET   n        intra-site link
180     #                           from session no longer known to browser
181     #                           do not revoke y2 as not a POST so not RESTful
182     #                           treat as cross-site link, show data
183     #  y   n   GET   n        intra-site link from stale session,
184     #                           treat as cross-site link, show data
185     #
186     #  y   -   GET    r       bug or attack, fail
187     #  y1  y2  GET    r       intra-site data request
188     #                           from session no longer known to browser
189     #                           do not revoke y2 as not a POST so not RESTful
190     #                           fail
191     #  y   n   GET    r       intra-site data request from stale session
192     #                           fail
193     #
194     #  -/n y2  GET   n        cross-site link
195     #                         but user has cleared cookies, revoke session
196     #                           show login form
197     #
198     #  -/n y2  GET    rmuio   user has cleared cookies, revoke session
199     #                           then as for   - - GET
200     #
201     #  n   any GET   n        cross-site link but user not logged in
202     #                           show login form
203     #
204     #  n   any GET    r       data request from stale session
205     #                           fail
206     #
207     #  any any GET     muoi   bug or attack, fail
208     #
209     #  y   y   POST  nrmu     mutation is OK, do operation
210     #  y   y   POST      o    logout
211     #  y   y   POST       i   login, redirect to GET of remaining params
212     #
213     #  any -   POST           bug or xsrf attack, fail
214     #
215     #  n/y1 y2 POST   r       intra-site form submission
216     #                           from session no longer known to browser
217     #                           revoke y2
218     #                           show "session interrupted" login form
219     #  n/y1 y2 POST    m      intra-site js operation
220     #                           from session no longer known to browser
221     #                           revoke y2
222     #                           fail
223     #  y   n   POST  r        intra-site form submission from stale session
224     #                           show "session interrupted"
225     #  y   n   POST    m      intra-site form submission from stale session
226     #                           fail
227     #
228     #  -   y2  GET            intra-site link or data request
229     #                           from session no longer known to browser
230     #                           fail
231
232     #  -   y2        any      req from old session y2, del y2, show login
233     #  y1  y2        any      req from old session y2, del y2, show y1 main
234
235     #  y1 any  GET   non-mut  cross-site link
236     #  y1 any  GET   non-mut  no mutation, show page providing new par
237     #
238     #  A   B         any      page from old session or cross-site request
239     #  any y2 POST  logout    do logout y2
240
241
242     #  any any GET   mutate   bug or attack, forbidden, call die
243
244     my $dbh = $r->{Dbh};
245     my ($nusername, $nlast) =
246         $dbh->selectrow_array("SELECT username, last".
247                               " FROM $r->{S}{assocdb_table}".
248                               " WHERE associd = ?", {}, $nassoc);
249     return undef unless defined $nusername;
250     my $timeout = $r->{S}{login_timeout};
251     return undef unless !defined $timeout || time <= $nlast + $timeout;
252
253     # hooray
254     return ($nusername, $nassoc, $nmutate);
255 }
256
257 sub _check ($) {
258     my ($r) = @_;
259
260     return if exists $r->{Username};
261     ($r->{Username}, $r->{Assoc}, $r->{Mutate}) = $r->_check();
262
263     if (defined $r->{Assoc}) {
264         $dbh->do("UPDATE $r->{S}{assocdb_table}".
265                  " SET last = ?".
266                  " WHERE associd = ?", {}, time, $nassoc);
267         $dbh->do("COMMIT");
268     }
269 }
270
271 sub logout ($) {
272     my ($r) = @_;
273
274     my ($nusername, $nassoc, $nmutate) = $r->_check();
275     return undef unless $nmutate;
276     $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
277              " WHERE associd = ?", {}, $nassoc);
278     $dbh->do("COMMIT");
279     return $nusername;
280 }
281
282 sub check ($) {
283     my ($r) = @_;
284     $r->_check();
285     return !!defined $r->{Username};
286 }
287
288 sub check_mutate ($) {
289     my ($r) = @_;
290     $r->check();
291     return $r->{Mutate};
292 }
293
294 sub username ($) {
295     my ($r) = @_;
296     $r->check();
297     return $r->{Username};
298
299 sub hidden_val ($) {
300     my ($r) = @_;
301     $r->check();
302     return defined $r->{Assoc} ? $r->{Assoc} : '';
303 }
304
305 #---------- simple wrappers ----------
306
307 sub hidden_hargs ($) {
308     my ($r) = @_;
309     return (-name => $r->{S}{param_name},
310             -default => $r->hidden_val());
311 }
312
313 sub hidden_html ($) {
314     my ($r) = @_;
315     return hidden($r->hidden_hargs());
316 }
317
318 sub cookiea_cargs ($) {
319     my ($r) = @_;
320     return (-name => $r->{S}{cookie_name},
321             -value => hidden_val());
322 }
323
324 __END__
325
326 =head1 NAME
327
328 CGI::Auth::Hybrid - web authentication optionally using cookies
329
330 =head1 SYNOPSYS
331
332  my $verifier = CGI::Auth::Hybrid->new_verifier(setting => value,...);
333  my $authreq = $verifier->new_request($cgi_request_object);
334
335  my $authreq = CGI::Auth::Hybrid->new_request($cgi_request_object,
336                                               setting => value,...);
337
338 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
339
340  if ( form submission is login request ) {
341      check login details, if wrong print error and quit
342      $authreq->record_login(...username...);
343  }
344  if ( form submission is logout request ) {
345      my $logged_out_user = $authreq->logout();
346      if (!defined $logged_out_user) {
347          print "you are not logged in" error and quit
348      } else {
349          print "goodbye $username you are now logged out" and quit
350      }
351  }
352  if ( !$authreq->check() ) {
353      display login form, quit
354
355
356 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
357
358  if ( form submission is login request ) {
359      check login details, if wrong print error and quit
360      $authreq->record_login(...username...);
361  }
362  if ( !$authreq->check() ) {
363      display login form, quit
364  if ( form submission is logout request ) {
365      die unless $authreq->mutate();
366      my $logged_out_user = $authreq->logout();
367      if (!defined $logged_out_user) {
368          print "you are not logged in" error and quit
369      } else {
370          print "goodbye $username you are now logged out" and quit
371      }
372  }
373
374
375 advantages of cookie
376  - user can sort of log out by clearing cookies
377  - sophisticated applications can have get-requests