blib/lib/Apache/AuthzLDAP.pm untested

filter: Statementstmt 0.0% 0 / 162 Branchbran 0.0% 0 / 64 Conditioncond 0.0% 0 / 40 MC/DCmcdc 0.0% 0 / 21 Subroutinesub 0.0% 0 / 9 Podpod 0.0% 0 / 2 totaltotal 0.0% 0 / 298 CC 33 SCAR 55.5
CC
33
Cov
0%
check_group
342.0
handler
272.0
BEGIN
2.0
CRAP 256.6
1 # $Id: AuthzLDAP.pm,v 1.26 2005/05/09 16:36:06 cgilmore Exp $
2 #
3 # Author : Jason Bodnar, Christian Gilmore
4 # Created On : Apr 04 12:04:00 CDT 2000
5 # Status : Functional
6 #
7 # PURPOSE
8 # LDAP Group Authentication
9 #
10 ###############################################################################
11 #
12 # IBM Public License Version 1.0
13 #
14 # THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS IBM
15 # PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR
16 # DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF
17 # THIS AGREEMENT.
18 #
19 # 1. DEFINITIONS
20 #
21 # "Contribution" means:
22 #
23 # a) in the case of International Business Machines Corporation
24 # ("IBM"), the Original Program, and
25 #
26 # b) in the case of each Contributor,
27 #
28 # i) changes to the Program, and
29 #
30 # ii) additions to the Program;
31 #
32 # where such changes and/or additions to the Program originate from
33 # and are distributed by that particular Contributor. A Contribution
34 # 'originates' from a Contributor if it was added to the Program by
35 # such Contributor itself or anyone acting on such Contributor's
36 # behalf. Contributions do not include additions to the Program
37 # which: (i) are separate modules of software distributed in
38 # conjunction with the Program under their own license agreement,
39 # and (ii) are not derivative works of the Program.
40 #
41 # "Contributor" means IBM and any other entity that distributes the
42 # Program.
43 #
44 # "Licensed Patents " mean patent claims licensable by a Contributor
45 # which are necessarily infringed by the use or sale of its
46 # Contribution alone or when combined with the Program.
47 #
48 # "Original Program" means the original version of the software
49 # accompanying this Agreement as released by IBM, including source
50 # code, object code and documentation, if any.
51 #
52 # "Program" means the Original Program and Contributions.
53 #
54 # "Recipient" means anyone who receives the Program under this
55 # Agreement, including all Contributors.
56 #
57 # 2. GRANT OF RIGHTS
58 #
59 # a) Subject to the terms of this Agreement, each Contributor hereby
60 # grants Recipient a non-exclusive, worldwide, royalty-free
61 # copyright license to reproduce, prepare derivative works of,
62 # publicly display, publicly perform, distribute and sublicense the
63 # Contribution of such Contributor, if any, and such derivative
64 # works, in source code and object code form.
65 #
66 # b) Subject to the terms of this Agreement, each Contributor hereby
67 # grants Recipient a non-exclusive, worldwide, royalty-free patent
68 # license under Licensed Patents to make, use, sell, offer to sell,
69 # import and otherwise transfer the Contribution of such
70 # Contributor, if any, in source code and object code form. This
71 # patent license shall apply to the combination of the Contribution
72 # and the Program if, at the time the Contribution is added by the
73 # Contributor, such addition of the Contribution causes such
74 # combination to be covered by the Licensed Patents. The patent
75 # license shall not apply to any other combinations which include
76 # the Contribution. No hardware per se is licensed hereunder.
77 #
78 # c) Recipient understands that although each Contributor grants the
79 # licenses to its Contributions set forth herein, no assurances are
80 # provided by any Contributor that the Program does not infringe the
81 # patent or other intellectual property rights of any other entity.
82 # Each Contributor disclaims any liability to Recipient for claims
83 # brought by any other entity based on infringement of intellectual
84 # property rights or otherwise. As a condition to exercising the
85 # rights and licenses granted hereunder, each Recipient hereby
86 # assumes sole responsibility to secure any other intellectual
87 # property rights needed, if any. For example, if a third party
88 # patent license is required to allow Recipient to distribute the
89 # Program, it is Recipient's responsibility to acquire that license
90 # before distributing the Program.
91 #
92 # d) Each Contributor represents that to its knowledge it has
93 # sufficient copyright rights in its Contribution, if any, to grant
94 # the copyright license set forth in this Agreement.
95 #
96 # 3. REQUIREMENTS
97 #
98 # A Contributor may choose to distribute the Program in object code
99 # form under its own license agreement, provided that:
100 #
101 # a) it complies with the terms and conditions of this Agreement;
102 #
103 # and
104 #
105 # b) its license agreement:
106 #
107 # i) effectively disclaims on behalf of all Contributors all
108 # warranties and conditions, express and implied, including
109 # warranties or conditions of title and non-infringement, and
110 # implied warranties or conditions of merchantability and fitness
111 # for a particular purpose;
112 #
113 # ii) effectively excludes on behalf of all Contributors all
114 # liability for damages, including direct, indirect, special,
115 # incidental and consequential damages, such as lost profits;
116 # iii) states that any provisions which differ from this Agreement
117 # are offered by that Contributor alone and not by any other party;
118 # and
119 #
120 # iv) states that source code for the Program is available from such
121 # Contributor, and informs licensees how to obtain it in a
122 # reasonable manner on or through a medium customarily used for
123 # software exchange.
124 #
125 # When the Program is made available in source code form:
126 #
127 # a) it must be made available under this Agreement; and
128 #
129 # b) a copy of this Agreement must be included with each copy of the
130 # Program.
131 #
132 # Each Contributor must include the following in a conspicuous
133 # location in the Program:
134 #
135 # Copyright © {date here}, International Business Machines
136 # Corporation and others. All Rights Reserved.
137 #
138 # In addition, each Contributor must identify itself as the originator
139 # of its Contribution, if any, in a manner that reasonably allows
140 # subsequent Recipients to identify the originator of the
141 # Contribution.
142 #
143 # 4. COMMERCIAL DISTRIBUTION
144 #
145 # Commercial distributors of software may accept certain
146 # responsibilities with respect to end users, business partners and
147 # the like. While this license is intended to facilitate the
148 # commercial use of the Program, the Contributor who includes the
149 # Program in a commercial product offering should do so in a manner
150 # which does not create potential liability for other Contributors.
151 # Therefore, if a Contributor includes the Program in a commercial
152 # product offering, such Contributor ("Commercial Contributor") hereby
153 # agrees to defend and indemnify every other Contributor ("Indemnified
154 # Contributor") against any losses, damages and costs (collectively
155 # "Losses") arising from claims, lawsuits and other legal actions
156 # brought by a third party against the Indemnified Contributor to the
157 # extent caused by the acts or omissions of such Commercial
158 # Contributor in connection with its distribution of the Program in a
159 # commercial product offering. The obligations in this section do not
160 # apply to any claims or Losses relating to any actual or alleged
161 # intellectual property infringement. In order to qualify, an
162 # Indemnified Contributor must: a) promptly notify the Commercial
163 # Contributor in writing of such claim, and b) allow the Commercial
164 # Contributor to control, and cooperate with the Commercial
165 # Contributor in, the defense and any related settlement negotiations.
166 # The Indemnified Contributor may participate in any such claim at its
167 # own expense.
168 #
169 # For example, a Contributor might include the Program in a commercial
170 # product offering, Product X. That Contributor is then a Commercial
171 # Contributor. If that Commercial Contributor then makes performance
172 # claims, or offers warranties related to Product X, those performance
173 # claims and warranties are such Commercial Contributor's
174 # responsibility alone. Under this section, the Commercial Contributor
175 # would have to defend claims against the other Contributors related
176 # to those performance claims and warranties, and if a court requires
177 # any other Contributor to pay any damages as a result, the Commercial
178 # Contributor must pay those damages.
179 #
180 # 5. NO WARRANTY
181 #
182 # EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS
183 # PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
184 # ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION,
185 # ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT,
186 # MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient
187 # is solely responsible for determining the appropriateness of using
188 # and distributing the Program and assumes all risks associated with
189 # its exercise of rights under this Agreement, including but not
190 # limited to the risks and costs of program errors, compliance with
191 # applicable laws, damage to or loss of data, programs or equipment,
192 # and unavailability or interruption of operations.
193 #
194 # 6. DISCLAIMER OF LIABILITY
195 #
196 # EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT
197 # NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT,
198 # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
199 # (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON
200 # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
201 # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
202 # THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS
203 # GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
204 # DAMAGES.
205 #
206 # 7. GENERAL
207 #
208 # If any provision of this Agreement is invalid or unenforceable under
209 # applicable law, it shall not affect the validity or enforceability
210 # of the remainder of the terms of this Agreement, and without further
211 # action by the parties hereto, such provision shall be reformed to
212 # the minimum extent necessary to make such provision valid and
213 # enforceable.
214 #
215 # If Recipient institutes patent litigation against a Contributor with
216 # respect to a patent applicable to software (including a cross-claim
217 # or counterclaim in a lawsuit), then any patent licenses granted by
218 # that Contributor to such Recipient under this Agreement shall
219 # terminate as of the date such litigation is filed. In addition, If
220 # Recipient institutes patent litigation against any entity (including
221 # a cross-claim or counterclaim in a lawsuit) alleging that the
222 # Program itself (excluding combinations of the Program with other
223 # software or hardware) infringes such Recipient's patent(s), then
224 # such Recipient's rights granted under Section 2(b) shall terminate
225 # as of the date such litigation is filed.
226 #
227 # All Recipient's rights under this Agreement shall terminate if it
228 # fails to comply with any of the material terms or conditions of this
229 # Agreement and does not cure such failure in a reasonable period of
230 # time after becoming aware of such noncompliance. If all Recipient's
231 # rights under this Agreement terminate, Recipient agrees to cease use
232 # and distribution of the Program as soon as reasonably practicable.
233 # However, Recipient's obligations under this Agreement and any
234 # licenses granted by Recipient relating to the Program shall continue
235 # and survive.
236 #
237 # IBM may publish new versions (including revisions) of this Agreement
238 # from time to time. Each new version of the Agreement will be given a
239 # distinguishing version number. The Program (including Contributions)
240 # may always be distributed subject to the version of the Agreement
241 # under which it was received. In addition, after a new version of the
242 # Agreement is published, Contributor may elect to distribute the
243 # Program (including its Contributions) under the new version. No one
244 # other than IBM has the right to modify this Agreement. Except as
245 # expressly stated in Sections 2(a) and 2(b) above, Recipient receives
246 # no rights or licenses to the intellectual property of any
247 # Contributor under this Agreement, whether expressly, by implication,
248 # estoppel or otherwise. All rights in the Program not expressly
249 # granted under this Agreement are reserved.
250 #
251 # This Agreement is governed by the laws of the State of New York and
252 # the intellectual property laws of the United States of America. No
253 # party to this Agreement will bring a legal action under this
254 # Agreement more than one year after the cause of action arose. Each
255 # party waives its rights to a jury trial in any resulting litigation.
256 #
257 ###############################################################################
258  
259  
260 # Package name
261 package Apache::AuthzLDAP;
262  
263  
264 # Required libraries
265 use strict;
266 use mod_perl ();
267 use Apache::Constants ':common';
268 use Apache::Log ();
269 use Net::LDAP qw(:all);
270 use Text::ParseWords ();
271  
272  
273 # Global constants
274 use constant REQUIRE_OPTS => { 'inagroup' => 1,
275 'inmanygroups' => 2,
276 'inallgroups' => 3 };
277  
278  
279 # Global variables
280 $Apache::AuthzLDAP::VERSION = '1.11';
281  
282  
283 ###############################################################################
284 ###############################################################################
285 # check_group: check user membership in group
286 ###############################################################################
287 ###############################################################################
288 sub check_group {
289 my ($r, $ld, $basedn, $groupattrtype, $memberattrtype,
290 $userinfo, $groups, $nestedattrtype, $nested_groups,
291 $requirement, $recursion_depth) = @_;
292 my ($group, $authgroups, $member) = undef;
293 my $foundgroups = '';
294 my @grouplist = ();
295  
296 $r->log->debug("check_group: Recursion depth is $recursion_depth");
297 $r->log->debug("check_group: Parsing on $groups");
298 @grouplist = Text::ParseWords::parse_line('\s+', 0, $groups);
299  
300 foreach $group (@grouplist) {
301 # Look up the group
302 my $filter = qq(($groupattrtype=$group));
303 $r->log->debug("check_group: Iterating over group $group");
304 $r->log->debug("check_group: Using filter: $filter");
305 $r->log->debug("check_group: Using base: $basedn");
306 # Want to just validate group's existence, not get its contents
307 my $msg = $ld->search(base => $basedn, filter => $filter,
308 attrs => [ $nestedattrtype ]);
309 unless ($msg->code == LDAP_SUCCESS) {
310 $r->note_basic_auth_failure;
311 $r->log_reason("user $userinfo: Could not search for $group: " .
312 $msg->code . " " . $msg->error, $r->uri);
313 next unless $requirement == 3;
314 return AUTH_REQUIRED;
315 }
316  
317 # Did we get any entries?
318 unless ($msg->count) {
319 $r->log->debug("check_group: user $userinfo: could not find $group");
320 return AUTH_REQUIRED if $requirement == 3;
321 next;
322 }
323  
324 # Check the group
325 my $entry = $msg->first_entry; # Only want one
326 my $dn = $entry->dn;
327 $r->log->debug("check_group: Checking group $dn for $userinfo");
328 $msg = $ld->compare($dn, attr => $memberattrtype, value => $userinfo);
329  
330 if ($msg->code == LDAP_COMPARE_TRUE) {
331 return (OK, $group) unless $recursion_depth == 1;
332 if ($requirement == 1) {
333 $r->log->debug("LDAP compare inAGroup user found; returning");
334 return (OK, "\"$group\"");
335 } elsif ($foundgroups eq '') {
336 $r->log->debug("LDAP compare inManyGroups or inAllGroups user found; appending");
337 $foundgroups = "\"$group\"";
338 } else {
339 $r->log->debug("LDAP compare inManyGroups or inAllGroups user found; appending");
340 $foundgroups .= " \"$group\"";
341 }
342 next;
343 }
344  
345 # Return undef if nested groups is not set
346 $r->log->debug("check_group: Could not find $userinfo in $group");
347 next unless $nested_groups =~ /on/i;
348  
349 # If we did not find the person in the group let's check the
350 # group's members
351 foreach $member ($entry->get($nestedattrtype)) {
352 $r->log->debug("check_group: Checking $member");
353 # We just want the group's name
354 if ($member =~ /^[^=]+="([^"]+)",/) {
355 $member = $1;
356 $r->log->debug("check_group: Setting quoted $member");
357 } elsif ($member =~ /^[^=]+=([^,]+),/) {
358 $member = $1;
359 $r->log->debug("check_group: Examining escaped $member");
360 $member =~ s/\\(.)/$1/g;
361 $r->log->debug("check_group: Setting escaped $member");
362 }
363  
364 $r->log->debug("check_group: Member now $member");
365 my ($result, $child_group) = check_group($r, $ld, $basedn, $groupattrtype,
366 $memberattrtype, $userinfo,
367 "\"$member\"", $nestedattrtype,
368 $nested_groups, $requirement,
369 $recursion_depth + 1);
370 if ($recursion_depth != 1 && $result == OK) {
371 $r->log->debug("Recursion of $recursion_depth; returning OK");
372 return (OK, $group);
373 } elsif ($result == OK) {
374 if ($requirement == 1) {
375 $r->log->debug("Requirement inAGroup; returning");
376 return (OK, "\"$group\"");
377 } elsif ($foundgroups eq '') {
378 $r->log->debug("Requirement inManyGroups or inAllGroups; appending");
379 $foundgroups = "\"$group\"";
380 } else {
381 $r->log->debug("Requirement inManyGroups or inAllGroups; appending");
382 $foundgroups .= " \"$group\"";
383 }
384 next;
385 }
386 }
387 $r->log->debug("Requirement inAllGroups failed; returning"),
388 return AUTH_REQUIRED if $requirement == 3 &&
389 !($entry->exists($nestedattrtype));
390 }
391  
392 # This case happens when inManyGroups is required
393 $r->log->debug("inManyGroups success"),
394 return(OK, $foundgroups) if $foundgroups ne '';
395  
396 # We've fallen through without finding the user in the group
397 $r->log_reason("Could not find $userinfo in $groups", $r->uri);
398 return AUTH_REQUIRED;
399 }
400  
401  
402 ###############################################################################
403 ###############################################################################
404 # handler: hook into Apache/mod_perl API
405 ###############################################################################
406 ###############################################################################
407 sub handler {
408 my $r = shift;
409 return OK unless $r->is_initial_req; # only the first internal request
410 my $requires = $r->requires;
411 return OK unless $requires;
412  
413 my $username = $r->connection->user;
414  
415 # The required patch was not introduced in 1.26. It is no longer
416 # promised to be included in any timeframe. Commenting out.
417 # if ($mod_perl::VERSION < 1.26) {
418 # I shouldn't need to use the below lines as this module
419 # should never be called if there was a cache hit. Since
420 # set_handlers() doesn't work properly until 1.26 (according
421 # to Doug MacEachern) I have to work around it by cobbling
422 # together cheat sheets for the previous and subsequent
423 # handlers in this phase. I get the willies about the
424 # security implications in a general environment where you
425 # might be using someone else's handlers upstream or
426 # downstream...
427 my $group_sent = $r->subprocess_env("REMOTE_GROUP") ||
428 $r->headers_in->{'REMOTE_GROUP'};
429 my $cache_result = $r->notes('AuthzCache');
430 if ($group_sent && $cache_result eq 'hit') {
431 $r->log->debug("handler: upstream cache hit for ",
432 "user=$username, group=$group_sent");
433 return OK;
434 # }
435 }
436  
437 # Clear for paranoid security precautions
438 $r->subprocess_env(REMOTE_GROUP => undef);
439 undef($r->headers_in->{'REMOTE_GROUP'});
440  
441 my $basedn = $r->dir_config('AuthzBaseDN');
442 my $groupattrtype = $r->dir_config('AuthzGroupAttrType') || 'cn';
443 my $authzldapserver = $r->dir_config('AuthzLDAPServer') || "localhost";
444 my $authzldapport = $r->dir_config('AuthzLDAPPort') || 389;
445 my $authenldapserver = $r->dir_config('AuthenLDAPServer') ||
446 $r->dir_config('AuthzLDAPServer') || "localhost";
447 my $authenldapport = $r->dir_config('AuthenLDAPPort') ||
448 $r->dir_config('AuthzLDAPPort') || 389;
449 my $memberattrtype = $r->dir_config('AuthzMemberAttrType') || 'member';
450 my $memberattrvalue = $r->dir_config('AuthzMemberAttrValue') || 'cn';
451 my $nestedattrtype = $r->dir_config('AuthzNestedAttrType') || 'member';
452 my $nested_groups = $r->dir_config('AuthzNestedGroups');
453 my $requirement = $r->dir_config('AuthzRequire') || 'inAGroup';
454 my $uidattrtype = $r->dir_config('AuthzUidAttrType') || 'uid';
455 my $userbasedn = $r->dir_config('AuthenBaseDN');
456  
457 $requirement = REQUIRE_OPTS->{lc($requirement)} || 1;
458 $r->log->debug(join ", ", "AuthzBaseDN=$basedn",
459 "GroupAttrType=$groupattrtype",
460 "LDAPServer=$authzldapserver",
461 "MemberAttrType=$memberattrtype",
462 "MemberAttrValue=$memberattrvalue",
463 "NestedAttrType=$nestedattrtype",
464 "NestedGroups=$nested_groups",
465 "Requirement=$requirement",
466 "UserBaseDN=$userbasedn");
467  
468 for my $req (@$requires) {
469 my ($require, $rest) = split /\s+/, $req->{requirement}, 2;
470  
471 if ($require eq "user") { return OK
472 if grep $username eq $_, split /\s+/, $rest}
473 elsif ($require eq "valid-user") { return OK }
474 elsif ($require eq 'group') {
475 my $ld = undef;
476 # Connect to the server
477 unless ($ld = new Net::LDAP($authenldapserver,port => $authenldapport)) {
478 $r->note_basic_auth_failure;
479 $r->log_reason("user $username: Authen LDAP Connection Failed",$r->uri);
480 return SERVER_ERROR;
481 }
482  
483 # Bind anonymously
484 my $msg = $ld->bind;
485 unless ($msg->code == LDAP_SUCCESS) {
486 $r->note_basic_auth_failure;
487 $r->log_reason("user $username: Authen LDAP Initial Bind Failed: " .
488 $msg->code . " " . $msg->error, $r->uri);
489 return SERVER_ERROR;
490 }
491  
492 # Get user DN
493 $msg = $ld->search(base => $userbasedn,
494 filter => qq($uidattrtype=$username));
495 unless ($msg->code == LDAP_SUCCESS) {
496 $r->note_basic_auth_failure;
497 $r->log_reason("LDAP read failure " .
498 $msg->code . " " . $msg->error, $r->uri);
499 return SERVER_ERROR;
500 }
501 unless ($msg->count) {
502 $r->note_basic_auth_failure;
503 $r->log_reason("user ($uidattrtype) $username doesn't " .
504 "exist in LDAP " .
505 $msg->code . " " . $msg->error . $r->uri);
506 return AUTH_REQUIRED;
507 }
508  
509 my $userinfo = undef;
510 if ($memberattrvalue eq 'dn') {
511 $userinfo = $msg->first_entry->dn;
512 } else {
513 $userinfo = ($msg->first_entry->get($memberattrvalue))[0];
514 }
515 $r->log->debug("handler: Userinfo is $userinfo ($memberattrvalue)");
516  
517 $ld->unbind();
518 $ld = undef;
519 # Connect to the server
520 unless ($ld = new Net::LDAP($authzldapserver,port => $authzldapport)) {
521 $r->note_basic_auth_failure;
522 $r->log_reason("user $username: Authz LDAP Connection Failed",$r->uri);
523 return SERVER_ERROR;
524 }
525  
526 # Bind anonymously
527 $msg = $ld->bind;
528 unless ($msg->code == LDAP_SUCCESS) {
529 $r->note_basic_auth_failure;
530 $r->log_reason("user $username: Authz LDAP Initial Bind Failed: " .
531 $msg->code . " " . $msg->error, $r->uri);
532 return SERVER_ERROR;
533 }
534  
535 # Compare the username
536 my ($result, $group) = check_group($r, $ld, $basedn, $groupattrtype,
537 $memberattrtype, $userinfo, $rest,
538 $nestedattrtype, $nested_groups,
539 $requirement, 1);
540 return $result unless $result == OK;
541  
542 # Everything's A-OK
543 $r->log->debug("Setting REMOTE_GROUP to $group");
544 $r->subprocess_env(REMOTE_GROUP => $group);
545 $r->headers_in->{'REMOTE_GROUP'} = $group;
546 return OK;
547 }
548 }
549 }
550  
551 1;
552  
553 __END__