chiark / gitweb /
aa9566be42009f0e742c4a8b4b3d3917b04ea6ba
[cgi-auth-flexible.git] / caf.pod
1 # -*- fundamental -*-
2
3 =head1 NAME
4
5 CGI::Auth::Flexible - web authentication optionally using cookies
6
7 =head1 SYNOPSYS
8
9  my $verifier = CGI::Auth::Flexible->new_verifier(setting => value,...);
10  my $authreq = $verifier->new_request($cgi_query_object);
11
12  # simple applications
13  $authreq->check_ok() or return;
14
15  # sophisticated applications
16  my $divert_kind = $authreq->check_divert();
17  if ($divert_kind) { ... print diversion page and quit ... }
18
19  # while handling the request
20  $user = $authreq->get_username();
21  $authreq->check_mutate();
22
23 =head1 DESCRIPTION
24
25 CGI::Auth::Flexible is a library which you can use to add a
26 forms/cookie-based login facility to a Perl web application.
27
28 CGI::Auth::Flexible doesn't interfere with your application's URL path
29 namespace and just needs a few (configurable) form parameter and
30 cookie name(s) for its own use.  It tries to avoid making assumptions
31 about the implementation structure of your application.
32
33 Because CGI::Auth::Flexible is licenced under the AGPLv3, you will
34 probably need to provide a facility to allow users (even ones not
35 logged in) to download the source code for your web app.  Conveniently
36 by default CGI::Auth::Flexible provides (for pure Perl webapps) a
37 mechanism for users to get the source.
38
39 CGI::Auth::Flexible is designed to try to stop you accidentally
40 granting access by misunderstanding the API.  (Also it, of course,
41 guards against cross-site scripting.)  You do need to make sure to
42 call CGI::Auth::Flexible before answering AJAX requests as well as
43 before generating HTML pages, of course, and to call it in every
44 entrypoint to your system.
45
46 =head2 CHECKLIST
47
48 As a minimum you need to do all of the things on this checklist, where
49 applicable.  The items marked SECURITY are the ones that you might
50 forget: without them your application may appear to work, but will be
51 insecure.
52
53 =over
54
55 =item *
56
57 Call C<new_verifier> (once at application startup)
58
59 =item *
60
61 Call C<new_request> (once per request)
62
63 =item *
64
65 B<SECURITY>: Call C<check_ok> or C<check_divert> on every request, and
66 honour the return value.
67
68 =item *
69
70 If you're using C<check_ok>, implement either the
71 C<username_password_error> or C<login_ok> hook and provide it as
72 a setting to C<new_verifier>.
73
74 =item *
75
76 Provide the setting C<dir> (or provide absolute paths for all the
77 other relevant settings).
78
79 =item *
80
81 Call C<get_username> when you need to know who's logged in.
82
83 =item *
84
85 B<SECURITY>: Call C<check_mutate> or C<mutate_ok>, if you specified
86 C<promise_check_mutate>.
87
88 =item *
89
90 B<SECURITY>: Call C<check_nonpage> for every request which is not a page load
91 (if your application has any of those).
92
93 =item *
94
95 When generating URLs and forms (including AJAX requests), include the
96 hidden form parameter using C<secret_hidden_val> or
97 C<secret_hidden_html> when appropriate (see below).
98
99 =item *
100
101 B<SECURITY>: If you do not override the source provision facility (see
102 L</SOURCE CODE DOWNLOAD>), check that the assumptions it makes aren't
103 going to leak security-critical data.
104
105 =back
106
107 These points will now be covered in more detail.
108
109 =head2 INITIALISATION
110
111 Your application should, on startup (eg, when it is loaded by
112 mod_perl) do
113 C<< $verifier = CGI::Auth::Flexible->new_verifier(settings...) >>.
114 This call can be expensive and is best amortised.
115
116 The resulting verifier object can be used to process individual
117 requests, in each case with
118 C<< $authreq = CGI::Auth::Flexible->new_request($cgi_query) >>.
119
120 See L</SETTINGS>.
121
122 =head2 CHECKING AND RESPONSE GENERATION
123
124 If the user is logged in, your application is to handle the request.
125 Otherwise, the user needs to be presented with a login form or error
126 message, as appropriate.  CGI::Auth::Flexible provides two alternative
127 interfaces for this:
128
129 =head3 Simple applications
130
131 The simplist usage is to call C<< $request->check_ok() >> which will
132 check the user's authentication.  If the user is not logged in it will
133 generate a login form (or redirection or other appropriate page) and
134 return false; your application should not then processing that request
135 any further.  If the user is logged in it will return true.
136
137 Various hooks are provided to customise the responses generated by
138 C<check_ok>.
139
140 After C<check_ok> returns true you should go ahead and process the
141 request; you can use C<< $request->get_username >> to find out which
142 user the request came from.
143
144 =head2 Sophisticated applications
145
146 If you want to handle the control flow and to generate login forms,
147 redirections, etc., yourself, you can say
148 C<< $divert = $request->check_divert >>.  This returns undef if
149 the user is logged in, or I<divert spec> if some kind of login
150 page or diversion should be generated.  See L</DIVERT SPEC> below for
151 details of how to deal with the return value.
152
153 =head2 MUTATING OPERATIONS AND EXTERNAL LINKS
154
155 =head3 Mutation-ignorant applications
156
157 By default CGI::Auth::Flexible does not permit external links into
158 your site.  All GET requests give a "click to continue" page which
159 submits a form which loads your app's main page.  In this
160 configuration all your application's forms and AJAX requests should
161 use C<POST>.  This restriction arises from complicated deficiencies
162 in the web's security architecture.
163
164 Such applications are also not able to provide user-specific CSS
165 stylesheets, javascript, favicons, etc.
166
167 =head3 Mutation-aware applications
168
169 The alternative is for your application to always make a special check
170 when the incoming request is going to do some kind of action (such as
171 modifying the user's setup, purchasing goods, or whatever) rather than
172 just retrieve and/or display information.  We term such requests
173 "mutating" requests.
174
175 Then non-mutating pages can be linked to from other, untrustworthy,
176 websites.
177
178 To support external links, and C<GET> requests, pass
179 C<< promise_check_mutate => 1 >> in I<settings>, and then call
180 C<< $authreq->check_mutate() >> before taking any actions.  If the
181 incoming request is not suitable then C<< $authreq->check_mutate() >>
182 will call C<die>.
183
184 There have to be no mutating C<GET> requests in your application (but
185 you shouldn't have any of those anyway); if there are, they won't
186 work.  (CGI::Auth::Flexible will spot them and cause them to fail,
187 rather than allow them to be insecure.)
188
189 =head2 GENERATING URLS, FORMS AND AJAX QUERIES
190
191 When you generate a URL, C<POST> form or AJAX request you may need to
192 include a secret hidden form parameter for the benefit of
193 CGI::Auth::Generic.  This form parameter will be checked by
194 C<check_ok>/C<check_divert> and should be ignored by your application.
195
196 By default the hidden parameter is called C<caf_assochash>.
197
198 After calling C<check_ok> or C<check_divert> the value to put in your
199 form can be obtained from C<secret_hidden_val>; C<secret_hidden_html>
200 will generate the whole HTML C<< <input...> >> element.
201
202 =head3 Mutation-ignorant applications
203
204 For mutation-ignorant applications (see above), all forms etc. should
205 include the hidden parameter (and as discussed, they must all use
206 POST rather than GET).
207
208 =head3 Mutation-aware applications
209
210 For mutation-aware applications, whether to include the secret
211 parameter depends on the kind of request.  CGI::Auth::Flexible knows
212 when it is necessary.  You should find out by calling
213 C<need_add_hidden>.
214
215 If it is inconvenient to call C<need_add_hidden> at runtime, you can
216 rely instead on the following promises:  All POST requests (which
217 includes all mutating requests) need the parameter.  The return value
218 of need_add_hidden depends only on the $method and $reqtype
219 parameters, so you can query it once and remember the answer.
220 HTML page load GETs do not need the parameter.  It is better to
221 err on the side of including the parameter.
222
223 If you really must, you can call C<need_add_hidden> "on the bench"
224 during development and bake the answer into your application code
225 structure.  However, if you do that and a new vulnerability was
226 discovered which is fixed by changing the answer, updating
227 CGI::Auth::Flexible wouldn't be sufficient to fix it.
228
229 =head3 Mutation-aware applications - non-page requests
230
231 If your mutation-aware application supports non-page resources (AJAX
232 and JSON requests, stylesheets, favicons, etc.) it must inform
233 CGI::Auth::Flexible when it is handling such a request, by calling
234 C<check_nonpage>.
235
236 Normally C<check_nonpage> will simply return (and you can ignore the
237 return value).  However, if there is an attack (or, perhaps, a bug) it
238 will die, stopping the attack.
239
240 (You do not need to call C<check_nonpage> for POST requests, but it is
241 harmless to do so.)
242
243 =head3 Mutation-aware applications - novel kinds of request
244
245 If you want to support a kind of request perhaps not yet known about
246 by CGI::Auth::Flexible, you can provide information about that new
247 request kind using C<update_get_need_add_hidden>.
248
249 =head2 DATA STORAGE
250
251 CGI::Auth::Flexible needs to store various information in plain files;
252 it does this in the directory specified by the C<dir> parameter.
253
254 =head1 SOURCE CODE DOWNLOAD
255
256 By default, CGI::Auth::Flexible provides a facility for users to
257 download the source code for the running version of your web
258 application.
259
260 This facility makes a number of important assumptions which you need
261 to check.  Note that if the provided facility is not sufficient
262 because your application is more sophisticated than it copes with (or
263 if you disable the builtin facility), you may need to implement a
264 functioning alternative to avoid violating the AGPLv3 licence.
265
266 Here are the most important (default) assumptions:
267
268 =over
269
270 =item *
271
272 Your app's source code is available by looking at @INC, $0 and
273 S<$ENV{'SCRIPT_FILENAME'}> (the B<source items>).  See
274 C<srcdump_listitems>.  Where these point to files or directories under
275 revision control, the source item is the whole containing vcs tree.
276
277 =item *
278
279 Specifically, there are no compiled or autogenerated Perl
280 files, Javascript resources, etc., which are not contained in one of
281 the source item directories.  (Files which came with your operating
282 system install don't need to be shipped as they fall under the system
283 library exception.)
284
285 =item *
286
287 You have not installed any modified versions of system
288 libraries (including system-supplied Perl modules) in C</usr> outside
289 C</usr/local>.  See C<srcdump_system_dir>.
290
291 =item *
292
293 For each source item in a dvcs, the entire dvcs history does
294 not contain anything confidential (or libellous).  Also, all files which
295 contain secrets are in the dvcs's I<.ignore> file.  See
296 C<srcdump_vcsscript_git> et al.
297
298 =item *
299
300 For each source item NOT in a dvcs, there are no confidential
301 files with the world-readable bit set (being in a world-inaccessible
302 directory is not sufficient).  See C<srcdump_excludes>.
303
304 =item *
305
306 You have none of your app's source code in C</etc>.
307
308 =item *
309
310 You don't regard pathnames on your server as secret.
311
312 =item *
313
314 You don't intentionally load Perl code by virtue of C<.>
315 being in C<@INC> by default.  (See C<srcdump_filter_cwd>.)
316
317 =back
318
319 =head1 MAIN FUNCTIONS AND METHODS
320
321 =over
322
323 =item C<< CGI::Auth::Flexible->new_verifier(setting => value, ...) >>
324
325 Initialises an instance and returns a verifier object.
326 The arguments are setting pairs like a hash initialiser.
327 See L</SETTINGS> below.
328
329 =item C<< $verifier->new_request($cgi_query) >>
330
331 Prepares to process a request.  I<$cgi_query> should normally
332 be the query object from L<CGI(3perl)>.  Most of the default
333 hook methods assume that it is; however if you replace enough of
334 the hook methods then you can pass any value you like and it
335 will be passed to your hooks.
336
337 The return value is the authentication request object (I<$authreq>)
338 which is used to check the incoming request and will contain
339 information about its credentials.
340
341 =item C<< $authreq->check_divert() >>
342
343 Checks whether the user is logged in.  Returns undef if the user is
344 logged in and we should service the request.  Otherwise returns a
345 divert spec (see L</DIVERT SPEC>) saying what should happen instead.
346
347 This method may die if it doesn't like the request, in which case
348 the request needs to be rejected.
349
350 =item C<< $authreq->check_ok() >>
351
352 Checks whether the user is logged in.  Returns true if the user is
353 logged in and we should service the request.
354
355 Otherwise it handles the request itself, generating any appropriate
356 redirect, login form, or continuation page.  It then returns false and
357 the application should not process the request further.
358
359 =item C<< $verifier->disconnect() >>
360
361 Discards the resources (open files, etc.) in the verifier object.
362
363 =back
364
365 =head REQUEST-RELATED FUNCTIONS AND METHODS
366
367 All of these are only valid after C<check_divert> or C<check_ok> has
368 been called.  (In the case of C<check_ok> it won't normally be sensible
369 to call these functions unless C<check_ok> returned true.)
370
371 =item C<< $authreq->get_divert() >>
372
373 Returns the value previously returned by C<check_divert>.
374
375 =item C<< $authreq->get_username() >>
376
377 Returns the name of the logged-in user.  If the user was not logged
378 in (or their session had timed out, or something), returns undef.
379
380 =item C<< $authreq->check_mutate() >>
381
382 Declares to CGI::Auth::Generic that the request being handled will
383 "mutate".  That is, it will modify some server-side state (eg, adding
384 items to shopping baskets, posting messages to blogs, sending emails,
385 or whatever).
386
387 If you have set the setting C<promise_check_mutate> you must call
388 C<check_mutate> whenever appropriate.  If you haven't then it's
389 irrelevant.  See L<MUTATING OPERATIONS AND EXTERNAL LINKS>.
390
391 C<check_mutate> will either return successfully, indicating that all
392 is well and the request should proceed, or it will die.  If it dies
393 that means that the request was improper, which can only result from a
394 bug or an attack.  So an "internal server error" is a suitable
395 response.
396
397 =item C<< $authreq->check_nonpage($method, $reqtype) >>
398
399 Declares to CGI::Auth::Generic that the request is not a page request,
400 but rather a request of type I<$reqtype>.
401
402 If your application has set the setting C<promise_check_mutate>,
403 whenever it is handling anything except an HTML page loads, it must
404 call this function.  See L</REQUEST TYPES>, and
405 L<GENERATING URLS, FORMS AND AJAX QUERIES>.
406
407 C<check_mutate> will either return successfully, indicating that all
408 is well and the request should proceed, or it will die, like
409 C<check_mutate>.
410
411 =head RESPONSE-RELATED FUNCTIONS AND METHODS
412
413 =item C<< $authreq->url_with_query_params($params, [$nonpagetype]) >>
414
415 Convenience function which returns a url for a GET request to this
416 application.
417
418 I<$params> is a hashref specifying the parameters and the PATH_INFO.
419 The keys are the parameter names, and the values are array refs with
420 the parameter value(s) (as strings, as yet unquoted).  (They are array
421 refs because it is possible to pass multiple values for the same
422 parameter in a single request; normally each arrayref would be a
423 singleton.)
424
425 The request path will be the path to the application.  If a parameter
426 with name C<< '' >> is supplied, it is taken as the PATH_INFO - its
427 value will be appended to the application path.  (It should normally
428 start with C<< / >>, and only one value should be supplied.)
429
430 =item C<< something->need_add_hidden($method, $reqtype) >>
431
432 Enquires whether a request of type I<$reqtype> using HTTP method
433 I<$method> needs the hidden form parameter.  See L</REQUEST TYPES>.
434
435 =item C<< something->secret_hidden_val() >>
436
437 Returns the value of the hidden form parameter.  This should be
438 included in all POST requests to your application (and thus be a
439 hidden form parameter in all forms).
440
441 It should also be in some (maybe all) GET requests.  If your
442 application is mutation-ignorant, it should be in all GET requests.
443 If you are mutation-aware, you need to consult C<need_add_hidden>.
444
445 The name of the hidden parameter is the setting C<assoc_param_name>,
446 C<caf_hassochash> by default.  xxx rename param and setting
447
448 =item C<< something->secret_hidden_html() >>
449
450 Returns the HTML for an C<INPUT> element specifying the hidden form
451 parameter.
452
453 =item C<< something->secret_cookie_val() >>
454
455 Returns the value of the secret cookie.  CGI::Auth::Flexible sets this
456 cookie in the forms generated by C<check_ok>.  You may also set it
457 yourself (and indeed you must do so if you use C<check_divert>).
458
459 =item C<< $authreq->chain_params() >>
460
461 Returns a hash of the "relevant" parameters to this request, in a form
462 used by XXX.  This is all of the query parameters which are not
463 related to CGI::Auth::Flexible.  The PATH_INFO from the request is
464 returned as the parameter C<< '' >>.
465
466 xxx why use this function
467
468 =back
469
470 =head OTHER FUNCTIONS AND METHODS
471
472 =over
473
474 =item C<< $verifier_or_authreq->hash($data) >>
475
476 Hashes the supplied data using the hash function specified by the
477 C<hash_algorithm> setting, and converts the result to a string of hex
478 digits.
479
480 =item C<< something->update_get_need_add_hidden($reqtype, $value, [$force]) >>
481
482 Updates CGI::Auth::Generic's knowledge about the various kinds of
483 request, and whether they need the hidden form parameter.  This
484 function applies only to GET requests - POST requests always use the
485 parameter.
486
487 I<$reqtype> is the request type (the value which will be passed to
488 C<check_nonpage> and C<need_add_hidden>.  If you are supporting a new
489 I<$reqtype> you shouuld coordinate with CGI::Auth::Flexible upstrea,
490 or other users, to assign a unique request type name.
491
492 This method may be called on an authreq or a verifier, in which case
493 it will affect all authreqs using the same verifier.  Or it may be
494 called on the class as a whole, in which case it will affect the
495 global default list for all verifiers.
496
497 If I<$force> is supplied and true, this will override
498 CGI::Auth::Flexible's existing knowledge.  Otherwise this new setting
499 will be ignored if CGI::Auth::Flexible already knows about the request
500 type.  (When called on a verifier or authreq, it will ignore the
501 update in favour of existing knowledge recorded both globally in the
502 class or due to previous requests on the same verifier.)
503
504 See L</REQUEST TYPES>.
505
506 =item C<< $verifier_or_authreq->($data) | CGI::Auth::Flexible->>>
507
508 Hashes the supplied data using the hash function specified by the
509 C<hash_algorithm> setting, and converts the result to a string of hex
510 digits.
511
512 =back
513
514 =head1 SETTINGS
515
516 C<new_verifier> and C<new_request> each take a list of settings, as
517 a list of pairs C<< key => value >> (like a Perl hash assignment).
518
519 The settings supplied to C<new_verifier> are stored in the verifier
520 and will apply to all authreqs made from it unless overridden in the
521 call to C<new_request>
522
523 =over
524
525 =head2 GENERAL SETTINGS
526
527 =item C<dir>
528
529 The directory CGI::Auth::Generic should use for its data storage.
530 This is actually just a default absolute path used when the other
531 path settings are relative values.
532
533 Must be an absolute filename.
534
535 =item C<assocdb_dbh>
536
537 CGI::Auth::Flexible needs a database for recording users' login
538 session.  This database needs to be shared across all instances of the
539 web application, so in a multi-node cluster it needs to be your actual
540 database.
541
542 CGI::Auth::Flexible will create the table and index it needs if they
543 don't already exist, and will manage their contents.  You do not need
544 to integrate them into the rest of your webapp's data storage.  (In
545 particular, there is no need for transactional integrity across
546 changes made by CAF and your own application.)
547
548 By default, CAF uses a sqlite3 database stored on local disk in the
549 file named by C<assocdb_path>.  This will be suitable for all
550 applications which run on a single host.
551
552 This value, if supplied, should be a DBI handle for the database.
553
554 =item C<assocdb_dsn>
555
556 This is the DSN to pass to C<< DBI->connect >>.  Used only if
557 C<assocdb_dbh> is not supplied.
558
559 =item C<assocdb_path>
560
561 Path to the sqlite3 database used for CAF's session storage.  The
562 default is currently C<caf-assocs.db> but will change in the future.
563
564 Used only if neither C<assocdb_dbh> or C<assocdb_dsn> are supplied.
565
566 If this is a relative path, it is in C<dir>.
567
568 =item C<assocdb_table>
569
570 Prefix for the SQL tables and indices to use (and to create, if
571 necessary).
572
573 See L</DATABASE TABLES>.
574
575 =item C<keys_path>
576
577 Path to the keys file used by CAF.  This arrangement will change in
578 the future.  See L</BUGS>.
579
580 =item C<random_source>
581
582 Special file to read random numbers from.  Should return
583 cryptographically secure (pseudo)-random bytes, unpredictable to
584 adversaries (even ones on the same machine).
585
586 On Linux, there is no device which is properly suitable.  This is a
587 bug in Linux.  You can use C</dev/random> which can block
588 unnecessarily even though the kernel PRNG has been properly seeded and
589 is fine, or C</dev/urandom> which might return values which attackers
590 can predict if the kernel PRNG has not been properly seeded.
591
592 The default is C</dev/urandom>.
593
594 =item C<secretbits>
595
596 Length of the assoc secret.  Defaults to 128.
597
598 =item C<hash_algorithm>
599
600 Must be a string suitable for use with C<new Digest>.
601 Defaults to C<SHA-256>.
602
603 =item C<login_timeout>
604
605 A user will be logged out this many seconds after they first logged
606 in.  Default: 86400 (one day).
607
608 =item C<login_form_timeout>
609
610 A login form becomes invalid this many seconds after it has been sent.
611 Default: 3600 seconds (one hour).
612
613 =item C<key_rollover>
614
615 The key used for generating assoc secrets is rolled over approximately
616 this often (in seconds).  Default: 86400.
617
618 =item C<assoc_param_name>
619
620 Name of the hidden form parameter.  Default: C<caf_assochash>.
621
622 =item C<dummy_param_name_prefix>
623
624 Some of CAF's HTML-generating functions need to invent form parameter
625 names.  They will all start with this string.  Default: C<caf__>.
626
627 =item C<cookie_name>
628
629 Name of the cookie used for login sessions.  Default:
630 C<caf_assocsecret>.
631
632 =item C<password_param_name>
633
634 Name of the password field in the login form.  Default: C<password>.
635
636 Used by C<login_ok_password> (the default C<login_ok> hook),
637 C<gen_plain_login_form> and the default C<is_login> hook.
638
639 =item C<srcdump_param_name>
640
641 Form parameter name used to indicate that this is a source download
642 request.  If this parameter is supplied, C<check_ok> and
643 C<check_divert> will arrange for the applicaton source code to be
644 delivered as the response (in C<check_ok>'s case by doing it itself
645 and in C<check_divert>'s case by asking your application to do so.
646
647 Default is C<caf_srcdump>.
648
649 =item C<username_param_names>
650
651 Arrayref of name(s) of username form parameters.
652
653 The first entry is used by C<login_ok_password> (the default
654 C<login_ok> hook) to pass to the C<username_password_error> hook and
655 used as the username if all is well.
656
657 All the entries are used by C<gen_plain_login_fork> (the default
658 C<gen_login_form> hook for C<check_ok>) to generate form entry fields.
659
660 The default is C<['username']>.
661
662 =item C<logout_param_names>
663
664 Arrayref of name(s) of form parameters indicating that the request is
665 a logout request.
666
667 Used by the default C<is_logout> hook.
668
669 If you want users to be able to explicitly log out, you need to
670 provide a logout button, something like
671 C<< <input type="submit" name="caf_logout" ...>>
672
673 The default is C<['caf_logout']>
674
675 =back
676
677 =head2 SETTINGS FOR SOURCE CODE DOWNLOAD FACILITY
678
679 =over
680
681 =item C<srcdump_path>
682
683 Path to the directory used for storing pre-prepared source downloads.
684 Defaults to C<caf-srcdump>.
685
686 If this is a relative path, it is in C<dir>.
687
688 =back
689
690 =head2 SETTINGS FOR HTML GENERATION
691
692 =over
693
694 =item C<form_entry_size>
695
696 xxx
697
698 =back
699
700
701
702 =head1 DATABASE TABLES
703
704 In a simple application, you do not need to worry about this.  But if
705 your application runs on multiple frontend hosts with a shared
706 database, you may need to create for yourself the tables and indices
707 used by CGI::Auth::Flexible.
708
709 xxx document _db_setup_do
710 xxx make _db_setup_do explicitly overrideable
711
712
713 xxx divert spec
714 xxx reqtype
715 xxx settings
716 xxx html generators
717 xxx document cookie
718
719 xxx bugs wrong default random on Linux
720 xxx bugs wrong default random on *BSD
721 xxx bugs keys not shared should be in db
722 xxx rename caf-assocs.db
723 xxx rename caf_assocsecret default cookie name
724 xxx mention relationship between login_timeout and cookies