blib/lib/Apache/AuthCookieDBI.pm

filter: Statementstmt 81.8% 9 / 11 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 4 / 4 Podpod n/a totaltotal 86.6% 13 / 15 CC 1 SCAR 0.7
CC
1
Cov
82%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
↑ Summary
1 #===============================================================================
2 #
3 # $Id: AuthCookieDBI.pm,v 1.22.2.4 2007/02/03 19:22:24 matisse Exp $
4 #
5 # Apache::AuthCookieDBI
6 #
7 # An AuthCookie module backed by a DBI database.
8 #
9 # Copyright (C) 2000-2003 SF Interactive.
10 #
11 # Author: Jacob Davies <jacob@well.com>
12 #
13 # Incomplete list of additional contributors:
14 # Matisse Enzer
15 # Nick Phillips
16 # William McKee
17 #
18 # This library is free software; you can redistribute it and/or
19 # modify it under the terms of the GNU Lesser General Public
20 # License as published by the Free Software Foundation; either
21 # version 2.1 of the License, or (at your option) any later version.
22 #
23 # This library is distributed in the hope that it will be useful,
24 # but WITHOUT ANY WARRANTY; without even the implied warranty of
25 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
26 # Lesser General Public License for more details.
27 #
28 # You should have received a copy of the GNU Lesser General Public
29 # License along with this library; if not, write to the Free Software
30 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
31 #
32 #===============================================================================
33  
34 package Apache::AuthCookieDBI;
35  
36 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
37 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
38 1 ▶use 5.004_04;
Subroutine BEGIN: called CC=1 SCAR=0.0
39  
40 our $VERSION = 2.10;
41  
42 0 ▶use Apache;
Subroutine BEGIN: called CC=1 SCAR=2.6
43 use Apache::AuthCookie;
44 use Apache::DBI;
45 use Apache::Constants;
46 use Apache::File;
47 use Digest::MD5 qw( md5_hex );
48 use Date::Calc qw( Today_and_Now Add_Delta_DHMS );
49  
50 # Also uses Crypt::CBC if you're using encrypted cookies.
51 use base qw( Apache::AuthCookie );
52  
53 my $EMPTY_STRING = q{};
54  
55 #===============================================================================
56 # F U N C T I O N D E C L A R A T I O N S
57 #===============================================================================
58  
59  
60 #===============================================================================
61 # P A C K A G E G L O B A L S
62 #===============================================================================
63  
64 use vars qw( %CIPHERS );
65  
66 # Stores Cipher::CBC objects in $CIPHERS{ idea:AuthName },
67 # $CIPHERS{ des:AuthName } etc.
68  
69 use vars qw( %SECRET_KEYS );
70  
71 # Stores secret keys for MD5 checksums and encryption for each auth realm in
72 # $SECRET_KEYS{ AuthName }.
73  
74 #===============================================================================
75 # S E R V E R S T A R T I N I T I A L I Z A T I O N
76 #===============================================================================
77  
78 BEGIN {
79 my @keyfile_vars =
80 grep { $_ =~ /DBI_SecretKeyFile$/ }
81 keys %{ Apache->server->dir_config() };
82 foreach my $keyfile_var (@keyfile_vars) {
83 my $keyfile = Apache->server->dir_config($keyfile_var);
84 my $auth_name = $keyfile_var;
85 $auth_name =~ s/DBI_SecretKeyFile$//;
86 my $key_fh;
87 open( $key_fh, '<', $keyfile );
88 if ( -r $key_fh ) {
89 $SECRET_KEYS{$auth_name} = <$key_fh>;
90 close $key_fh;
91 }
92 else {
93 Apache::log_error(
94 "Could not open keyfile '$keyfile' for $auth_name in file $keyfile"
95 );
96 }
97 }
98 }
99  
100 #===============================================================================
101 # P E R L D O C
102 #===============================================================================
103  
104 =head1 NAME
105  
106 Apache::AuthCookieDBI - An AuthCookie module backed by a DBI database.
107  
108 =head1 VERSION
109  
110 $Revision: 1.22.2.4 $
111  
112 =head1 SYNOPSIS
113  
114 # In httpd.conf or .htaccess
115
116 # This PerlSetVar MUST precede the PerlModule line because the
117 # key is read in a BEGIN block when the module is loaded.
118 PerlSetVar WhatEverDBI_SecretKeyFile /etc/httpd/acme.com.key
119  
120 PerlModule Apache::AuthCookieDBI
121 PerlSetVar WhatEverPath /
122 PerlSetVar WhatEverLoginScript /login.pl
123  
124 # Optional, to share tickets between servers.
125 PerlSetVar WhatEverDomain .domain.com
126
127 # These must be set
128 PerlSetVar WhatEverDBI_DSN "DBI:mysql:database=test"
129 PerlSetVar WhatEverDBI_SecretKey "489e5eaad8b3208f9ad8792ef4afca73598ae666b0206a9c92ac877e73ce835c"
130  
131 # These are optional, the module sets sensible defaults.
132 PerlSetVar WhatEverDBI_User "nobody"
133 PerlSetVar WhatEverDBI_Password "password"
134 PerlSetVar WhatEverDBI_UsersTable "users"
135 PerlSetVar WhatEverDBI_UserField "user"
136 PerlSetVar WhatEverDBI_PasswordField "password"
137 PerlSetVar WhatEverDBI_CryptType "none"
138 PerlSetVar WhatEverDBI_GroupsTable "groups"
139 PerlSetVar WhatEverDBI_GroupField "grp"
140 PerlSetVar WhatEverDBI_GroupUserField "user"
141 PerlSetVar WhatEverDBI_EncryptionType "none"
142 PerlSetVar WhatEverDBI_SessionLifetime 00-24-00-00
143  
144 # Protected by AuthCookieDBI.
145 <Directory /www/domain.com/authcookiedbi>
146 AuthType Apache::AuthCookieDBI
147 AuthName WhatEver
148 PerlAuthenHandler Apache::AuthCookieDBI->authenticate
149 PerlAuthzHandler Apache::AuthCookieDBI->authorize
150 require valid-user
151 # or you can require users:
152 require user jacob
153 # You can optionally require groups.
154 require group system
155 </Directory>
156  
157 # Login location.
158 <Files LOGIN>
159 AuthType Apache::AuthCookieDBI
160 AuthName WhatEver
161 SetHandler perl-script
162 PerlHandler Apache::AuthCookieDBI->login
163 </Files>
164  
165 =head1 DESCRIPTION
166  
167 This module is an authentication handler that uses the basic mechanism provided
168 by Apache::AuthCookie with a DBI database for ticket-based protection. It
169 is based on two tokens being provided, a username and password, which can
170 be any strings (there are no illegal characters for either). The username is
171 used to set the remote user as if Basic Authentication was used.
172  
173 On an attempt to access a protected location without a valid cookie being
174 provided, the module prints an HTML login form (produced by a CGI or any
175 other handler; this can be a static file if you want to always send people
176 to the same entry page when they log in). This login form has fields for
177 username and password. On submitting it, the username and password are looked
178 up in the DBI database. The supplied password is checked against the password
179 in the database; the password in the database can be plaintext, or a crypt()
180 or md5_hex() checksum of the password. If this succeeds, the user is issued
181 a ticket. This ticket contains the username, an issue time, an expire time,
182 and an MD5 checksum of those and a secret key for the server. It can
183 optionally be encrypted before returning it to the client in the cookie;
184 encryption is only useful for preventing the client from seeing the expire
185 time. If you wish to protect passwords in transport, use an SSL-encrypted
186 connection. The ticket is given in a cookie that the browser stores.
187  
188 After a login the user is redirected to the location they originally wished
189 to view (or to a fixed page if the login "script" was really a static file).
190  
191 On this access and any subsequent attempt to access a protected document, the
192 browser returns the ticket to the server. The server unencrypts it if
193 encrypted tickets are enabled, then extracts the username, issue time, expire
194 time and checksum. A new checksum is calculated of the username, issue time,
195 expire time and the secret key again; if it agrees with the checksum that
196 the client supplied, we know that the data has not been tampered with. We
197 next check that the expire time has not passed. If not, the ticket is still
198 good, so we set the username.
199  
200 Authorization checks then check that any "require valid-user" or "require
201 user jacob" settings are passed. Finally, if a "require group foo" directive
202 was given, the module will look up the username in a groups database and
203 check that the user is a member of one of the groups listed. If all these
204 checks pass, the document requested is displayed.
205  
206 If a ticket has expired or is otherwise invalid it is cleared in the browser
207 and the login form is shown again.
208  
209 =cut
210  
211 #===============================================================================
212 # P R I V A T E F U N C T I O N S
213 #===============================================================================
214  
215 #-------------------------------------------------------------------------------
216 # _log_not_set -- Log that a particular authentication variable was not set.
217  
218 sub _log_not_set {
219 my ( $r, $variable ) = @_;
220 my $auth_name = $r->auth_name;
221 return $r->log_error(
222 "Apache::AuthCookieDBI: $variable not set for auth realm
223 $auth_name", $r->uri
224 );
225 }
226  
227 #-------------------------------------------------------------------------------
228 # _dir_config_var -- Get a particular authentication variable.
229  
230 sub _dir_config_var {
231 my ( $r, $variable ) = @_;
232 my $auth_name = $r->auth_name;
233 return $r->dir_config("$auth_name$variable");
234 }
235  
236 #-------------------------------------------------------------------------------
237 # _dbi_config_vars -- Gets the config variables from the dir_config and logs
238 # errors if required fields were not set, returns undef if any of the fields
239 # had errors or a hash of the values if they were all OK. Takes a request
240 # object.
241  
242 sub _dbi_config_vars {
243 my ($r) = @_;
244  
245 my %c; # config variables hash
246  
247 =head1 APACHE CONFIGURATION DIRECTIVES
248  
249 All configuration directives for this module are passed in PerlSetVars. These
250 PerlSetVars must begin with the AuthName that you are describing, so if your
251 AuthName is PrivateBankingSystem they will look like:
252  
253 PerlSetVar PrivateBankingSystemDBI_DSN "DBI:mysql:database=banking"
254  
255 See also L<Apache::Authcookie> for the directives required for any kind
256 of Apache::AuthCookie-based authentication system.
257  
258 In the following descriptions, replace "WhatEver" with your particular
259 AuthName. The available configuration directives are as follows:
260  
261 =over 4
262  
263 =item C<WhatEverDBI_DSN>
264  
265 Specifies the DSN for DBI for the database you wish to connect to retrieve
266 user information. This is required and has no default value.
267  
268 =cut
269  
270 unless ( $c{DBI_DSN} = _dir_config_var $r, 'DBI_DSN' ) {
271 _log_not_set $r, 'DBI_DSN';
272 return;
273 }
274  
275 =item C<WhateverDBI_SecretKey>
276  
277 Specifies the secret key for this auth scheme. This should be a long
278 random string. This should be secret; either make the httpd.conf file
279 only readable by root, or put the PerlSetVar in a file only readable by
280 root and include it.
281  
282 This is required and has no default value
283 =cut
284  
285 unless ( $c{DBI_SecretKey} = _dir_config_var $r, 'DBI_SecretKey'
286 or _dir_config_var $r, 'DBI_SecretKeyFile' )
287 {
288 _log_not_set $r, 'DBI_SecretKey or DBI_SecretKeyFile';
289 return;
290 }
291  
292 =item C<WhatEverDBI_User>
293  
294 The user to log into the database as. This is not required and
295 defaults to undef.
296  
297 =cut
298  
299 $c{DBI_user} = _dir_config_var( $r, 'DBI_User' )
300 || undef;
301  
302 =item C<WhatEverDBI_Password>
303  
304 The password to use to access the database. This is not required
305 and defaults to undef.
306  
307 =cut
308  
309 $c{DBI_password} = _dir_config_var( $r, 'DBI_Password' )
310 || undef;
311  
312 =item C<WhatEverDBI_UsersTable>
313  
314 The table that user names and passwords are stored in. This is not
315 required and defaults to 'users'.
316  
317 =cut
318  
319 $c{DBI_userstable} = _dir_config_var( $r, 'DBI_UsersTable' )
320 || 'users';
321  
322 =item C<WhatEverDBI_UserField>
323  
324 The field in the above table that has the user name. This is not
325 required and defaults to 'user'.
326  
327 =cut
328  
329 $c{DBI_userfield} = _dir_config_var( $r, 'DBI_UserField' )
330 || 'user';
331  
332 =item C<WhatEverDBI_PasswordField>
333  
334 The field in the above table that has the password. This is not
335 required and defaults to 'password'.
336  
337 =cut
338  
339 $c{DBI_passwordfield} = _dir_config_var( $r, 'DBI_PasswordField' )
340 || 'password';
341  
342 =item C<WhatEverDBI_CryptType>
343  
344 What kind of hashing is used on the password field in the database. This can
345 be 'none', 'crypt', or 'md5'. This is not required and defaults to 'none'.
346  
347 =cut
348  
349 $c{DBI_crypttype} = _dir_config_var( $r, 'DBI_CryptType' )
350 || 'none';
351  
352 =item C<WhatEverDBI_GroupsTable>
353  
354 The table that has the user / group information. This is not required and
355 defaults to 'groups'.
356  
357 =cut
358  
359 $c{DBI_groupstable} = _dir_config_var( $r, 'DBI_GroupsTable' )
360 || 'groups';
361  
362 =item C<WhatEverDBI_GroupField>
363  
364 The field in the above table that has the group name. This is not required
365 and defaults to 'grp' (to prevent conflicts with the SQL reserved word 'group').
366  
367 =cut
368  
369 $c{DBI_groupfield} = _dir_config_var( $r, 'DBI_GroupField' )
370 || 'grp';
371  
372 =item C<WhatEverDBI_GroupUserField>
373  
374 The field in the above table that has the user name. This is not required
375 and defaults to 'user'.
376  
377 =cut
378  
379 $c{DBI_groupuserfield} = _dir_config_var( $r, 'DBI_GroupUserField' )
380 || 'user';
381  
382 =item C<WhatEverDBI_SecretKeyFile - DEPRECATED>
383  
384 The file that contains the secret key (on the first line of the file). This
385 is required and has no default value. This key should be owned and only
386 readable by root. It is read at server startup time. The key should be long
387 and fairly random. If you want, you can change it and restart the server,
388 (maybe daily), which will invalidate all prior-issued tickets.
389  
390 This directive MUST be set before the PerlModule line that loads this module,
391 because the secret key file is read immediately (at server start time). This
392 is so you can have it owned and only readable by root even though Apache
393 then changes to another user.
394  
395 I suggest using DBI_SecretKey instead.
396  
397 =cut
398  
399 unless ( $c{DBI_secretkeyfile} = _dir_config_var $r, 'DBI_SecretKeyFile'
400 or _dir_config_var $r, 'DBI_SecretKey' )
401 {
402 _log_not_set $r, 'DBI_SecretKeyFile or DBI_SecretKey';
403 return;
404 }
405  
406 =item C<WhatEverDBI_EncryptionType>
407  
408 What kind of encryption to use to prevent the user from looking at the fields
409 in the ticket we give them. This is almost completely useless, so don't
410 switch it on unless you really know you need it. It does not provide any
411 protection of the password in transport; use SSL for that. It can be 'none',
412 'des', 'idea', 'blowfish', or 'blowfish_pp'.
413  
414 This is not required and defaults to 'none'.
415  
416 =cut
417  
418 $c{DBI_encryptiontype} = _dir_config_var( $r, 'DBI_EncryptionType' )
419 || 'none';
420  
421 # If we used encryption we need to pull in Crypt::CBC.
422 if ( $c{DBI_encryptiontype} ne 'none' ) {
423 require Crypt::CBC;
424 }
425  
426 =item C<WhatEverDBI_SessionLifetime>
427  
428 How long tickets are good for after being issued. Note that presently
429 Apache::AuthCookie does not set a client-side expire time, which means that
430 most clients will only keep the cookie until the user quits the browser.
431 However, if you wish to force people to log in again sooner than that, set
432 this value. This can be 'forever' or a life time specified as:
433  
434 DD-hh-mm-ss -- Days, hours, minute and seconds to live.
435  
436 This is not required and defaults to '00-24-00-00' or 24 hours.
437  
438 =cut
439  
440 $c{DBI_sessionlifetime} = _dir_config_var( $r, 'DBI_SessionLifetime' )
441 || '00-24-00-00';
442  
443 return %c;
444 }
445  
446 #-------------------------------------------------------------------------------
447 # _now_year_month_day_hour_minute_second -- Return a string with the time in
448 # this order separated by dashes.
449  
450 sub _now_year_month_day_hour_minute_second {
451 return sprintf '%04d-%02d-%02d-%02d-%02d-%02d', Today_and_Now;
452 }
453  
454 #-------------------------------------------------------------------------------
455 # _percent_encode -- Percent-encode (like URI encoding) any non-alphanumberics
456 # in the supplied string.
457  
458 sub _percent_encode {
459 my ($str) = @_;
460 $str =~ s/([^\w])/ uc sprintf '%%%02x', ord $1 /eg;
461 return $str;
462 }
463  
464 #-------------------------------------------------------------------------------
465 # _percent_decode -- Percent-decode (like URI decoding) any %XX sequences in
466 # the supplied string.
467  
468 sub _percent_decode {
469 my ($str) = @_;
470 $str =~ s/%([0-9a-fA-F]{2})/ pack( "c",hex( $1 ) ) /ge;
471 return $str;
472 }
473  
474 #===============================================================================
475 # P U B L I C F U N C T I O N S
476 #===============================================================================
477  
478 =head1 SUBCLASSING
479  
480 You can subclass this module to override public functions and change
481 their behaviour.
482  
483 =over 4
484  
485 =item C<extra_session_info()>
486  
487 This method returns extra fields to add to the session key.
488 It should return a string consisting of ":field1:field2:field3"
489 (where each field is preceded by a colon).
490  
491 The default implementation returns false.
492  
493 =back
494  
495 =cut
496  
497 sub extra_session_info {
498 my ( $self, $r, @credentials ) = @_;
499  
500 return;
501 }
502  
503 #-------------------------------------------------------------------------------
504 # Take the credentials for a user and check that they match; if so, return
505 # a new session key for this user that can be stored in the cookie.
506 # If there is a problem, return a bogus session key.
507  
508 sub authen_cred {
509 my ( $self, $r, @credentials ) = @_;
510 my ( $user, $password, @extra_credentials ) = @credentials;
511 my $auth_name = $r->auth_name;
512 ( $user, $password ) = _defined_or_empty( $user, $password );
513  
514 if ( !length $user ) {
515 $r->log_reason(
516 "Apache::AuthCookieDBI: no username supplied for auth realm $auth_name",
517 $r->uri
518 );
519 return;
520 }
521  
522 if ( !length $password ) {
523 $r->log_reason(
524 "Apache::AuthCookieDBI: no password supplied for auth realm $auth_name",
525 $r->uri
526 );
527 return;
528 }
529  
530 # get the configuration information.
531 my %c = _dbi_config_vars $r;
532  
533 # get the crypted password from the users database for this user.
534 my $dbh = DBI->connect( $c{DBI_DSN}, $c{DBI_user}, $c{DBI_password} );
535 unless ( defined $dbh ) {
536 $r->log_reason(
537 "Apache::AuthCookieDBI: couldn't connect to $c{ DBI_DSN } for auth realm $auth_name",
538 $r->uri
539 );
540 return;
541 }
542 my $sth = $dbh->prepare( <<"EOS" );
543 SELECT $c{ DBI_passwordfield }
544 FROM $c{ DBI_userstable }
545 WHERE $c{ DBI_userfield } = ?
546 EOS
547 $sth->execute($user);
548 my ($crypted_password) = $sth->fetchrow_array;
549 unless ( defined $crypted_password ) {
550 $r->log_reason(
551 "Apache::AuthCookieDBI: couldn't select password from $c{ DBI_DSN }, $c{ DBI_userstable }, $c{ DBI_userfield } for user $user for auth realm $auth_name",
552 $r->uri
553 );
554 return;
555 }
556  
557 # now return unless the passwords match.
558 if ( lc $c{DBI_crypttype} eq 'none' ) {
559 unless ( $password eq $crypted_password ) {
560 $r->log_reason(
561 "Apache::AuthCookieDBI: plaintext passwords didn't match for user $user for auth realm $auth_name",
562 $r->uri
563 );
564 return;
565 }
566 }
567 elsif ( lc $c{DBI_crypttype} eq 'crypt' ) {
568 my $salt = substr $crypted_password, 0, 2;
569 unless ( crypt( $password, $salt ) eq $crypted_password ) {
570 $r->log_reason(
571 "Apache::AuthCookieDBI: crypted passwords didn't match for user $user for auth realm $auth_name",
572 $r->uri
573 );
574 return;
575 }
576 }
577 elsif ( lc $c{DBI_crypttype} eq 'md5' ) {
578 unless ( md5_hex($password) eq $crypted_password ) {
579 $r->log_reason(
580 "Apache::AuthCookieDBI: MD5 passwords didn't match for user $user for auth realm $auth_name",
581 $r->uri
582 );
583 return;
584 }
585 }
586  
587 # Create the expire time for the ticket.
588 my $expire_time;
589  
590 # expire time in a zillion years if it's forever.
591 if ( lc $c{DBI_sessionlifetime} eq 'forever' ) {
592 $expire_time = '9999-01-01-01-01-01';
593 }
594 else {
595 my ( $deltaday, $deltahour, $deltaminute, $deltasecond ) =
596 split /-/, $c{DBI_sessionlifetime};
597  
598 # Figure out the expire time.
599 $expire_time = sprintf(
600 '%04d-%02d-%02d-%02d-%02d-%02d',
601 Add_Delta_DHMS( Today_and_Now, $deltaday, $deltahour,
602 $deltaminute, $deltasecond
603 )
604 );
605 }
606  
607 # Now we need to %-encode non-alphanumberics in the username so we
608 # can stick it in the cookie safely.
609 my $enc_user = _percent_encode $user;
610  
611 # OK, now we stick the username and the current time and the expire
612 # time together to make the public part of the session key:
613 my $current_time = _now_year_month_day_hour_minute_second;
614 my $public_part = "$enc_user:$current_time:$expire_time";
615 $public_part .= $self->extra_session_info( $r, @credentials );
616  
617 # Now we calculate the hash of this and the secret key and then
618 # calculate the hash of *that* and the secret key again.
619 my $secret_key = $SECRET_KEYS{$auth_name};
620 unless ( defined $secret_key ) {
621 $r->log_reason(
622 "Apache::AuthCookieDBI: didn't have the secret key for auth realm $auth_name",
623 $r->uri
624 );
625 return;
626 }
627 my $hash =
628 md5_hex( join ':', $secret_key,
629 md5_hex( join ':', $public_part, $secret_key ) );
630  
631 # Now we add this hash to the end of the public part.
632 my $session_key = "$public_part:$hash";
633  
634 # Now we encrypt this and return it.
635 my $encrypted_session_key;
636 if ( $c{DBI_encryptiontype} eq 'none' ) {
637 $encrypted_session_key = $session_key;
638 }
639 elsif ( lc $c{DBI_encryptiontype} eq 'des' ) {
640 $CIPHERS{"des:$auth_name"} ||= Crypt::CBC->new( $secret_key, 'DES' );
641 $encrypted_session_key =
642 $CIPHERS{"des:$auth_name"}->encrypt_hex($session_key);
643 }
644 elsif ( lc $c{DBI_encryptiontype} eq 'idea' ) {
645 $CIPHERS{"idea:$auth_name"} ||= Crypt::CBC->new( $secret_key, 'IDEA' );
646 $encrypted_session_key =
647 $CIPHERS{"idea:$auth_name"}->encrypt_hex($session_key);
648 }
649 elsif ( lc $c{DBI_encryptiontype} eq 'blowfish' ) {
650 $CIPHERS{"blowfish:$auth_name"} ||=
651 Crypt::CBC->new( $secret_key, 'Blowfish' );
652 $encrypted_session_key =
653 $CIPHERS{"blowfish:$auth_name"}->encrypt_hex($session_key);
654 }
655  
656 return $encrypted_session_key;
657 }
658  
659 #-------------------------------------------------------------------------------
660 # Take a session key and check that it is still valid; if so, return the user.
661  
662 sub authen_ses_key {
663 my ( $self, $r, $encrypted_session_key ) = @_;
664  
665 my $auth_name = $r->auth_name;
666  
667 # Get the configuration information.
668 my %c = _dbi_config_vars $r;
669  
670 # Get the secret key.
671 my $secret_key = $SECRET_KEYS{$auth_name};
672 unless ( defined $secret_key ) {
673 $r->log_reason(
674 "Apache::AuthCookieDBI: didn't have the secret key from for auth realm $auth_name",
675 $r->uri
676 );
677 return;
678 }
679  
680 # Decrypt the session key.
681 my $session_key;
682 if ( $c{DBI_encryptiontype} eq 'none' ) {
683 $session_key = $encrypted_session_key;
684 }
685 else {
686  
687 # Check that this looks like an encrypted hex-encoded string.
688 unless ( $encrypted_session_key =~ /^[0-9a-fA-F]+$/ ) {
689 $r->log_reason(
690 "Apache::AuthCookieDBI: encrypted session key $encrypted_session_key doesn't look like it's properly hex-encoded for auth realm $auth_name",
691 $r->uri
692 );
693 return;
694 }
695  
696 # Get the cipher from the cache, or create a new one if the
697 # cached cipher hasn't been created, & decrypt the session key.
698 my $cipher;
699 if ( lc $c{DBI_encryptiontype} eq 'des' ) {
700 $cipher = $CIPHERS{"des:$auth_name"} ||=
701 Crypt::CBC->new( $secret_key, 'DES' );
702 }
703 elsif ( lc $c{DBI_encryptiontype} eq 'idea' ) {
704 $cipher = $CIPHERS{"idea:$auth_name"} ||=
705 Crypt::CBC->new( $secret_key, 'IDEA' );
706 }
707 elsif ( lc $c{DBI_encryptiontype} eq 'blowfish' ) {
708 $cipher = $CIPHERS{"blowfish:$auth_name"} ||=
709 Crypt::CBC->new( $secret_key, 'Blowfish' );
710 }
711 elsif ( lc $c{DBI_encryptiontype} eq 'blowfish_pp' ) {
712 $cipher = $CIPHERS{"blowfish_pp:$auth_name"} ||=
713 Crypt::CBC->new( $secret_key, 'Blowfish_PP' );
714 }
715 else {
716 $r->log_reason(
717 "Apache::AuthCookieDBI: unknown encryption type $c{ DBI_encryptiontype } for auth realm $auth_name",
718 $r->uri
719 );
720 return;
721 }
722 $session_key = $cipher->decrypt_hex($encrypted_session_key);
723 }
724  
725 # Break up the session key.
726 my ( $enc_user, $issue_time, $expire_time, @rest ) =
727 ( split /:/, $session_key );
728 my $supplied_hash = pop @rest;
729 ( $enc_user, $issue_time, $expire_time, $supplied_hash ) =
730 _defined_or_empty( $enc_user, $issue_time, $expire_time, $supplied_hash );
731  
732 # Let's check that we got passed sensible values in the cookie.
733 unless ( $enc_user =~ /^[a-zA-Z0-9_\%]+$/ ) {
734 $r->log_reason(
735 "Apache::AuthCookieDBI: bad percent-encoded user $enc_user recovered from session ticket for auth_realm $auth_name",
736 $r->uri
737 );
738 return;
739 }
740  
741 # decode the user
742 my $user = _percent_decode($enc_user);
743 unless ( $issue_time =~ /^\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}$/ ) {
744 $r->log_reason(
745 "Apache::AuthCookieDBI: bad issue time $issue_time recovered from ticket for user $user for auth_realm $auth_name",
746 $r->uri
747 );
748 return;
749 }
750 unless ( $expire_time =~ /^\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}$/ ) {
751 $r->log_reason(
752 "Apache::AuthCookieDBI: bad expire time $expire_time recovered from ticket for user $user for auth_realm $auth_name",
753 $r->uri
754 );
755 return;
756 }
757 unless ( $supplied_hash =~ /^[0-9a-fA-F]{32}$/ ) {
758 $r->log_reason(
759 "Apache::AuthCookieDBI: bad hash $supplied_hash recovered from ticket for user $user for auth_realm $auth_name",
760 $r->uri
761 );
762 return;
763 }
764  
765 # Calculate the hash of the user, issue time, expire_time and
766 # the secret key and then the hash of that and the secret key again.
767 my $hash = md5_hex(
768 join ':',
769 $secret_key,
770 md5_hex(
771 join ':', $enc_user, $issue_time,
772 $expire_time, @rest, $secret_key
773 )
774 );
775  
776 # Compare it to the hash they gave us.
777 unless ( $hash eq $supplied_hash ) {
778 $r->log_reason(
779 "Apache::AuthCookieDBI: hash in cookie did not match calculated hash of contents for user $user for auth realm $auth_name",
780 $r->uri
781 );
782 return;
783 }
784  
785 # Check that their session hasn't timed out.
786 if ( _now_year_month_day_hour_minute_second gt $expire_time ) {
787 $r->log_reason(
788 "Apache:AuthCookieDBI: expire time $expire_time has passed for user $user for auth realm $auth_name",
789 $r->uri
790 );
791 return;
792 }
793  
794 # If we're being paranoid about timing-out long-lived sessions,
795 # check that the issue time + the current (server-set) session lifetime
796 # hasn't passed too (in case we issued long-lived session tickets
797 # in the past that we want to get rid of). *** TODO ***
798 # if ( lc $c{ DBI_AlwaysUseCurrentSessionLifetime } eq 'on' ) {
799  
800 # They must be okay, so return the user.
801 return $user;
802 }
803  
804 #-------------------------------------------------------------------------------
805 # Take a list of groups and make sure that the current remote user is a member
806 # of one of them.
807  
808 sub group {
809 my ( $self, $r, @groups ) = @_;
810  
811 my $auth_name = $r->auth_name;
812  
813 # Get the configuration information.
814 my %c = _dbi_config_vars $r;
815  
816 my $user = $r->connection->user;
817  
818 # See if we have a row in the groups table for this user/group.
819 my $dbh = DBI->connect( $c{DBI_DSN}, $c{DBI_user}, $c{DBI_password} );
820 unless ( defined $dbh ) {
821 $r->log_reason(
822 "Apache::AuthCookieDBI: couldn't connect to $c{ DBI_DSN } for auth realm $auth_name",
823 $r->uri
824 );
825 return;
826 }
827  
828 # Now loop through all the groups to see if we're a member of any:
829 my $sth = $dbh->prepare( <<"EOS" );
830 SELECT $c{ DBI_groupuserfield }
831 FROM $c{ DBI_groupstable }
832 WHERE $c{ DBI_groupfield } = ?
833 AND $c{ DBI_groupuserfield } = ?
834 EOS
835 foreach my $group (@groups) {
836 $sth->execute( $group, $user );
837 return OK if ( $sth->fetchrow_array );
838 }
839 $r->log_reason(
840 "Apache::AuthCookieDBI: user $user was not a member of any of the required groups @groups for auth realm $auth_name",
841 $r->uri
842 );
843 return FORBIDDEN;
844 }
845  
846 # Takes a list and returns a list of the same size.
847 # Any element in the inputs that is defined is returned unchanged. Elements that
848 # were undef are returned as empty strings.
849 sub _defined_or_empty {
850 my @args = @_;
851 my @all_defined = ();
852 for ( my $i = 0 ; $i < scalar @args ; $i++ ) {
853 my $arg = $args[$i];
854 if ( defined $arg ) {
855 push @all_defined, $arg;
856 }
857 else {
858 push @all_defined, $EMPTY_STRING;
859 }
860 }
861 return @all_defined;
862 }
863  
864 1;
865 __END__
↑ Summary