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