chiark / gitweb /
wip, before redo params
[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 use Locale::Gettext;
35
36 #---------- default callbacks ----------
37
38 sub has_a_param ($$) {
39     my ($c,$cn) = @_;
40     foreach my $pn (@{ $r->{S}{$cn} }) {
41         return 1 if $r->_cm('get_param')($pn);
42     }
43     return 0;
44 }
45
46 sub get_param_list ($$) {
47     my ($c) = @_;
48     my @p = ( );
49     foreach my $name ($c->param()) {
50         foreach my $val ($c->param($name)) {
51             push @p, $name, $val;
52         }
53     }
54     return @p;
55 }
56
57 sub get_cookie_domain ($$$) {
58     my ($c,$r) = @_;
59     my $uri = new URI $r->_ch('get_url');
60     return $uri->host();
61 }
62
63 sub construct_cookie ($$$) {
64     my ($c, $r, $cookv) = @_;
65     return $c->cookie(-name => $r->{S}{cookie_name},
66                       -value => $cookv,
67                       -path => $r->{S}{cookie_path},
68                       -domain => $r->_ch('get_cookie_domain'),
69                       -expires => '+'.$r->{S}{login_timeout}.'s',
70                       -secure => $r->{S}{encrypted_only});
71 }
72
73 sub do_redirect_cgi ($$$$) {
74     my ($c, $r, $new_url, $cookie) = @_;
75     my @ha = ('text/html',
76               -status => '303 See other',
77               -location => $new_url);
78     push @ha, (-cookie => $cookie) if defined $cookie;
79     $r->_print($c->header(@ha),
80                $r->_ch('gen_start_html')($r->_gt('Redirection')),
81                '<a href="'.escapeHTML($new_url).'">',
82                $r->_gt("If you aren't redirected, click to continue."),
83                "</a>",
84                $c->_ch('gen_end_html'));
85 }
86
87 sub gen_plain_login_form ($$) {
88     my ($c,$r, $params) = @_;
89     my @form;
90     push @form, ('<form method="POST" action="',
91                  escapeHTML($r->_ch('get_url')).'>',
92                  '<table>');
93     my $sz = 'size="'.$r->{S}{form_entry_size}.'"';
94     foreach my $up (@{ $r->{S}{username_param_names}}) {
95         push @form, ('<tr><td>',$r->_gt(ucfirst $up),'</td>',
96                      '<td><input type="text" ',$sz,
97                      ' name=',$up,'></td></tr>');
98     }
99     push @form, ('<tr><td>'.$r->_gt('Password'),'</td>',
100                  '<td><input type="password" ',$sz,
101                  ' name="'.$r->{S}{password_param_name}.'"></td></tr>');
102     push @form, ('<tr><td colspan="2">',
103                  '<input type="submit"'.
104                  ' name="'.$r->{S}{login_submit_name}.'"',
105                  ' value="'.$r->_gt('Login').'"></td></tr></table>');
106     foreach my $p (@$params) {
107         
108
109 #---------- verifier object methods ----------
110
111 sub new_verifier {
112     my $class = shift;
113     my $s = {
114         S => {
115             assocdb_path => 'cah-assocs.db';
116             assocdb_dsn => undef,
117             assocdb_user => '',
118             assocdb_password => '',
119             assocdb_table => 'assocs',
120             random_source => '/dev/urandom',
121             associdlen => 128, # bits
122             login_timeout => 86400, # seconds
123             assoc_param_name => 'cah_associd',
124             password_param_name => 'password',
125             username_param_names => [qw(username)],
126             form_entry_size => 60,
127             logout_param_names => [qw(cah_logout)],
128             login_submit_name => [qw(cah_login)],
129             loggedout_param_names => [qw(cah_loggedout)],
130             promise_check_mutate => 0,
131             get_param => sub { $_[0]->param($_[2]) },
132             get_param_list => sub { $_[1]->get_param_list() },
133             get_cookie => sub { $_[0]->cookie($s->{S}{cookie_name}) },
134             get_method => sub { $_[0]->request_method() },
135             get_url => sub { $_[0]->url(); },
136             is_login => sub { defined $_[1]->_rp('password_param_name') },
137             login_ok => sub { die },
138             is_logout => sub { $_[1]->has_a_param('logout_param_names') },
139             is_loggedout => sub { $_[1]->has_a_param('loggedout_param_names') },
140             is_page => sub { return 1 },
141             handle_divert => sub { return 0 },
142             do_redirect => \&do_redirect_cgi, # this hook is allowed to throw
143             cookie_path => "/",
144             get_cookie_domain => \&get_cookie_domain,
145             encrypted_only => 0,
146             gen_start_html => sub { $_[0]->start_html($_[2]); },
147             gen_end_html => sub { $_[0]->end_html(); },
148             gen_login_form => \&gen_plain_login_form,
149             gettext => sub { gettext($_[2]); },
150             };
151         },
152         Dbh => undef,
153     };
154     my ($k,$v);
155     while (($k,$v,@_) = @_) {
156         die "unknown setting $k" unless exists $s->{S}{$k};
157         $s->{S}{$k} = $v;
158     }
159     bless $s, $class;
160     $s->_dbopen();
161     return $s;
162 }
163
164 sub _dbopen ($) {
165     my ($s) = @_;
166     my $dbh = $s->{Dbh};
167     return $dbh if $dbh; 
168
169     $s->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=$s->{S}{assocdb_path}";
170
171     my $u = umask 077;
172     $dbh = DBI->open($s->{S}{assocdb_dsn}, $s->{S}{assocdb_user}, 
173                      $s->{S}{assocdb_password}, { 
174                          AutoCommit => 0, RaiseError => 1,
175                      });
176     die "${assocdb_dsn} $! ?" unless $dbh;
177     $s->{Dbh} = $dbh;
178
179     $dbh->do("BEGIN");
180
181     eval {
182         $dbh->do("CREATE TABLE $s->{S}{assocdb_table} (".
183                  " associdh VARCHAR PRIMARY KEY,".
184                  " username VARCHAR,".
185                  " last INTEGER NOT NULL"
186                  ")");
187     };
188     return $dbh;
189 }
190
191 #---------- request object methods ----------
192
193 sub new_request {
194     my ($classbase, $cgi, @extra) = @_;
195     if (!ref $classbase) {
196         $classbase = $classbase->new_verifier(@extra);
197     } else {
198         die if @extra;
199     }
200     my $r = {
201         S => $classbase->{S},
202         Dbh => $classbase->{Dbh},
203         Cgi => $cgi,
204     };
205     bless $r, ref $classbase;
206 }
207
208 sub _ch ($$@) { # calls an application hook
209     my ($r,$methname, @args) = @_;
210     my $methfunc = $r->{S}{$methname};
211     return $methfunc->($r->{Cgi}, $r, @args);
212 }
213
214 sub _rp ($$@) {
215     my ($r,$pnvb) = @_;
216     my $pn = $r->{S}{$pnvb};
217     my $p = scalar $r->_ch('get_param',$pn)
218 }
219
220 sub _gt ($$) { my ($r, $t) = @_; return $r->_ch('gettext')($t); }
221 sub _print ($$) { my ($r, @t) = @_; return $r->_ch('print')(join '', @t); }
222
223 # pages/param-sets are
224 #   n normal non-mutating page
225 #   r retrieval of information for JS, non-mutating
226 #   m mutating page
227 #   u update of information by JS, mutating
228 #   i login
229 #   o logout
230 #   O "you have just logged out" page load
231
232 # in cook and par,
233 #    a, aN     anything including -
234 #    t, tN     temporary value (in our db, no logged in user yet)
235 #    y, yN     value corresponds to logged-in user
236 #    n, nN     value not in our db
237 #    x, xN     t or y
238 #    -         no value supplied
239 # if N differs the case applies only when the two values differ
240 # (eg,   a1 y2   does not apply when the logged-in value is supplied twice)
241
242 # "stale session" means request originates from a page from a login
243 # session which has been revoked (eg by logout); "cleared session"
244 # means request originates from a browser which has a different (or
245 # no) cookie.
246
247     # Case analysis, cookie mode, app promises re mutate:
248     # cook parm meth form
249     #                      
250     #  any -   POST  nrmuoi   bug or attack, fail
251     #  any -   GET    rmuoi   bug or attack, fail
252     #  any any GET     muoi   bug or attack, fail
253     #  any t   any   nrmu     bug or attack, fail
254     #
255     #  -   -   GET         O  "just logged out" page
256     #  (any other)         O  bug or attack, fail
257     #
258     #  a1  a2  POST      o    logout
259     #                           if a1 is valid, revoke it
260     #                           if a2 is valid, revoke it
261     #                           delete cookie
262     #                           redirect to "just logged out" page
263     #                             (which contains link to login form)
264     #
265     #  -   t   POST       i   complain about cookies being disabled
266     #                           (with link to login form)
267     #
268     #  any n   POST       i   complain about stale login form
269     #                           show new login form
270     #
271     #  x1  t2  POST       i   login (or switch user)
272     #                           if bad
273     #                             show new login form
274     #                           if good
275     #                             revoke x1 if it was valid and !=t2
276     #                             upgrade t2 to y2 in our db (setting username)
277     #                             set cookie to t2
278     #                             redirect to GET of remaining params
279     #
280     #  t1  a2  ANY   nrmu     treat as  - a2 ANY
281     #
282     #  y   -   GET   n        cross-site link
283     #                           show data
284     #
285     #  y   y   GET   nr       fine, show page or send data
286     #  y   y   POST  nrmu     mutation is OK, do operation
287     #
288     #  y1  y2  GET   nr       request from stale page
289     #                           do not revoke y2 as not RESTful
290     #                           treat as   y1 n GET
291     #
292     #  y1  y2  POST  nrmu     request from stale page
293     #                           revoke y2
294     #                           treat as   y1 n POST
295     #
296     #  y   n   GET   n        intra-site link from stale page,
297     #                           treat as cross-site link, show data
298     #
299     #  y   n   POST  n m      intra-site form submission from stale page
300     #                           show "session interrupted"
301     #                           with link to main data page
302     #
303     #  y   n   GET    r       intra-site request from stale page
304     #                           fail
305     #
306     #  y   n   POST   r u     intra-site request from stale page
307     #                           fail
308     #
309     #  -/n y2  GET   nr       intra-site link from cleared session
310     #                           do not revoke y2 as not RESTful
311     #                           treat as   -/n n GET
312     #
313     #  -/n y2  POST  nrmu     request from cleared session
314     #                           revoke y2
315     #                           treat as   -/n n POST
316     #
317     #  -/n n   GET   n        cross-site link but user not logged in
318     #                           show login form with redirect to orig params
319     #
320     #  -/n n   GET    rmu     user not logged in
321     #                           fail
322     #
323     #  -/n n   POST  n m      user not logged in
324     #                           show login form
325     #
326     #  -/n n   POST   r u     user not logged in
327     #                           fail
328
329 sub _check_divert_core ($) {
330 fixme needs wrapping with something to make and commit a transaction
331     my ($r) = @_;
332
333     my $meth = $r->_ch('get_method');
334     my $cookv = $r->_ch('get_cookie');
335     my $parmv = $r->_rp('assoc_param_name');
336
337     my ($cookt,$cooku) = $r->_db_lookup($cookv);
338     my $parmt = $r->_db_lookup($parmv);
339
340     if ($r->_ch('is_logout')) {
341         $r->_must_be_post();
342         die unless $parmt;
343         $r->_db_revoke($cookv);
344         $r->_db_revoke($parmv);
345         return ({ Kind => 'REDIRECT-LOGGEDOUT',
346                   Message => "Logging out...",
347                   Cookie => '',
348                   Params => [ ] });
349     }
350     if ($r->_ch('is_loggedout')) {
351         die unless $meth eq 'GET';
352         die unless $cookt;
353         die unless $parmt;
354         return ({ Kind => 'SMALLPAGE-LOGGEDOUT',
355                   Message => "You have been logged out.",
356                   Cookie => '',
357                   Params => [ ] });
358     }
359     if ($r->_ch('is_login')) {
360         $r->_must_be_post();
361         return ({ Kind => 'LOGIN-STALE',
362                   Message => "Stale session; you need to log in again.",
363                   Cookie => $r->_fresh_cookie(),
364                   Params => [ ] })
365             if $parmt eq 'n';
366         die unless $parmt eq 't' || $parmt eq 'y';
367         return ({ Kind => 'SMALLPAGE-NOCOOKIE',
368                   Message => "You do not seem to have cookies enabled.  ".
369                       "You must enable cookies as we use them for login.",
370                   Cookie => $r->_fresh_cookie(),
371                   Params => $r->_chain_params() })
372             if !$cookt && $parmt eq 't';
373         return ({ Kind => 'LOGIN-BAD',
374                   Message => "Incorrect username/password.",
375                   Cookie => $cookv,
376                   Params => $r->_chain_params() })
377             unless defined $username && length $username;
378         $r->_db_revoke($cookv) 
379             if defined $cookv && !(defined $parmv && $cookv eq $parmv);
380         my $username = $r->_ch('login_ok');
381         $r->_db_record_login_ok($parmv,$username);
382         return ({ Kind => 'REDIRECT-LOGGEDIN',
383                   Message => "Logging in...",
384                   Cookie => $parmv,
385                   Params => $r->_chain_params() });
386     }
387     if ($cookt eq 't') {
388         $cookt = '';
389     }
390     die if $parmt eq 't';
391
392     if ($cookt eq 'y' && $parmt eq 'y' && $cookv ne $parmv) {
393         $r->_db_revoke($parmv) if $meth eq 'POST';
394         $parmt = 'n';
395     }
396
397     if ($cookt ne 'y') {
398         die unless !$cookt || $cookt eq 'n';
399         die unless !$parmt || $parmt eq 'n' || $parmt eq 'y';
400         if ($meth eq 'GET') {
401             return ({ Kind => 'LOGIN-INCOMINGLINK',
402                       Message => "You need to log in again.",
403                       Cookie => $parmv,
404                       Params => $r->_chain_params() });
405         } else {
406             return ((Kind => 'LOGIN-FRESH',
407                      Message => "You need to log in again.",
408                      Cookie => $parmv,
409                      Params => [ ]);
410         }
411     }
412
413     if (!$r->{S}{promise_check_mutate}) {
414         if ($meth ne 'POST') {
415             return ({ Kind => 'MAINPAGEONLY',
416                       Message => 'Entering via cross-site link.',
417                       Cookie => $cookv,
418                       Params => [ ] });
419             # NB caller must then ignore params & path!
420             # if this is too hard they can spit out a small form
421             # with a "click to continue"
422         }
423     }
424
425     die unless $cookt eq 'y';
426     die unless $parmt eq 'y';
427     die unless $cookv eq $parmv;
428     $r->{UserOK} = $cooku;
429     return undef;
430 }
431
432 sub _chain_params ($) {
433     my ($r) = @_;
434     my %elim = { };
435     foreach my $pncn (keys %{ $r->{S} }) {
436         if ($pncn =~ m/_param_name$/) {
437             my $name = $r->{S}{$pncn};
438             die "$pncn ?" if ref $name;
439             $names = [ $name ];
440         } elsif ($pncn =~ m/_param_names$/) {
441             $names = $r->{S}{$pncn};
442         } else {
443             next;
444         }
445         foreach my $param (@$names) {
446             $elim{$name} = 1;
447         }
448     }
449     my @p = $r->_ch('get_param_list');
450     my ($name,$val);
451     my @q = ();
452     while (@p) {
453         ($name,$val,@p) = @p;
454         next if $elim{$name};
455         push @q, $name, $val;
456     }
457     return @q;
458 }
459
460 sub _db_lookup ($$) {
461     # returns ($t,$username)
462     # where $t is one of "t" "y" "n", or "" (for -)
463     my ($r,$v) = @_;
464
465     my $dbh = $r->{Dbh};
466
467     my ($nusername, $nlast) =
468         $dbh->selectrow_array("SELECT username, last".
469                               " FROM $r->{S}{assocdb_table}".
470                               " WHERE associd = ?", {}, $nassoc);
471     return ('') unless defined $nusername;
472
473     my $timeout = $r->{S}{login_timeout};
474     return ('n') unless !defined $timeout || time <= $nlast + $timeout;
475
476     return ('t') unless defined $nusername;
477
478     # hooray
479     return ('y', $nusername);
480 }
481
482 sub _db_revoke ($$) {
483     # revokes $v if it's valid; no-op if it's not
484     my ($r,$v) = @_;
485
486     my $dbh = $r->{Dbh};
487
488     $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
489              " WHERE associd = ?", {}, $v);
490 }
491
492 sub _db_record_login_ok ($$$) {
493     my ($r,$v,$user) = @_;
494     $r->_db_revoke($v);
495     $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
496              " (associd, username, last) VALUES (?,?,?)", {},
497              $v, $user, time);
498 }
499
500 sub url_with_query_params ($@) {
501     my ($r, @params) = @_;
502     my $uri = URI->new($r->_ch('get_url'));
503     $uri->query_form(\@params);
504     return $uri->as_string();
505 }
506
507 sub check_ok ($) {
508     my ($r) = @_;
509
510     my ($divert) = $authreq->check_divert();
511     return 1 if $divert;
512
513     my $handled = $r->_ch('handle_divert')($divert);
514     return 0 if $handled;
515
516     my $kind = $divert->{Kind};
517     my $cookie = $divert->{Cookie};
518     my $params = $divert->{Params};
519
520     if ($kind =~ m/^REDIRECT-/) {
521         # for redirects, we honour stored NextParams and SetCookie,
522         # as we would for non-divert
523         if ($divert_kind eq 'REDIRECT-LOGGEDOUT') {
524             push @$params, $r->{S}{cah_loggedout}[0], 1;
525         } elsif ($divert_kind eq 'REDIRECT-LOGOUT') {
526             push @$params, $r->{S}{cah_logout}[0], 1;
527         } elsif ($divert_kind eq 'REDIRECT-LOGGEDIN') {
528         } else {
529             die;
530         }
531         my $new_url = $r->url_with_query_params(@$params);
532         $r->_ch('do_redirect')($new_url, $cookie);
533         return 0;
534     }
535     $kind =~ m/^SMALLPAGE|^LOGIN/ or die;
536
537     my ($title, @body);
538     if ($kind =~ m/^LOGIN-/) {
539         $title = $r->_gt('Login');
540         push @body, $r->_gt($divert->{Message});
541         push @body, $r->_ch('gen_login_form', $params);
542         $body .= $r->_ch(
543
544         $r->_print(
545                    $r->_ch('start_html')($title),
546                    
547                    
548
549     if ($kind =~ m/^SMALLPAGE
550
551 if (defined $cookie) {
552         $r->_ch('header_out')($cookie);
553     }
554     
555 UP TO HERE
556
557 sub record_login ($$) {
558     my ($r,$nusername) = @_;
559     my $rsp = $r->{S}{random_source};
560     my $rsf = new IO::File $rsp, '<' or die "$rsp $!";
561     my $bytes = ($r->{S}{associdlen} + 7) >> 3;
562     my $nassocbin;
563     $!=0;
564     read($rsf,$nassocbin,$bytes) == $bytes or die "$rsp $!";
565     close $rsf;
566     my $nassoc = unpack "H*", $nassocbin;
567     my $dbh = $r->{Dbh};
568     $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
569              " (associd, username, last) VALUES (?,?,?)", {},
570              $nassoc, $nusername, time);
571     $dbh->do("COMMIT");
572     $r->{U} = $nusername;
573     $r->{A} = $nassoc;
574 }
575
576 sub _check ($) {
577     my ($r) = @_;
578
579     return if exists $r->{Username};
580     ($r->{Username}, $r->{Assoc}, $r->{Mutate}) = $r->_check();
581
582     if (defined $r->{Assoc}) {
583         $dbh->do("UPDATE $r->{S}{assocdb_table}".
584                  " SET last = ?".
585                  " WHERE associd = ?", {}, time, $nassoc);
586         $dbh->do("COMMIT");
587     }
588 }
589
590 sub logout ($) {
591     my ($r) = @_;
592
593     my ($nusername, $nassoc, $nmutate) = $r->_check();
594     return undef unless $nmutate;
595     $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
596              " WHERE associd = ?", {}, $nassoc);
597     $dbh->do("COMMIT");
598     return $nusername;
599 }
600
601 sub check ($) {
602     my ($r) = @_;
603     $r->_check();
604     return !!defined $r->{Username};
605 }
606
607 sub check_mutate ($) {
608     my ($r) = @_;
609     $r->check();
610     return $r->{Mutate};
611 }
612
613 sub username ($) {
614     my ($r) = @_;
615     $r->check();
616     return $r->{Username};
617
618 sub hidden_val ($) {
619     my ($r) = @_;
620     $r->check();
621     return defined $r->{Assoc} ? $r->{Assoc} : '';
622 }
623
624 #---------- simple wrappers ----------
625
626 sub hidden_hargs ($) {
627     my ($r) = @_;
628     return (-name => $r->{S}{param_name},
629             -default => $r->hidden_val());
630 }
631
632 sub hidden_html ($) {
633     my ($r) = @_;
634     return hidden($r->hidden_hargs());
635 }
636
637 sub cookiea_cargs ($) {
638     my ($r) = @_;
639     return (-name => $r->{S}{cookie_name},
640             -value => hidden_val());
641 }
642
643 __END__
644
645 =head1 NAME
646
647 CGI::Auth::Hybrid - web authentication optionally using cookies
648
649 =head1 SYNOPSYS
650
651  my $verifier = CGI::Auth::Hybrid->new_verifier(setting => value,...);
652  my $authreq = $verifier->new_request($cgi_request_object);
653
654  my $authreq = CGI::Auth::Hybrid->new_request($cgi_request_object,
655                                               setting => value,...);
656
657 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
658
659  $authreq->check_ok() or return;
660
661  blah blah blah
662  $authreq->mutating();
663  blah blah blah
664
665 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
666
667  my $divert_kind = $authreq->check_divert();
668  if ($divert_kind) {
669      if ($divert_kind eq 'LOGGEDOUT') {
670          print "goodbye you are now logged out" and quit
671      } elsif ($divert_kind eq 'NOCOOKIES') {
672          print "you need cookies" and quit
673      ... etc.
674      }
675  }
676