]> granicus.if.org Git - apache/blob - modules/aaa/mod_authnz_ldap.c
When checking direct group membership, interpret LDAP_NO_SUCH_ATTRIBUTE the same as
[apache] / modules / aaa / mod_authnz_ldap.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "ap_provider.h"
18 #include "httpd.h"
19 #include "http_config.h"
20 #include "ap_provider.h"
21 #include "http_core.h"
22 #include "http_log.h"
23 #include "http_protocol.h"
24 #include "http_request.h"
25 #include "util_ldap.h"
26
27 #include "mod_auth.h"
28
29 #include "apr_strings.h"
30 #include "apr_xlate.h"
31 #define APR_WANT_STRFUNC
32 #include "apr_want.h"
33 #include "apr_lib.h"
34
35 #if APR_HAVE_UNISTD_H
36 /* for getpid() */
37 #include <unistd.h>
38 #endif
39 #include <ctype.h>
40
41 #if !APR_HAS_LDAP
42 #error mod_authnz_ldap requires APR-util to have LDAP support built in. To fix add --with-ldap to ./configure.
43 #endif
44
45 static char *default_attributes[3] = { "member", "uniqueMember", NULL };
46
47 typedef struct {
48     apr_pool_t *pool;               /* Pool that this config is allocated from */
49 #if APR_HAS_THREADS
50     apr_thread_mutex_t *lock;       /* Lock for this config */
51 #endif
52
53     /* These parameters are all derived from the AuthLDAPURL directive */
54     char *url;                      /* String representation of the URL */
55
56     char *host;                     /* Name of the LDAP server (or space separated list) */
57     int port;                       /* Port of the LDAP server */
58     char *basedn;                   /* Base DN to do all searches from */
59     char *attribute;                /* Attribute to search for */
60     char **attributes;              /* Array of all the attributes to return */
61     int scope;                      /* Scope of the search */
62     char *filter;                   /* Filter to further limit the search  */
63     deref_options deref;            /* how to handle alias dereferening */
64     char *binddn;                   /* DN to bind to server (can be NULL) */
65     char *bindpw;                   /* Password to bind to server (can be NULL) */
66     int bind_authoritative;         /* If true, will return errors when bind fails */
67
68     int user_is_dn;                 /* If true, connection->user is DN instead of userid */
69     char *remote_user_attribute;    /* If set, connection->user is this attribute instead of userid */
70     int compare_dn_on_server;       /* If true, will use server to do DN compare */
71
72     int have_ldap_url;              /* Set if we have found an LDAP url */
73
74     apr_array_header_t *groupattr;  /* List of Group attributes identifying user members. Default:"member uniqueMember" */
75     int group_attrib_is_dn;         /* If true, the group attribute is the DN, otherwise,
76                                         it's the exact string passed by the HTTP client */
77     char **sgAttributes;            /* Array of strings constructed (post-config) from subgroupattrs. Last entry is NULL. */
78     apr_array_header_t *subgroupclasses; /* List of object classes of sub-groups. Default:"groupOfNames groupOfUniqueNames" */
79     int maxNestingDepth;            /* Maximum recursive nesting depth permitted during subgroup processing. Default: 10 */
80
81     int secure;                     /* True if SSL connections are requested */
82     char *authz_prefix;             /* Prefix for environment variables added during authz */
83     int initial_bind_as_user;               /* true if we should try to bind (to lookup DN) directly with the basic auth username */
84     ap_regex_t *bind_regex;         /* basic auth -> bind'able username regex */
85     const char *bind_subst;         /* basic auth -> bind'able username substitution */
86     int search_as_user;             /* true if authz searches should be done with the users credentials (when we did authn) */
87     int compare_as_user;            /* true if authz compares should be done with the users credentials (when we did authn) */
88 } authn_ldap_config_t;
89
90 typedef struct {
91     char *dn;                       /* The saved dn from a successful search */
92     char *user;                     /* The username provided by the client */
93     const char **vals;              /* The additional values pulled during the DN search*/
94     char *password;                 /* if this module successfully authenticates, the basic auth password, else null */
95 } authn_ldap_request_t;
96
97 enum auth_ldap_phase {
98     LDAP_AUTHN, LDAP_AUTHZ
99 };
100
101 enum auth_ldap_optype {
102     LDAP_SEARCH, LDAP_COMPARE, LDAP_COMPARE_AND_SEARCH /* nested groups */
103 };
104
105 /* maximum group elements supported */
106 #define GROUPATTR_MAX_ELTS 10
107
108 module AP_MODULE_DECLARE_DATA authnz_ldap_module;
109
110 static APR_OPTIONAL_FN_TYPE(uldap_connection_close) *util_ldap_connection_close;
111 static APR_OPTIONAL_FN_TYPE(uldap_connection_find) *util_ldap_connection_find;
112 static APR_OPTIONAL_FN_TYPE(uldap_cache_comparedn) *util_ldap_cache_comparedn;
113 static APR_OPTIONAL_FN_TYPE(uldap_cache_compare) *util_ldap_cache_compare;
114 static APR_OPTIONAL_FN_TYPE(uldap_cache_check_subgroups) *util_ldap_cache_check_subgroups;
115 static APR_OPTIONAL_FN_TYPE(uldap_cache_checkuserid) *util_ldap_cache_checkuserid;
116 static APR_OPTIONAL_FN_TYPE(uldap_cache_getuserdn) *util_ldap_cache_getuserdn;
117 static APR_OPTIONAL_FN_TYPE(uldap_ssl_supported) *util_ldap_ssl_supported;
118
119 static apr_hash_t *charset_conversions = NULL;
120 static char *to_charset = NULL;           /* UTF-8 identifier derived from the charset.conv file */
121
122
123 /* Derive a code page ID give a language name or ID */
124 static char* derive_codepage_from_lang (apr_pool_t *p, char *language)
125 {
126     int lang_len;
127     char *charset;
128
129     if (!language)          /* our default codepage */
130         return apr_pstrdup(p, "ISO-8859-1");
131     else
132         lang_len = strlen(language);
133
134     charset = (char*) apr_hash_get(charset_conversions, language, APR_HASH_KEY_STRING);
135
136     if (!charset) {
137         language[2] = '\0';
138         charset = (char*) apr_hash_get(charset_conversions, language, APR_HASH_KEY_STRING);
139     }
140
141     if (charset) {
142         charset = apr_pstrdup(p, charset);
143     }
144
145     return charset;
146 }
147
148 static apr_xlate_t* get_conv_set (request_rec *r)
149 {
150     char *lang_line = (char*)apr_table_get(r->headers_in, "accept-language");
151     char *lang;
152     apr_xlate_t *convset;
153
154     if (lang_line) {
155         lang_line = apr_pstrdup(r->pool, lang_line);
156         for (lang = lang_line;*lang;lang++) {
157             if ((*lang == ',') || (*lang == ';')) {
158                 *lang = '\0';
159                 break;
160             }
161         }
162         lang = derive_codepage_from_lang(r->pool, lang_line);
163
164         if (lang && (apr_xlate_open(&convset, to_charset, lang, r->pool) == APR_SUCCESS)) {
165             return convset;
166         }
167     }
168
169     return NULL;
170 }
171
172
173 static const char* authn_ldap_xlate_password(request_rec *r,
174                                              const char* sent_password)
175 {
176     apr_xlate_t *convset = NULL;
177     apr_size_t inbytes;
178     apr_size_t outbytes;
179     char *outbuf;
180
181     if (charset_conversions && (convset = get_conv_set(r)) ) {
182         inbytes = strlen(sent_password);
183         outbytes = (inbytes+1)*3;
184         outbuf = apr_pcalloc(r->pool, outbytes);
185
186         /* Convert the password to UTF-8. */
187         if (apr_xlate_conv_buffer(convset, sent_password, &inbytes, outbuf,
188                                   &outbytes) == APR_SUCCESS)
189             return outbuf;
190     }
191
192     return sent_password;
193 }
194
195
196 /*
197  * Build the search filter, or at least as much of the search filter that
198  * will fit in the buffer. We don't worry about the buffer not being able
199  * to hold the entire filter. If the buffer wasn't big enough to hold the
200  * filter, ldap_search_s will complain, but the only situation where this
201  * is likely to happen is if the client sent a really, really long
202  * username, most likely as part of an attack.
203  *
204  * The search filter consists of the filter provided with the URL,
205  * combined with a filter made up of the attribute provided with the URL,
206  * and the actual username passed by the HTTP client. For example, assume
207  * that the LDAP URL is
208  *
209  *   ldap://ldap.airius.com/ou=People, o=Airius?uid??(posixid=*)
210  *
211  * Further, assume that the userid passed by the client was `userj'.  The
212  * search filter will be (&(posixid=*)(uid=userj)).
213  */
214 #define FILTER_LENGTH MAX_STRING_LEN
215 static void authn_ldap_build_filter(char *filtbuf,
216                              request_rec *r,
217                              const char* sent_user,
218                              const char* sent_filter,
219                              authn_ldap_config_t *sec)
220 {
221     char *p, *q, *filtbuf_end;
222     char *user, *filter;
223     apr_xlate_t *convset = NULL;
224     apr_size_t inbytes;
225     apr_size_t outbytes;
226     char *outbuf;
227
228     if (sent_user != NULL) {
229         user = apr_pstrdup (r->pool, sent_user);
230     }
231     else
232         return;
233
234     if (sent_filter != NULL) {
235         filter = apr_pstrdup (r->pool, sent_filter);
236     }
237     else
238         filter = sec->filter;
239
240     if (charset_conversions) {
241         convset = get_conv_set(r);
242     }
243
244     if (convset) {
245         inbytes = strlen(user);
246         outbytes = (inbytes+1)*3;
247         outbuf = apr_pcalloc(r->pool, outbytes);
248
249         /* Convert the user name to UTF-8.  This is only valid for LDAP v3 */
250         if (apr_xlate_conv_buffer(convset, user, &inbytes, outbuf, &outbytes) == APR_SUCCESS) {
251             user = apr_pstrdup(r->pool, outbuf);
252         }
253     }
254
255     /*
256      * Create the first part of the filter, which consists of the
257      * config-supplied portions.
258      */
259     apr_snprintf(filtbuf, FILTER_LENGTH, "(&(%s)(%s=", filter, sec->attribute);
260
261     /*
262      * Now add the client-supplied username to the filter, ensuring that any
263      * LDAP filter metachars are escaped.
264      */
265     filtbuf_end = filtbuf + FILTER_LENGTH - 1;
266 #if APR_HAS_MICROSOFT_LDAPSDK
267     for (p = user, q=filtbuf + strlen(filtbuf);
268          *p && q < filtbuf_end; ) {
269         if (strchr("*()\\", *p) != NULL) {
270             if ( q + 3 >= filtbuf_end)
271               break;  /* Don't write part of escape sequence if we can't write all of it */
272             *q++ = '\\';
273             switch ( *p++ )
274             {
275               case '*':
276                 *q++ = '2';
277                 *q++ = 'a';
278                 break;
279               case '(':
280                 *q++ = '2';
281                 *q++ = '8';
282                 break;
283               case ')':
284                 *q++ = '2';
285                 *q++ = '9';
286                 break;
287               case '\\':
288                 *q++ = '5';
289                 *q++ = 'c';
290                 break;
291                         }
292         }
293         else
294             *q++ = *p++;
295     }
296 #else
297     for (p = user, q=filtbuf + strlen(filtbuf);
298          *p && q < filtbuf_end; *q++ = *p++) {
299         if (strchr("*()\\", *p) != NULL) {
300             *q++ = '\\';
301             if (q >= filtbuf_end) {
302               break;
303             }
304         }
305     }
306 #endif
307     *q = '\0';
308
309     /*
310      * Append the closing parens of the filter, unless doing so would
311      * overrun the buffer.
312      */
313     if (q + 2 <= filtbuf_end)
314         strcat(filtbuf, "))");
315 }
316
317 static void *create_authnz_ldap_dir_config(apr_pool_t *p, char *d)
318 {
319     authn_ldap_config_t *sec =
320         (authn_ldap_config_t *)apr_pcalloc(p, sizeof(authn_ldap_config_t));
321
322     sec->pool = p;
323 #if APR_HAS_THREADS
324     apr_thread_mutex_create(&sec->lock, APR_THREAD_MUTEX_DEFAULT, p);
325 #endif
326 /*
327     sec->authz_enabled = 1;
328 */
329     sec->groupattr = apr_array_make(p, GROUPATTR_MAX_ELTS,
330                                     sizeof(struct mod_auth_ldap_groupattr_entry_t));
331     sec->subgroupclasses = apr_array_make(p, GROUPATTR_MAX_ELTS,
332                                     sizeof(struct mod_auth_ldap_groupattr_entry_t));
333
334     sec->have_ldap_url = 0;
335     sec->url = "";
336     sec->host = NULL;
337     sec->binddn = NULL;
338     sec->bindpw = NULL;
339     sec->bind_authoritative = 1;
340     sec->deref = always;
341     sec->group_attrib_is_dn = 1;
342     sec->secure = -1;   /*Initialize to unset*/
343     sec->maxNestingDepth = 10;
344     sec->sgAttributes = apr_pcalloc(p, sizeof (char *) * GROUPATTR_MAX_ELTS + 1);
345
346     sec->user_is_dn = 0;
347     sec->remote_user_attribute = NULL;
348     sec->compare_dn_on_server = 0;
349
350     sec->authz_prefix = AUTHZ_PREFIX;
351
352     return sec;
353 }
354
355 static apr_status_t authnz_ldap_cleanup_connection_close(void *param)
356 {
357     util_ldap_connection_t *ldc = param;
358     util_ldap_connection_close(ldc);
359     return APR_SUCCESS;
360 }
361
362 static int set_request_vars(request_rec *r, enum auth_ldap_phase phase) { 
363     char *prefix = NULL;
364     int prefix_len;
365     int remote_user_attribute_set = 0;
366     authn_ldap_request_t *req =
367         (authn_ldap_request_t *)ap_get_module_config(r->request_config, &authnz_ldap_module);
368     authn_ldap_config_t *sec =
369         (authn_ldap_config_t *)ap_get_module_config(r->per_dir_config, &authnz_ldap_module);
370     const char **vals = req->vals;
371
372     prefix = (phase == LDAP_AUTHN) ? AUTHN_PREFIX : sec->authz_prefix;
373     prefix_len = strlen(prefix);
374
375     if (sec->attributes && vals) {
376         apr_table_t *e = r->subprocess_env;
377         int i = 0;
378         while (sec->attributes[i]) {
379             char *str = apr_pstrcat(r->pool, prefix, sec->attributes[i], NULL);
380             int j = prefix_len;
381             while (str[j]) {
382                 str[j] = apr_toupper(str[j]);
383                 j++;
384             }
385             apr_table_setn(e, str, vals[i] ? vals[i] : "");
386
387             /* handle remote_user_attribute, if set */
388             if ((phase == LDAP_AUTHN) &&
389                 sec->remote_user_attribute && 
390                 !strcmp(sec->remote_user_attribute, sec->attributes[i])) {
391                 r->user = (char *)apr_pstrdup(r->pool, vals[i]);
392                 remote_user_attribute_set = 1;
393             }
394             i++;
395         }
396     }
397     return remote_user_attribute_set;
398 }
399
400 static const char *ldap_determine_binddn(request_rec *r, const char *user) {
401     authn_ldap_config_t *sec =
402         (authn_ldap_config_t *)ap_get_module_config(r->per_dir_config, &authnz_ldap_module);
403     const char *result = user;
404     ap_regmatch_t regm[AP_MAX_REG_MATCH];
405
406     if (NULL == user || NULL == sec || !sec->bind_regex || !sec->bind_subst) {
407         return result;
408     }
409
410     if (!ap_regexec(sec->bind_regex, user, AP_MAX_REG_MATCH, regm, 0)) {
411         char *substituted = ap_pregsub(r->pool, sec->bind_subst, user, AP_MAX_REG_MATCH, regm);
412         if (NULL != substituted) {
413             result = substituted;
414         }
415     }
416
417     apr_table_set(r->subprocess_env, "LDAP_BINDASUSER", result);
418
419     return result;
420 }
421
422
423 /* Some LDAP servers restrict who can search or compare, and the hard-coded ID
424  * might be good for the DN lookup but not for later operations.
425  */
426 static util_ldap_connection_t *get_connection_for_authz(request_rec *r, enum auth_ldap_optype type) {
427     authn_ldap_request_t *req =
428         (authn_ldap_request_t *)ap_get_module_config(r->request_config, &authnz_ldap_module);
429     authn_ldap_config_t *sec =
430         (authn_ldap_config_t *)ap_get_module_config(r->per_dir_config, &authnz_ldap_module);
431
432     char *binddn = sec->binddn;
433     char *bindpw = sec->bindpw;
434
435     /* If the per-request config isn't set, we didn't authenticate this user, and leave the default credentials */
436     if (req && req->password &&
437          ((type == LDAP_SEARCH && sec->search_as_user)    ||
438           (type == LDAP_COMPARE && sec->compare_as_user)  ||
439           (type == LDAP_COMPARE_AND_SEARCH && sec->compare_as_user && sec->search_as_user))){
440             binddn = req->dn;
441             bindpw = req->password;
442     }
443
444     return util_ldap_connection_find(r, sec->host, sec->port,
445                                      binddn, bindpw,
446                                      sec->deref, sec->secure);
447 }
448 /*
449  * Authentication Phase
450  * --------------------
451  *
452  * This phase authenticates the credentials the user has sent with
453  * the request (ie the username and password are checked). This is done
454  * by making an attempt to bind to the LDAP server using this user's
455  * DN and the supplied password.
456  *
457  */
458 static authn_status authn_ldap_check_password(request_rec *r, const char *user,
459                                               const char *password)
460 {
461     int failures = 0;
462     char filtbuf[FILTER_LENGTH];
463     authn_ldap_config_t *sec =
464         (authn_ldap_config_t *)ap_get_module_config(r->per_dir_config, &authnz_ldap_module);
465
466     util_ldap_connection_t *ldc = NULL;
467     int result = 0;
468     int remote_user_attribute_set = 0;
469     const char *dn = NULL;
470     const char *utfpassword;
471
472     authn_ldap_request_t *req =
473         (authn_ldap_request_t *)apr_pcalloc(r->pool, sizeof(authn_ldap_request_t));
474     ap_set_module_config(r->request_config, &authnz_ldap_module, req);
475
476 /*
477     if (!sec->enabled) {
478         return AUTH_USER_NOT_FOUND;
479     }
480 */
481
482     /*
483      * Basic sanity checks before any LDAP operations even happen.
484      */
485     if (!sec->have_ldap_url) {
486         return AUTH_GENERAL_ERROR;
487     }
488
489 start_over:
490
491     /* There is a good AuthLDAPURL, right? */
492     if (sec->host) {
493         const char *binddn = sec->binddn;
494         const char *bindpw = sec->bindpw;
495         if (sec->initial_bind_as_user) {
496             bindpw = password;
497             binddn = ldap_determine_binddn(r, user);
498         }
499
500         ldc = util_ldap_connection_find(r, sec->host, sec->port,
501                                        binddn, bindpw,
502                                        sec->deref, sec->secure);
503     }
504     else {
505         ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
506                       "[%" APR_PID_T_FMT "] auth_ldap authenticate: no sec->host - weird...?", getpid());
507         return AUTH_GENERAL_ERROR;
508     }
509
510     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
511                   "[%" APR_PID_T_FMT "] auth_ldap authenticate: using URL %s", getpid(), sec->url);
512
513     /* Get the password that the client sent */
514     if (password == NULL) {
515         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
516                       "[%" APR_PID_T_FMT "] auth_ldap authenticate: no password specified", getpid());
517         util_ldap_connection_close(ldc);
518         return AUTH_GENERAL_ERROR;
519     }
520
521     if (user == NULL) {
522         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
523                       "[%" APR_PID_T_FMT "] auth_ldap authenticate: no user specified", getpid());
524         util_ldap_connection_close(ldc);
525         return AUTH_GENERAL_ERROR;
526     }
527
528     /* build the username filter */
529     authn_ldap_build_filter(filtbuf, r, user, NULL, sec);
530
531     /* convert password to utf-8 */
532     utfpassword = authn_ldap_xlate_password(r, password);
533
534     /* do the user search */
535     result = util_ldap_cache_checkuserid(r, ldc, sec->url, sec->basedn, sec->scope,
536                                          sec->attributes, filtbuf, utfpassword,
537                                          &dn, &(req->vals));
538     util_ldap_connection_close(ldc);
539
540     /* sanity check - if server is down, retry it up to 5 times */
541     if (AP_LDAP_IS_SERVER_DOWN(result)) {
542         if (failures++ <= 5) {
543             goto start_over;
544         }
545     }
546
547     /* handle bind failure */
548     if (result != LDAP_SUCCESS) {
549         if (!sec->bind_authoritative) {
550            ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
551                       "[%" APR_PID_T_FMT "] auth_ldap authenticate: "
552                       "user %s authentication failed; URI %s [%s][%s] (not authoritative)",
553                       getpid(), user, r->uri, ldc->reason, ldap_err2string(result));
554            return AUTH_USER_NOT_FOUND;
555         }
556
557         ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
558                       "[%" APR_PID_T_FMT "] auth_ldap authenticate: "
559                       "user %s authentication failed; URI %s [%s][%s]",
560                       getpid(), user, r->uri, ldc->reason, ldap_err2string(result));
561
562         return (LDAP_NO_SUCH_OBJECT == result) ? AUTH_USER_NOT_FOUND
563 #ifdef LDAP_SECURITY_ERROR
564                  : (LDAP_SECURITY_ERROR(result)) ? AUTH_DENIED
565 #else
566                  : (LDAP_INAPPROPRIATE_AUTH == result) ? AUTH_DENIED
567                  : (LDAP_INVALID_CREDENTIALS == result) ? AUTH_DENIED
568 #ifdef LDAP_INSUFFICIENT_ACCESS
569                  : (LDAP_INSUFFICIENT_ACCESS == result) ? AUTH_DENIED
570 #endif
571 #ifdef LDAP_INSUFFICIENT_RIGHTS
572                  : (LDAP_INSUFFICIENT_RIGHTS == result) ? AUTH_DENIED
573 #endif
574 #endif
575                  : AUTH_GENERAL_ERROR;
576     }
577
578     /* mark the user and DN */
579     req->dn = apr_pstrdup(r->pool, dn);
580     req->user = apr_pstrdup(r->pool, user);
581     req->password = apr_pstrdup(r->pool, password);
582     if (sec->user_is_dn) {
583         r->user = req->dn;
584     }
585
586     /* add environment variables */
587     remote_user_attribute_set = set_request_vars(r, LDAP_AUTHN);
588
589     /* sanity check */
590     if (sec->remote_user_attribute && !remote_user_attribute_set) {
591         ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
592                   "[%" APR_PID_T_FMT "] auth_ldap authenticate: "
593                   "REMOTE_USER was to be set with attribute '%s', "
594                   "but this attribute was not requested for in the "
595                   "LDAP query for the user. REMOTE_USER will fall "
596                   "back to username or DN as appropriate.", getpid(),
597                   sec->remote_user_attribute);
598     }
599
600     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
601                   "[%" APR_PID_T_FMT "] auth_ldap authenticate: accepting %s", getpid(), user);
602
603     return AUTH_GRANTED;
604 }
605
606 static authz_status ldapuser_check_authorization(request_rec *r,
607                                              const char *require_args)
608 {
609     int result = 0;
610     authn_ldap_request_t *req =
611         (authn_ldap_request_t *)ap_get_module_config(r->request_config, &authnz_ldap_module);
612     authn_ldap_config_t *sec =
613         (authn_ldap_config_t *)ap_get_module_config(r->per_dir_config, &authnz_ldap_module);
614
615     util_ldap_connection_t *ldc = NULL;
616
617     const char *t;
618     char *w;
619
620     char filtbuf[FILTER_LENGTH];
621     const char *dn = NULL;
622
623     if (!sec->have_ldap_url) {
624         return AUTHZ_DENIED;
625     }
626
627     if (sec->host) {
628         ldc = get_connection_for_authz(r, LDAP_COMPARE);
629         apr_pool_cleanup_register(r->pool, ldc,
630                                   authnz_ldap_cleanup_connection_close,
631                                   apr_pool_cleanup_null);
632     }
633     else {
634         ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
635                       "[%" APR_PID_T_FMT "] auth_ldap authorize: no sec->host - weird...?", getpid());
636         return AUTHZ_DENIED;
637     }
638
639     /*
640      * If we have been authenticated by some other module than mod_authnz_ldap,
641      * the req structure needed for authorization needs to be created
642      * and populated with the userid and DN of the account in LDAP
643      */
644
645     /* Check that we have a userid to start with */
646     if (!r->user) {
647         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
648             "access to %s failed, reason: no authenticated user", r->uri);
649         return AUTHZ_DENIED;
650     }
651
652     if (!strlen(r->user)) {
653         ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
654             "ldap authorize: Userid is blank, AuthType=%s",
655             r->ap_auth_type);
656     }
657
658     if(!req) {
659         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
660             "ldap authorize: Creating LDAP req structure");
661
662         req = (authn_ldap_request_t *)apr_pcalloc(r->pool,
663             sizeof(authn_ldap_request_t));
664
665         /* Build the username filter */
666         authn_ldap_build_filter(filtbuf, r, r->user, NULL, sec);
667
668         /* Search for the user DN */
669         result = util_ldap_cache_getuserdn(r, ldc, sec->url, sec->basedn,
670              sec->scope, sec->attributes, filtbuf, &dn, &(req->vals));
671
672         /* Search failed, log error and return failure */
673         if(result != LDAP_SUCCESS) {
674             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
675                 "auth_ldap authorise: User DN not found, %s", ldc->reason);
676             return AUTHZ_DENIED;
677         }
678
679         ap_set_module_config(r->request_config, &authnz_ldap_module, req);
680         req->dn = apr_pstrdup(r->pool, dn);
681         req->user = r->user;
682
683     }
684
685     if (req->dn == NULL || strlen(req->dn) == 0) {
686         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
687                       "[%" APR_PID_T_FMT "] auth_ldap authorize: "
688                       "require user: user's DN has not been defined; failing authorization",
689                       getpid());
690         return AUTHZ_DENIED;
691     }
692
693     /*
694      * First do a whole-line compare, in case it's something like
695      *   require user Babs Jensen
696      */
697     result = util_ldap_cache_compare(r, ldc, sec->url, req->dn, sec->attribute, require_args);
698     switch(result) {
699         case LDAP_COMPARE_TRUE: {
700             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
701                           "[%" APR_PID_T_FMT "] auth_ldap authorize: "
702                           "require user: authorization successful", getpid());
703             set_request_vars(r, LDAP_AUTHZ);
704             return AUTHZ_GRANTED;
705         }
706         default: {
707             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
708                           "[%" APR_PID_T_FMT "] auth_ldap authorize: require user: "
709                           "authorization failed [%s][%s]", getpid(),
710                           ldc->reason, ldap_err2string(result));
711         }
712     }
713
714     /*
715      * Now break apart the line and compare each word on it
716      */
717     t = require_args;
718     while ((w = ap_getword_conf(r->pool, &t)) && w[0]) {
719         result = util_ldap_cache_compare(r, ldc, sec->url, req->dn, sec->attribute, w);
720         switch(result) {
721             case LDAP_COMPARE_TRUE: {
722                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
723                               "[%" APR_PID_T_FMT "] auth_ldap authorize: "
724                               "require user: authorization successful", getpid());
725                 set_request_vars(r, LDAP_AUTHZ);
726                 return AUTHZ_GRANTED;
727             }
728             default: {
729                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
730                               "[%" APR_PID_T_FMT "] auth_ldap authorize: "
731                               "require user: authorization failed [%s][%s]",
732                               getpid(), ldc->reason, ldap_err2string(result));
733             }
734         }
735     }
736
737     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
738                   "[%" APR_PID_T_FMT "] auth_ldap authorize user: authorization denied for user %s to %s",
739                   getpid(), r->user, r->uri);
740
741     return AUTHZ_DENIED;
742 }
743
744 static authz_status ldapgroup_check_authorization(request_rec *r,
745                                              const char *require_args)
746 {
747     int result = 0;
748     authn_ldap_request_t *req =
749         (authn_ldap_request_t *)ap_get_module_config(r->request_config, &authnz_ldap_module);
750     authn_ldap_config_t *sec =
751         (authn_ldap_config_t *)ap_get_module_config(r->per_dir_config, &authnz_ldap_module);
752
753     util_ldap_connection_t *ldc = NULL;
754
755     const char *t;
756
757     char filtbuf[FILTER_LENGTH];
758     const char *dn = NULL;
759     struct mod_auth_ldap_groupattr_entry_t *ent;
760     int i;
761
762     if (!sec->have_ldap_url) {
763         return AUTHZ_DENIED;
764     }
765
766     if (sec->host) {
767         ldc = get_connection_for_authz(r, LDAP_COMPARE); /* for the top-level group only */
768         apr_pool_cleanup_register(r->pool, ldc,
769                                   authnz_ldap_cleanup_connection_close,
770                                   apr_pool_cleanup_null);
771     }
772     else {
773         ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
774                       "[%" APR_PID_T_FMT "] auth_ldap authorize: no sec->host - weird...?", getpid());
775         return AUTHZ_DENIED;
776     }
777
778     /*
779      * If there are no elements in the group attribute array, the default should be
780      * member and uniquemember; populate the array now.
781      */
782     if (sec->groupattr->nelts == 0) {
783         struct mod_auth_ldap_groupattr_entry_t *grp;
784 #if APR_HAS_THREADS
785         apr_thread_mutex_lock(sec->lock);
786 #endif
787         grp = apr_array_push(sec->groupattr);
788         grp->name = "member";
789         grp = apr_array_push(sec->groupattr);
790         grp->name = "uniqueMember";
791 #if APR_HAS_THREADS
792         apr_thread_mutex_unlock(sec->lock);
793 #endif
794     }
795
796     /*
797      * If there are no elements in the sub group classes array, the default
798      * should be groupOfNames and groupOfUniqueNames; populate the array now.
799      */
800     if (sec->subgroupclasses->nelts == 0) {
801         struct mod_auth_ldap_groupattr_entry_t *grp;
802 #if APR_HAS_THREADS
803         apr_thread_mutex_lock(sec->lock);
804 #endif
805         grp = apr_array_push(sec->subgroupclasses);
806         grp->name = "groupOfNames";
807         grp = apr_array_push(sec->subgroupclasses);
808         grp->name = "groupOfUniqueNames";
809 #if APR_HAS_THREADS
810         apr_thread_mutex_unlock(sec->lock);
811 #endif
812     }
813
814     /*
815      * If we have been authenticated by some other module than mod_auth_ldap,
816      * the req structure needed for authorization needs to be created
817      * and populated with the userid and DN of the account in LDAP
818      */
819
820     /* Check that we have a userid to start with */
821     if (!r->user) {
822         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
823             "access to %s failed, reason: no authenticated user", r->uri);
824         return AUTHZ_DENIED;
825     }
826
827     if (!strlen(r->user)) {
828         ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
829             "ldap authorize: Userid is blank, AuthType=%s",
830             r->ap_auth_type);
831     }
832
833     if(!req) {
834         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
835             "ldap authorize: Creating LDAP req structure");
836
837         /* Build the username filter */
838         authn_ldap_build_filter(filtbuf, r, r->user, NULL, sec);
839
840         /* Search for the user DN */
841         result = util_ldap_cache_getuserdn(r, ldc, sec->url, sec->basedn,
842              sec->scope, sec->attributes, filtbuf, &dn, &(req->vals));
843
844         /* Search failed, log error and return failure */
845         if(result != LDAP_SUCCESS) {
846             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
847                 "auth_ldap authorise: User DN not found, %s", ldc->reason);
848             return AUTHZ_DENIED;
849         }
850
851         req = (authn_ldap_request_t *)apr_pcalloc(r->pool,
852             sizeof(authn_ldap_request_t));
853         ap_set_module_config(r->request_config, &authnz_ldap_module, req);
854         req->dn = apr_pstrdup(r->pool, dn);
855         req->user = r->user;
856     }
857
858     ent = (struct mod_auth_ldap_groupattr_entry_t *) sec->groupattr->elts;
859
860     if (sec->group_attrib_is_dn) {
861         if (req->dn == NULL || strlen(req->dn) == 0) {
862             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
863                           "[%" APR_PID_T_FMT "] auth_ldap authorize: require group: "
864                           "user's DN has not been defined; failing authorization for user %s",
865                           getpid(), r->user);
866             return AUTHZ_DENIED;
867         }
868     }
869     else {
870         if (req->user == NULL || strlen(req->user) == 0) {
871             /* We weren't called in the authentication phase, so we didn't have a
872              * chance to set the user field. Do so now. */
873             req->user = r->user;
874         }
875     }
876
877     t = require_args;
878
879     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
880                   "[%" APR_PID_T_FMT "] auth_ldap authorize: require group: "
881                   "testing for group membership in \"%s\"",
882                   getpid(), t);
883
884     for (i = 0; i < sec->groupattr->nelts; i++) {
885         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
886                       "[%" APR_PID_T_FMT "] auth_ldap authorize: require group: "
887                       "testing for %s: %s (%s)", getpid(),
888                       ent[i].name, sec->group_attrib_is_dn ? req->dn : req->user, t);
889
890         result = util_ldap_cache_compare(r, ldc, sec->url, t, ent[i].name,
891                              sec->group_attrib_is_dn ? req->dn : req->user);
892         switch(result) {
893             case LDAP_COMPARE_TRUE: {
894                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
895                               "[%" APR_PID_T_FMT "] auth_ldap authorize: require group: "
896                               "authorization successful (attribute %s) [%s][%d - %s]",
897                               getpid(), ent[i].name, ldc->reason, result, ldap_err2string(result));
898                 set_request_vars(r, LDAP_AUTHZ);
899                 return AUTHZ_GRANTED;
900             }
901             case LDAP_NO_SUCH_ATTRIBUTE: 
902             case LDAP_COMPARE_FALSE: {
903                 /* nested groups need searches and compares, so grab a new handle */
904                 authnz_ldap_cleanup_connection_close(ldc);
905                 apr_pool_cleanup_kill(r->pool, ldc,authnz_ldap_cleanup_connection_close);
906
907                 ldc = get_connection_for_authz(r, LDAP_COMPARE_AND_SEARCH);
908                 apr_pool_cleanup_register(r->pool, ldc,
909                                           authnz_ldap_cleanup_connection_close,
910                                           apr_pool_cleanup_null);
911
912                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
913                                "[%" APR_PID_T_FMT "] auth_ldap authorise: require group \"%s\": "
914                                "failed [%s][%d - %s], checking sub-groups",
915                                getpid(), t, ldc->reason, result, ldap_err2string(result));
916
917                 result = util_ldap_cache_check_subgroups(r, ldc, sec->url, t, ent[i].name,
918                                                          sec->group_attrib_is_dn ? req->dn : req->user,
919                                                          sec->sgAttributes[0] ? sec->sgAttributes : default_attributes,
920                                                          sec->subgroupclasses,
921                                                          0, sec->maxNestingDepth);
922                 if(result == LDAP_COMPARE_TRUE) {
923                     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
924                                    "[%" APR_PID_T_FMT "] auth_ldap authorise: require group (sub-group): "
925                                    "authorisation successful (attribute %s) [%s][%d - %s]",
926                                    getpid(), ent[i].name, ldc->reason, result, ldap_err2string(result));
927                     set_request_vars(r, LDAP_AUTHZ);
928                     return AUTHZ_GRANTED;
929                 }
930                 else {
931                     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
932                                    "[%" APR_PID_T_FMT "] auth_ldap authorise: require group (sub-group) \"%s\": "
933                                    "authorisation failed [%s][%d - %s]",
934                                    getpid(), t, ldc->reason, result, ldap_err2string(result));
935                 }
936                 break;
937             }
938             default: {
939                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
940                               "[%" APR_PID_T_FMT "] auth_ldap authorize: require group \"%s\": "
941                               "authorization failed [%s][%d - %s]",
942                               getpid(), t, ldc->reason, result, ldap_err2string(result));
943             }
944         }
945     }
946
947     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
948                   "[%" APR_PID_T_FMT "] auth_ldap authorize group: authorization denied for user %s to %s",
949                   getpid(), r->user, r->uri);
950
951     return AUTHZ_DENIED;
952 }
953
954 static authz_status ldapdn_check_authorization(request_rec *r,
955                                              const char *require_args)
956 {
957     int result = 0;
958     authn_ldap_request_t *req =
959         (authn_ldap_request_t *)ap_get_module_config(r->request_config, &authnz_ldap_module);
960     authn_ldap_config_t *sec =
961         (authn_ldap_config_t *)ap_get_module_config(r->per_dir_config, &authnz_ldap_module);
962
963     util_ldap_connection_t *ldc = NULL;
964
965     const char *t;
966
967     char filtbuf[FILTER_LENGTH];
968     const char *dn = NULL;
969
970     if (!sec->have_ldap_url) {
971         return AUTHZ_DENIED;
972     }
973
974     if (sec->host) {
975         ldc = get_connection_for_authz(r, LDAP_SEARCH); /* _comparedn is a searche */
976         apr_pool_cleanup_register(r->pool, ldc,
977                                   authnz_ldap_cleanup_connection_close,
978                                   apr_pool_cleanup_null);
979     }
980     else {
981         ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
982                       "[%" APR_PID_T_FMT "] auth_ldap authorize: no sec->host - weird...?", getpid());
983         return AUTHZ_DENIED;
984     }
985
986     /*
987      * If we have been authenticated by some other module than mod_auth_ldap,
988      * the req structure needed for authorization needs to be created
989      * and populated with the userid and DN of the account in LDAP
990      */
991
992     /* Check that we have a userid to start with */
993     if (!r->user) {
994         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
995             "access to %s failed, reason: no authenticated user", r->uri);
996         return AUTHZ_DENIED;
997     }
998
999     if (!strlen(r->user)) {
1000         ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
1001             "ldap authorize: Userid is blank, AuthType=%s",
1002             r->ap_auth_type);
1003     }
1004
1005     if(!req) {
1006         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1007             "ldap authorize: Creating LDAP req structure");
1008
1009         /* Build the username filter */
1010         authn_ldap_build_filter(filtbuf, r, r->user, NULL, sec);
1011
1012         /* Search for the user DN */
1013         result = util_ldap_cache_getuserdn(r, ldc, sec->url, sec->basedn,
1014              sec->scope, sec->attributes, filtbuf, &dn, &(req->vals));
1015
1016         /* Search failed, log error and return failure */
1017         if(result != LDAP_SUCCESS) {
1018             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1019                 "auth_ldap authorise: User DN not found, %s", ldc->reason);
1020             return AUTHZ_DENIED;
1021         }
1022
1023         req = (authn_ldap_request_t *)apr_pcalloc(r->pool,
1024             sizeof(authn_ldap_request_t));
1025         ap_set_module_config(r->request_config, &authnz_ldap_module, req);
1026         req->dn = apr_pstrdup(r->pool, dn);
1027         req->user = r->user;
1028     }
1029
1030     t = require_args;
1031
1032     if (req->dn == NULL || strlen(req->dn) == 0) {
1033         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1034                       "[%" APR_PID_T_FMT "] auth_ldap authorize: "
1035                       "require dn: user's DN has not been defined; failing authorization",
1036                       getpid());
1037         return AUTHZ_DENIED;
1038     }
1039
1040     result = util_ldap_cache_comparedn(r, ldc, sec->url, req->dn, t, sec->compare_dn_on_server);
1041     switch(result) {
1042         case LDAP_COMPARE_TRUE: {
1043             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1044                           "[%" APR_PID_T_FMT "] auth_ldap authorize: "
1045                           "require dn: authorization successful", getpid());
1046             set_request_vars(r, LDAP_AUTHZ);
1047             return AUTHZ_GRANTED;
1048         }
1049         default: {
1050             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1051                           "[%" APR_PID_T_FMT "] auth_ldap authorize: "
1052                           "require dn \"%s\": LDAP error [%s][%s]",
1053                           getpid(), t, ldc->reason, ldap_err2string(result));
1054         }
1055     }
1056
1057
1058     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1059                   "[%" APR_PID_T_FMT "] auth_ldap authorize dn: authorization denied for user %s to %s",
1060                   getpid(), r->user, r->uri);
1061
1062     return AUTHZ_DENIED;
1063 }
1064
1065 static authz_status ldapattribute_check_authorization(request_rec *r,
1066                                              const char *require_args)
1067 {
1068     int result = 0;
1069     authn_ldap_request_t *req =
1070         (authn_ldap_request_t *)ap_get_module_config(r->request_config, &authnz_ldap_module);
1071     authn_ldap_config_t *sec =
1072         (authn_ldap_config_t *)ap_get_module_config(r->per_dir_config, &authnz_ldap_module);
1073
1074     util_ldap_connection_t *ldc = NULL;
1075
1076     const char *t;
1077     char *w, *value;
1078
1079     char filtbuf[FILTER_LENGTH];
1080     const char *dn = NULL;
1081
1082     if (!sec->have_ldap_url) {
1083         return AUTHZ_DENIED;
1084     }
1085
1086     if (sec->host) {
1087         ldc = get_connection_for_authz(r, LDAP_COMPARE);
1088         apr_pool_cleanup_register(r->pool, ldc,
1089                                   authnz_ldap_cleanup_connection_close,
1090                                   apr_pool_cleanup_null);
1091     }
1092     else {
1093         ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
1094                       "[%" APR_PID_T_FMT "] auth_ldap authorize: no sec->host - weird...?", getpid());
1095         return AUTHZ_DENIED;
1096     }
1097
1098     /*
1099      * If we have been authenticated by some other module than mod_auth_ldap,
1100      * the req structure needed for authorization needs to be created
1101      * and populated with the userid and DN of the account in LDAP
1102      */
1103
1104     /* Check that we have a userid to start with */
1105     if (!r->user) {
1106         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1107             "access to %s failed, reason: no authenticated user", r->uri);
1108         return AUTHZ_DENIED;
1109     }
1110
1111     if (!strlen(r->user)) {
1112         ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
1113             "ldap authorize: Userid is blank, AuthType=%s",
1114             r->ap_auth_type);
1115     }
1116
1117     if(!req) {
1118         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1119             "ldap authorize: Creating LDAP req structure");
1120
1121         /* Build the username filter */
1122         authn_ldap_build_filter(filtbuf, r, r->user, NULL, sec);
1123
1124         /* Search for the user DN */
1125         result = util_ldap_cache_getuserdn(r, ldc, sec->url, sec->basedn,
1126              sec->scope, sec->attributes, filtbuf, &dn, &(req->vals));
1127
1128         /* Search failed, log error and return failure */
1129         if(result != LDAP_SUCCESS) {
1130             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1131                 "auth_ldap authorise: User DN not found, %s", ldc->reason);
1132             return AUTHZ_DENIED;
1133         }
1134
1135         req = (authn_ldap_request_t *)apr_pcalloc(r->pool,
1136             sizeof(authn_ldap_request_t));
1137         ap_set_module_config(r->request_config, &authnz_ldap_module, req);
1138         req->dn = apr_pstrdup(r->pool, dn);
1139         req->user = r->user;
1140     }
1141
1142     if (req->dn == NULL || strlen(req->dn) == 0) {
1143         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1144                       "[%" APR_PID_T_FMT "] auth_ldap authorize: "
1145                       "require ldap-attribute: user's DN has not been defined; failing authorization",
1146                       getpid());
1147         return AUTHZ_DENIED;
1148     }
1149
1150     t = require_args;
1151     while (t[0]) {
1152         w = ap_getword(r->pool, &t, '=');
1153         value = ap_getword_conf(r->pool, &t);
1154
1155         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1156                       "[%" APR_PID_T_FMT "] auth_ldap authorize: checking attribute"
1157                       " %s has value %s", getpid(), w, value);
1158         result = util_ldap_cache_compare(r, ldc, sec->url, req->dn, w, value);
1159         switch(result) {
1160             case LDAP_COMPARE_TRUE: {
1161                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG,
1162                               0, r, "[%" APR_PID_T_FMT "] auth_ldap authorize: "
1163                               "require attribute: authorization successful", 
1164                               getpid());
1165                 set_request_vars(r, LDAP_AUTHZ);
1166                 return AUTHZ_GRANTED;
1167             }
1168             default: {
1169                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG,
1170                               0, r, "[%" APR_PID_T_FMT "] auth_ldap authorize: "
1171                               "require attribute: authorization failed [%s][%s]", 
1172                               getpid(), ldc->reason, ldap_err2string(result));
1173             }
1174         }
1175     }
1176
1177     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1178                   "[%" APR_PID_T_FMT "] auth_ldap authorize attribute: authorization denied for user %s to %s",
1179                   getpid(), r->user, r->uri);
1180
1181     return AUTHZ_DENIED;
1182 }
1183
1184 static authz_status ldapfilter_check_authorization(request_rec *r,
1185                                              const char *require_args)
1186 {
1187     int result = 0;
1188     authn_ldap_request_t *req =
1189         (authn_ldap_request_t *)ap_get_module_config(r->request_config, &authnz_ldap_module);
1190     authn_ldap_config_t *sec =
1191         (authn_ldap_config_t *)ap_get_module_config(r->per_dir_config, &authnz_ldap_module);
1192
1193     util_ldap_connection_t *ldc = NULL;
1194     const char *t;
1195
1196     char filtbuf[FILTER_LENGTH];
1197     const char *dn = NULL;
1198
1199     if (!sec->have_ldap_url) {
1200         return AUTHZ_DENIED;
1201     }
1202
1203     if (sec->host) {
1204         ldc = get_connection_for_authz(r, LDAP_SEARCH);
1205         apr_pool_cleanup_register(r->pool, ldc,
1206                                   authnz_ldap_cleanup_connection_close,
1207                                   apr_pool_cleanup_null);
1208     }
1209     else {
1210         ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
1211                       "[%" APR_PID_T_FMT "] auth_ldap authorize: no sec->host - weird...?", getpid());
1212         return AUTHZ_DENIED;
1213     }
1214
1215     /*
1216      * If we have been authenticated by some other module than mod_auth_ldap,
1217      * the req structure needed for authorization needs to be created
1218      * and populated with the userid and DN of the account in LDAP
1219      */
1220
1221     /* Check that we have a userid to start with */
1222     if (!r->user) {
1223         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1224             "access to %s failed, reason: no authenticated user", r->uri);
1225         return AUTHZ_DENIED;
1226     }
1227
1228     if (!strlen(r->user)) {
1229         ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
1230             "ldap authorize: Userid is blank, AuthType=%s",
1231             r->ap_auth_type);
1232     }
1233
1234     if(!req) {
1235         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1236             "ldap authorize: Creating LDAP req structure");
1237
1238         /* Build the username filter */
1239         authn_ldap_build_filter(filtbuf, r, r->user, NULL, sec);
1240
1241         /* Search for the user DN */
1242         result = util_ldap_cache_getuserdn(r, ldc, sec->url, sec->basedn,
1243              sec->scope, sec->attributes, filtbuf, &dn, &(req->vals));
1244
1245         /* Search failed, log error and return failure */
1246         if(result != LDAP_SUCCESS) {
1247             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1248                 "auth_ldap authorise: User DN not found, %s", ldc->reason);
1249             return AUTHZ_DENIED;
1250         }
1251
1252         req = (authn_ldap_request_t *)apr_pcalloc(r->pool,
1253             sizeof(authn_ldap_request_t));
1254         ap_set_module_config(r->request_config, &authnz_ldap_module, req);
1255         req->dn = apr_pstrdup(r->pool, dn);
1256         req->user = r->user;
1257     }
1258
1259     if (req->dn == NULL || strlen(req->dn) == 0) {
1260         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1261                       "[%" APR_PID_T_FMT "] auth_ldap authorize: "
1262                       "require ldap-filter: user's DN has not been defined; failing authorization",
1263                       getpid());
1264         return AUTHZ_DENIED;
1265     }
1266
1267     t = require_args;
1268
1269     if (t[0]) {
1270         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1271                       "[%" APR_PID_T_FMT "] auth_ldap authorize: checking filter %s",
1272                       getpid(), t);
1273
1274         /* Build the username filter */
1275         authn_ldap_build_filter(filtbuf, r, req->user, t, sec);
1276
1277         /* Search for the user DN */
1278         result = util_ldap_cache_getuserdn(r, ldc, sec->url, sec->basedn,
1279              sec->scope, sec->attributes, filtbuf, &dn, &(req->vals));
1280
1281         /* Make sure that the filtered search returned the correct user dn */
1282         if (result == LDAP_SUCCESS) {
1283             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1284                           "[%" APR_PID_T_FMT "] auth_ldap authorize: checking dn match %s",
1285                           getpid(), dn);
1286             if (sec->compare_as_user) {
1287                 /* ldap-filter is the only authz that requires a search and a compare */
1288                 apr_pool_cleanup_kill(r->pool, ldc, authnz_ldap_cleanup_connection_close);
1289                 authnz_ldap_cleanup_connection_close(ldc);
1290                 ldc = get_connection_for_authz(r, LDAP_COMPARE);
1291             }
1292             result = util_ldap_cache_comparedn(r, ldc, sec->url, req->dn, dn,
1293                                                sec->compare_dn_on_server);
1294         }
1295
1296         switch(result) {
1297             case LDAP_COMPARE_TRUE: {
1298                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG,
1299                               0, r, "[%" APR_PID_T_FMT "] auth_ldap authorize: "
1300                               "require ldap-filter: authorization "
1301                               "successful", getpid());
1302                 set_request_vars(r, LDAP_AUTHZ);
1303                 return AUTHZ_GRANTED;
1304             }
1305             case LDAP_FILTER_ERROR: {
1306                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG,
1307                               0, r, "[%" APR_PID_T_FMT "] auth_ldap authorize: "
1308                               "require ldap-filter: %s authorization "
1309                               "failed [%s][%s]", getpid(),
1310                               filtbuf, ldc->reason, ldap_err2string(result));
1311                 break;
1312             }
1313             default: {
1314                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG,
1315                               0, r, "[%" APR_PID_T_FMT "] auth_ldap authorize: "
1316                               "require ldap-filter: authorization "
1317                               "failed [%s][%s]", getpid(),
1318                               ldc->reason, ldap_err2string(result));
1319             }
1320         }
1321     }
1322
1323     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1324                   "[%" APR_PID_T_FMT "] auth_ldap authorize filter: authorization denied for user %s to %s",
1325                   getpid(), r->user, r->uri);
1326
1327     return AUTHZ_DENIED;
1328 }
1329
1330
1331 /*
1332  * Use the ldap url parsing routines to break up the ldap url into
1333  * host and port.
1334  */
1335 static const char *mod_auth_ldap_parse_url(cmd_parms *cmd,
1336                                     void *config,
1337                                     const char *url,
1338                                     const char *mode)
1339 {
1340     int rc;
1341     apr_ldap_url_desc_t *urld;
1342     apr_ldap_err_t *result;
1343
1344     authn_ldap_config_t *sec = config;
1345
1346     rc = apr_ldap_url_parse(cmd->pool, url, &(urld), &(result));
1347     if (rc != APR_SUCCESS) {
1348         return result->reason;
1349     }
1350     sec->url = apr_pstrdup(cmd->pool, url);
1351
1352     /* Set all the values, or at least some sane defaults */
1353     if (sec->host) {
1354         sec->host = apr_pstrcat(cmd->pool, urld->lud_host, " ", sec->host, NULL);
1355     }
1356     else {
1357         sec->host = urld->lud_host? apr_pstrdup(cmd->pool, urld->lud_host) : "localhost";
1358     }
1359     sec->basedn = urld->lud_dn? apr_pstrdup(cmd->pool, urld->lud_dn) : "";
1360     if (urld->lud_attrs && urld->lud_attrs[0]) {
1361         int i = 1;
1362         while (urld->lud_attrs[i]) {
1363             i++;
1364         }
1365         sec->attributes = apr_pcalloc(cmd->pool, sizeof(char *) * (i+1));
1366         i = 0;
1367         while (urld->lud_attrs[i]) {
1368             sec->attributes[i] = apr_pstrdup(cmd->pool, urld->lud_attrs[i]);
1369             i++;
1370         }
1371         sec->attribute = sec->attributes[0];
1372     }
1373     else {
1374         sec->attribute = "uid";
1375     }
1376
1377     sec->scope = urld->lud_scope == LDAP_SCOPE_ONELEVEL ?
1378         LDAP_SCOPE_ONELEVEL : LDAP_SCOPE_SUBTREE;
1379
1380     if (urld->lud_filter) {
1381         if (urld->lud_filter[0] == '(') {
1382             /*
1383              * Get rid of the surrounding parens; later on when generating the
1384              * filter, they'll be put back.
1385              */
1386             sec->filter = apr_pstrdup(cmd->pool, urld->lud_filter+1);
1387             sec->filter[strlen(sec->filter)-1] = '\0';
1388         }
1389         else {
1390             sec->filter = apr_pstrdup(cmd->pool, urld->lud_filter);
1391         }
1392     }
1393     else {
1394         sec->filter = "objectclass=*";
1395     }
1396
1397     if (mode) {
1398         if (0 == strcasecmp("NONE", mode)) {
1399             sec->secure = APR_LDAP_NONE;
1400         }
1401         else if (0 == strcasecmp("SSL", mode)) {
1402             sec->secure = APR_LDAP_SSL;
1403         }
1404         else if (0 == strcasecmp("TLS", mode) || 0 == strcasecmp("STARTTLS", mode)) {
1405             sec->secure = APR_LDAP_STARTTLS;
1406         }
1407         else {
1408             return "Invalid LDAP connection mode setting: must be one of NONE, "
1409                    "SSL, or TLS/STARTTLS";
1410         }
1411     }
1412
1413       /* "ldaps" indicates secure ldap connections desired
1414       */
1415     if (strncasecmp(url, "ldaps", 5) == 0)
1416     {
1417         sec->secure = APR_LDAP_SSL;
1418         sec->port = urld->lud_port? urld->lud_port : LDAPS_PORT;
1419     }
1420     else
1421     {
1422         sec->port = urld->lud_port? urld->lud_port : LDAP_PORT;
1423     }
1424
1425     sec->have_ldap_url = 1;
1426
1427     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
1428                  cmd->server, "[%" APR_PID_T_FMT "] auth_ldap url parse: `%s', Host: %s, Port: %d, DN: %s, attrib: %s, scope: %s, filter: %s, connection mode: %s",
1429                  getpid(),
1430                  url,
1431                  urld->lud_host,
1432                  urld->lud_port,
1433                  urld->lud_dn,
1434                  urld->lud_attrs? urld->lud_attrs[0] : "(null)",
1435                  (urld->lud_scope == LDAP_SCOPE_SUBTREE? "subtree" :
1436                   urld->lud_scope == LDAP_SCOPE_BASE? "base" :
1437                   urld->lud_scope == LDAP_SCOPE_ONELEVEL? "onelevel" : "unknown"),
1438                  urld->lud_filter,
1439                  sec->secure == APR_LDAP_SSL  ? "using SSL": "not using SSL"
1440                  );
1441
1442     return NULL;
1443 }
1444
1445 static const char *mod_auth_ldap_set_deref(cmd_parms *cmd, void *config, const char *arg)
1446 {
1447     authn_ldap_config_t *sec = config;
1448
1449     if (strcmp(arg, "never") == 0 || strcasecmp(arg, "off") == 0) {
1450         sec->deref = never;
1451     }
1452     else if (strcmp(arg, "searching") == 0) {
1453         sec->deref = searching;
1454     }
1455     else if (strcmp(arg, "finding") == 0) {
1456         sec->deref = finding;
1457     }
1458     else if (strcmp(arg, "always") == 0 || strcasecmp(arg, "on") == 0) {
1459         sec->deref = always;
1460     }
1461     else {
1462         return "Unrecognized value for AuthLDAPAliasDereference directive";
1463     }
1464     return NULL;
1465 }
1466
1467 static const char *mod_auth_ldap_add_subgroup_attribute(cmd_parms *cmd, void *config, const char *arg)
1468 {
1469     int i = 0;
1470
1471     authn_ldap_config_t *sec = config;
1472
1473     for (i = 0; sec->sgAttributes[i]; i++) {
1474         ;
1475     }
1476     if (i == GROUPATTR_MAX_ELTS)
1477         return "Too many AuthLDAPSubGroupAttribute values";
1478
1479     sec->sgAttributes[i] = apr_pstrdup(cmd->pool, arg);
1480
1481     return NULL;
1482 }
1483
1484 static const char *mod_auth_ldap_add_subgroup_class(cmd_parms *cmd, void *config, const char *arg)
1485 {
1486     struct mod_auth_ldap_groupattr_entry_t *new;
1487
1488     authn_ldap_config_t *sec = config;
1489
1490     if (sec->subgroupclasses->nelts > GROUPATTR_MAX_ELTS)
1491         return "Too many AuthLDAPSubGroupClass values";
1492
1493     new = apr_array_push(sec->subgroupclasses);
1494     new->name = apr_pstrdup(cmd->pool, arg);
1495
1496     return NULL;
1497 }
1498
1499 static const char *mod_auth_ldap_set_subgroup_maxdepth(cmd_parms *cmd,
1500                                                        void *config,
1501                                                        const char *max_depth)
1502 {
1503     authn_ldap_config_t *sec = config;
1504
1505     sec->maxNestingDepth = atol(max_depth);
1506
1507     return NULL;
1508 }
1509
1510 static const char *mod_auth_ldap_add_group_attribute(cmd_parms *cmd, void *config, const char *arg)
1511 {
1512     struct mod_auth_ldap_groupattr_entry_t *new;
1513
1514     authn_ldap_config_t *sec = config;
1515
1516     if (sec->groupattr->nelts > GROUPATTR_MAX_ELTS)
1517         return "Too many AuthLDAPGroupAttribute directives";
1518
1519     new = apr_array_push(sec->groupattr);
1520     new->name = apr_pstrdup(cmd->pool, arg);
1521
1522     return NULL;
1523 }
1524
1525 static const char *set_charset_config(cmd_parms *cmd, void *config, const char *arg)
1526 {
1527     ap_set_module_config(cmd->server->module_config, &authnz_ldap_module,
1528                          (void *)arg);
1529     return NULL;
1530 }
1531
1532 static const char *set_bind_pattern(cmd_parms *cmd, void *_cfg, const char *exp, const char *subst)
1533 {
1534     authn_ldap_config_t *sec = _cfg;
1535     ap_regex_t *regexp;
1536
1537     regexp = ap_pregcomp(cmd->pool, exp, AP_REG_EXTENDED);
1538
1539     if (!regexp) {
1540         return apr_pstrcat(cmd->pool, "AuthLDAPInitialBindPattern: cannot compile regular "
1541                                       "expression '", exp, "'", NULL);
1542     }
1543
1544     sec->bind_regex = regexp;
1545     sec->bind_subst = apr_pstrdup(cmd->pool, subst);
1546
1547     return NULL;
1548 }
1549
1550 static const command_rec authnz_ldap_cmds[] =
1551 {
1552     AP_INIT_TAKE12("AuthLDAPURL", mod_auth_ldap_parse_url, NULL, OR_AUTHCFG,
1553                   "URL to define LDAP connection. This should be an RFC 2255 compliant\n"
1554                   "URL of the form ldap://host[:port]/basedn[?attrib[?scope[?filter]]].\n"
1555                   "<ul>\n"
1556                   "<li>Host is the name of the LDAP server. Use a space separated list of hosts \n"
1557                   "to specify redundant servers.\n"
1558                   "<li>Port is optional, and specifies the port to connect to.\n"
1559                   "<li>basedn specifies the base DN to start searches from\n"
1560                   "<li>Attrib specifies what attribute to search for in the directory. If not "
1561                   "provided, it defaults to <b>uid</b>.\n"
1562                   "<li>Scope is the scope of the search, and can be either <b>sub</b> or "
1563                   "<b>one</b>. If not provided, the default is <b>sub</b>.\n"
1564                   "<li>Filter is a filter to use in the search. If not provided, "
1565                   "defaults to <b>(objectClass=*)</b>.\n"
1566                   "</ul>\n"
1567                   "Searches are performed using the attribute and the filter combined. "
1568                   "For example, assume that the\n"
1569                   "LDAP URL is <b>ldap://ldap.airius.com/ou=People, o=Airius?uid?sub?(posixid=*)</b>. "
1570                   "Searches will\n"
1571                   "be done using the filter <b>(&((posixid=*))(uid=<i>username</i>))</b>, "
1572                   "where <i>username</i>\n"
1573                   "is the user name passed by the HTTP client. The search will be a subtree "
1574                   "search on the branch <b>ou=People, o=Airius</b>."),
1575
1576     AP_INIT_TAKE1("AuthLDAPBindDN", ap_set_string_slot,
1577                   (void *)APR_OFFSETOF(authn_ldap_config_t, binddn), OR_AUTHCFG,
1578                   "DN to use to bind to LDAP server. If not provided, will do an anonymous bind."),
1579
1580     AP_INIT_TAKE1("AuthLDAPBindPassword", ap_set_string_slot,
1581                   (void *)APR_OFFSETOF(authn_ldap_config_t, bindpw), OR_AUTHCFG,
1582                   "Password to use to bind to LDAP server. If not provided, will do an anonymous bind."),
1583
1584     AP_INIT_FLAG("AuthLDAPBindAuthoritative", ap_set_flag_slot,
1585                   (void *)APR_OFFSETOF(authn_ldap_config_t, bind_authoritative), OR_AUTHCFG,
1586                   "Set to 'on' to return failures when user-specific bind fails - defaults to on."),
1587
1588     AP_INIT_FLAG("AuthLDAPRemoteUserIsDN", ap_set_flag_slot,
1589                  (void *)APR_OFFSETOF(authn_ldap_config_t, user_is_dn), OR_AUTHCFG,
1590                  "Set to 'on' to set the REMOTE_USER environment variable to be the full "
1591                  "DN of the remote user. By default, this is set to off, meaning that "
1592                  "the REMOTE_USER variable will contain whatever value the remote user sent."),
1593
1594     AP_INIT_TAKE1("AuthLDAPRemoteUserAttribute", ap_set_string_slot,
1595                  (void *)APR_OFFSETOF(authn_ldap_config_t, remote_user_attribute), OR_AUTHCFG,
1596                  "Override the user supplied username and place the "
1597                  "contents of this attribute in the REMOTE_USER "
1598                  "environment variable."),
1599
1600     AP_INIT_FLAG("AuthLDAPCompareDNOnServer", ap_set_flag_slot,
1601                  (void *)APR_OFFSETOF(authn_ldap_config_t, compare_dn_on_server), OR_AUTHCFG,
1602                  "Set to 'on' to force auth_ldap to do DN compares (for the \"require dn\" "
1603                  "directive) using the server, and set it 'off' to do the compares locally "
1604                  "(at the expense of possible false matches). See the documentation for "
1605                  "a complete description of this option."),
1606
1607     AP_INIT_ITERATE("AuthLDAPSubGroupAttribute", mod_auth_ldap_add_subgroup_attribute, NULL, OR_AUTHCFG,
1608                     "Attribute labels used to define sub-group (or nested group) membership in groups - "
1609                     "defaults to member and uniqueMember"),
1610
1611     AP_INIT_ITERATE("AuthLDAPSubGroupClass", mod_auth_ldap_add_subgroup_class, NULL, OR_AUTHCFG,
1612                      "LDAP objectClass values used to identify sub-group instances - "
1613                      "defaults to groupOfNames and groupOfUniqueNames"),
1614
1615     AP_INIT_TAKE1("AuthLDAPMaxSubGroupDepth", mod_auth_ldap_set_subgroup_maxdepth, NULL, OR_AUTHCFG,
1616                       "Maximum subgroup nesting depth to be evaluated - defaults to 10 (top-level group = 0)"),
1617
1618     AP_INIT_ITERATE("AuthLDAPGroupAttribute", mod_auth_ldap_add_group_attribute, NULL, OR_AUTHCFG,
1619                     "A list of attribute labels used to identify the user members of groups - defaults to "
1620                     "member and uniquemember"),
1621
1622     AP_INIT_FLAG("AuthLDAPGroupAttributeIsDN", ap_set_flag_slot,
1623                  (void *)APR_OFFSETOF(authn_ldap_config_t, group_attrib_is_dn), OR_AUTHCFG,
1624                  "If set to 'on', auth_ldap uses the DN that is retrieved from the server for"
1625                  "subsequent group comparisons. If set to 'off', auth_ldap uses the string"
1626                  "provided by the client directly. Defaults to 'on'."),
1627
1628     AP_INIT_TAKE1("AuthLDAPDereferenceAliases", mod_auth_ldap_set_deref, NULL, OR_AUTHCFG,
1629                   "Determines how aliases are handled during a search. Can be one of the"
1630                   "values \"never\", \"searching\", \"finding\", or \"always\". "
1631                   "Defaults to always."),
1632
1633     AP_INIT_TAKE1("AuthLDAPCharsetConfig", set_charset_config, NULL, RSRC_CONF,
1634                   "Character set conversion configuration file. If omitted, character set"
1635                   "conversion is disabled."),
1636
1637     AP_INIT_TAKE1("AuthLDAPAuthorizePrefix", ap_set_string_slot,
1638                   (void *)APR_OFFSETOF(authn_ldap_config_t, authz_prefix), OR_AUTHCFG,
1639                   "The prefix to add to environment variables set during "
1640                   "successful authorization, default '" AUTHZ_PREFIX "'"),
1641
1642     AP_INIT_FLAG("AuthLDAPInitialBindAsUser", ap_set_flag_slot,
1643                  (void *)APR_OFFSETOF(authn_ldap_config_t, initial_bind_as_user), OR_AUTHCFG,
1644                  "Set to 'on' to perform the initial DN lookup with the basic auth credentials "
1645                  "instead of anonymous or hard-coded credentials"),
1646
1647      AP_INIT_TAKE2("AuthLDAPInitialBindPattern", set_bind_pattern, NULL, OR_AUTHCFG,
1648                    "The regex and substitution to determine a username that can bind based on an HTTP basic auth username"),
1649
1650      AP_INIT_FLAG("AuthLDAPSearchAsUser", ap_set_flag_slot,
1651                   (void *)APR_OFFSETOF(authn_ldap_config_t, search_as_user), OR_AUTHCFG,
1652                    "Set to 'on' to perform authorization-based searches with the users credentials, when this module"
1653                    " has also performed authentication.  Does not affect nested groups lookup."),
1654      AP_INIT_FLAG("AuthLDAPCompareAsUser", ap_set_flag_slot,
1655                   (void *)APR_OFFSETOF(authn_ldap_config_t, compare_as_user), OR_AUTHCFG,
1656                   "Set to 'on' to perform authorization-based compares with the users credentials, when this module"
1657                   " has also performed authentication.  Does not affect nested groups lookups."),
1658     {NULL}
1659 };
1660
1661 static int authnz_ldap_post_config(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
1662 {
1663     ap_configfile_t *f;
1664     char l[MAX_STRING_LEN];
1665     const char *charset_confname = ap_get_module_config(s->module_config,
1666                                                       &authnz_ldap_module);
1667     apr_status_t status;
1668
1669     /*
1670     authn_ldap_config_t *sec = (authn_ldap_config_t *)
1671                                     ap_get_module_config(s->module_config,
1672                                                          &authnz_ldap_module);
1673
1674     if (sec->secure)
1675     {
1676         if (!util_ldap_ssl_supported(s))
1677         {
1678             ap_log_error(APLOG_MARK, APLOG_CRIT, 0, s,
1679                      "LDAP: SSL connections (ldaps://) not supported by utilLDAP");
1680             return(!OK);
1681         }
1682     }
1683     */
1684
1685     /* make sure that mod_ldap (util_ldap) is loaded */
1686     if (ap_find_linked_module("util_ldap.c") == NULL) {
1687         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
1688                      "Module mod_ldap missing. Mod_ldap (aka. util_ldap) "
1689                      "must be loaded in order for mod_authnz_ldap to function properly");
1690         return HTTP_INTERNAL_SERVER_ERROR;
1691
1692     }
1693
1694     if (!charset_confname) {
1695         return OK;
1696     }
1697
1698     charset_confname = ap_server_root_relative(p, charset_confname);
1699     if (!charset_confname) {
1700         ap_log_error(APLOG_MARK, APLOG_ERR, APR_EBADPATH, s,
1701                      "Invalid charset conversion config path %s",
1702                      (const char *)ap_get_module_config(s->module_config,
1703                                                         &authnz_ldap_module));
1704         return HTTP_INTERNAL_SERVER_ERROR;
1705     }
1706     if ((status = ap_pcfg_openfile(&f, ptemp, charset_confname))
1707                 != APR_SUCCESS) {
1708         ap_log_error(APLOG_MARK, APLOG_ERR, status, s,
1709                      "could not open charset conversion config file %s.",
1710                      charset_confname);
1711         return HTTP_INTERNAL_SERVER_ERROR;
1712     }
1713
1714     charset_conversions = apr_hash_make(p);
1715
1716     while (!(ap_cfg_getline(l, MAX_STRING_LEN, f))) {
1717         const char *ll = l;
1718         char *lang;
1719
1720         if (l[0] == '#') {
1721             continue;
1722         }
1723         lang = ap_getword_conf(p, &ll);
1724         ap_str_tolower(lang);
1725
1726         if (ll[0]) {
1727             char *charset = ap_getword_conf(p, &ll);
1728             apr_hash_set(charset_conversions, lang, APR_HASH_KEY_STRING, charset);
1729         }
1730     }
1731     ap_cfg_closefile(f);
1732
1733     to_charset = derive_codepage_from_lang (p, "utf-8");
1734     if (to_charset == NULL) {
1735         ap_log_error(APLOG_MARK, APLOG_ERR, status, s,
1736                      "could not find the UTF-8 charset in the file %s.",
1737                      charset_confname);
1738         return HTTP_INTERNAL_SERVER_ERROR;
1739     }
1740
1741     return OK;
1742 }
1743
1744 static const authn_provider authn_ldap_provider =
1745 {
1746     &authn_ldap_check_password,
1747 };
1748
1749 static const authz_provider authz_ldapuser_provider =
1750 {
1751     &ldapuser_check_authorization,
1752 };
1753 static const authz_provider authz_ldapgroup_provider =
1754 {
1755     &ldapgroup_check_authorization,
1756 };
1757
1758 static const authz_provider authz_ldapdn_provider =
1759 {
1760     &ldapdn_check_authorization,
1761 };
1762
1763 static const authz_provider authz_ldapattribute_provider =
1764 {
1765     &ldapattribute_check_authorization,
1766 };
1767
1768 static const authz_provider authz_ldapfilter_provider =
1769 {
1770     &ldapfilter_check_authorization,
1771 };
1772
1773 static void ImportULDAPOptFn(void)
1774 {
1775     util_ldap_connection_close  = APR_RETRIEVE_OPTIONAL_FN(uldap_connection_close);
1776     util_ldap_connection_find   = APR_RETRIEVE_OPTIONAL_FN(uldap_connection_find);
1777     util_ldap_cache_comparedn   = APR_RETRIEVE_OPTIONAL_FN(uldap_cache_comparedn);
1778     util_ldap_cache_compare     = APR_RETRIEVE_OPTIONAL_FN(uldap_cache_compare);
1779     util_ldap_cache_checkuserid = APR_RETRIEVE_OPTIONAL_FN(uldap_cache_checkuserid);
1780     util_ldap_cache_getuserdn   = APR_RETRIEVE_OPTIONAL_FN(uldap_cache_getuserdn);
1781     util_ldap_ssl_supported     = APR_RETRIEVE_OPTIONAL_FN(uldap_ssl_supported);
1782     util_ldap_cache_check_subgroups = APR_RETRIEVE_OPTIONAL_FN(uldap_cache_check_subgroups);
1783 }
1784
1785 static void register_hooks(apr_pool_t *p)
1786 {
1787     /* Register authn provider */
1788     ap_register_auth_provider(p, AUTHN_PROVIDER_GROUP, "ldap",
1789                               AUTHN_PROVIDER_VERSION,
1790                               &authn_ldap_provider, AP_AUTH_INTERNAL_PER_CONF);
1791
1792     /* Register authz providers */
1793     ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "ldap-user",
1794                               AUTHZ_PROVIDER_VERSION,
1795                               &authz_ldapuser_provider,
1796                               AP_AUTH_INTERNAL_PER_CONF);
1797     ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "ldap-group",
1798                               AUTHZ_PROVIDER_VERSION,
1799                               &authz_ldapgroup_provider,
1800                               AP_AUTH_INTERNAL_PER_CONF);
1801     ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "ldap-dn",
1802                               AUTHZ_PROVIDER_VERSION,
1803                               &authz_ldapdn_provider,
1804                               AP_AUTH_INTERNAL_PER_CONF);
1805     ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "ldap-attribute",
1806                               AUTHZ_PROVIDER_VERSION,
1807                               &authz_ldapattribute_provider,
1808                               AP_AUTH_INTERNAL_PER_CONF);
1809     ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "ldap-filter",
1810                               AUTHZ_PROVIDER_VERSION,
1811                               &authz_ldapfilter_provider,
1812                               AP_AUTH_INTERNAL_PER_CONF);
1813
1814     ap_hook_post_config(authnz_ldap_post_config,NULL,NULL,APR_HOOK_MIDDLE);
1815
1816     ap_hook_optional_fn_retrieve(ImportULDAPOptFn,NULL,NULL,APR_HOOK_MIDDLE);
1817 }
1818
1819 module AP_MODULE_DECLARE_DATA authnz_ldap_module =
1820 {
1821     STANDARD20_MODULE_STUFF,
1822     create_authnz_ldap_dir_config,   /* dir config creater */
1823     NULL,                            /* dir merger --- default is to override */
1824     NULL,                            /* server config */
1825     NULL,                            /* merge server config */
1826     authnz_ldap_cmds,                /* command apr_table_t */
1827     register_hooks                   /* register hooks */
1828 };