]> granicus.if.org Git - apache/blob - modules/aaa/mod_authnz_ldap.c
2a6826f10df2a14fb97c864afdff6047fc65d282
[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_COMPARE_FALSE: {
902                 /* nested groups need searches and compares, so grab a new handle */
903                 authnz_ldap_cleanup_connection_close(ldc);
904                 apr_pool_cleanup_kill(r->pool, ldc,authnz_ldap_cleanup_connection_close);
905
906                 ldc = get_connection_for_authz(r, LDAP_COMPARE_AND_SEARCH);
907                 apr_pool_cleanup_register(r->pool, ldc,
908                                           authnz_ldap_cleanup_connection_close,
909                                           apr_pool_cleanup_null);
910
911                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
912                                "[%" APR_PID_T_FMT "] auth_ldap authorise: require group \"%s\": "
913                                "failed [%s][%d - %s], checking sub-groups",
914                                getpid(), t, ldc->reason, result, ldap_err2string(result));
915
916                 result = util_ldap_cache_check_subgroups(r, ldc, sec->url, t, ent[i].name,
917                                                          sec->group_attrib_is_dn ? req->dn : req->user,
918                                                          sec->sgAttributes[0] ? sec->sgAttributes : default_attributes,
919                                                          sec->subgroupclasses,
920                                                          0, sec->maxNestingDepth);
921                 if(result == LDAP_COMPARE_TRUE) {
922                     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
923                                    "[%" APR_PID_T_FMT "] auth_ldap authorise: require group (sub-group): "
924                                    "authorisation successful (attribute %s) [%s][%d - %s]",
925                                    getpid(), ent[i].name, ldc->reason, result, ldap_err2string(result));
926                     set_request_vars(r, LDAP_AUTHZ);
927                     return AUTHZ_GRANTED;
928                 }
929                 else {
930                     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
931                                    "[%" APR_PID_T_FMT "] auth_ldap authorise: require group (sub-group) \"%s\": "
932                                    "authorisation failed [%s][%d - %s]",
933                                    getpid(), t, ldc->reason, result, ldap_err2string(result));
934                 }
935                 break;
936             }
937             default: {
938                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
939                               "[%" APR_PID_T_FMT "] auth_ldap authorize: require group \"%s\": "
940                               "authorization failed [%s][%d - %s]",
941                               getpid(), t, ldc->reason, result, ldap_err2string(result));
942             }
943         }
944     }
945
946     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
947                   "[%" APR_PID_T_FMT "] auth_ldap authorize group: authorization denied for user %s to %s",
948                   getpid(), r->user, r->uri);
949
950     return AUTHZ_DENIED;
951 }
952
953 static authz_status ldapdn_check_authorization(request_rec *r,
954                                              const char *require_args)
955 {
956     int result = 0;
957     authn_ldap_request_t *req =
958         (authn_ldap_request_t *)ap_get_module_config(r->request_config, &authnz_ldap_module);
959     authn_ldap_config_t *sec =
960         (authn_ldap_config_t *)ap_get_module_config(r->per_dir_config, &authnz_ldap_module);
961
962     util_ldap_connection_t *ldc = NULL;
963
964     const char *t;
965
966     char filtbuf[FILTER_LENGTH];
967     const char *dn = NULL;
968
969     if (!sec->have_ldap_url) {
970         return AUTHZ_DENIED;
971     }
972
973     if (sec->host) {
974         ldc = get_connection_for_authz(r, LDAP_SEARCH); /* _comparedn is a searche */
975         apr_pool_cleanup_register(r->pool, ldc,
976                                   authnz_ldap_cleanup_connection_close,
977                                   apr_pool_cleanup_null);
978     }
979     else {
980         ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
981                       "[%" APR_PID_T_FMT "] auth_ldap authorize: no sec->host - weird...?", getpid());
982         return AUTHZ_DENIED;
983     }
984
985     /*
986      * If we have been authenticated by some other module than mod_auth_ldap,
987      * the req structure needed for authorization needs to be created
988      * and populated with the userid and DN of the account in LDAP
989      */
990
991     /* Check that we have a userid to start with */
992     if (!r->user) {
993         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
994             "access to %s failed, reason: no authenticated user", r->uri);
995         return AUTHZ_DENIED;
996     }
997
998     if (!strlen(r->user)) {
999         ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
1000             "ldap authorize: Userid is blank, AuthType=%s",
1001             r->ap_auth_type);
1002     }
1003
1004     if(!req) {
1005         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1006             "ldap authorize: Creating LDAP req structure");
1007
1008         /* Build the username filter */
1009         authn_ldap_build_filter(filtbuf, r, r->user, NULL, sec);
1010
1011         /* Search for the user DN */
1012         result = util_ldap_cache_getuserdn(r, ldc, sec->url, sec->basedn,
1013              sec->scope, sec->attributes, filtbuf, &dn, &(req->vals));
1014
1015         /* Search failed, log error and return failure */
1016         if(result != LDAP_SUCCESS) {
1017             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1018                 "auth_ldap authorise: User DN not found, %s", ldc->reason);
1019             return AUTHZ_DENIED;
1020         }
1021
1022         req = (authn_ldap_request_t *)apr_pcalloc(r->pool,
1023             sizeof(authn_ldap_request_t));
1024         ap_set_module_config(r->request_config, &authnz_ldap_module, req);
1025         req->dn = apr_pstrdup(r->pool, dn);
1026         req->user = r->user;
1027     }
1028
1029     t = require_args;
1030
1031     if (req->dn == NULL || strlen(req->dn) == 0) {
1032         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1033                       "[%" APR_PID_T_FMT "] auth_ldap authorize: "
1034                       "require dn: user's DN has not been defined; failing authorization",
1035                       getpid());
1036         return AUTHZ_DENIED;
1037     }
1038
1039     result = util_ldap_cache_comparedn(r, ldc, sec->url, req->dn, t, sec->compare_dn_on_server);
1040     switch(result) {
1041         case LDAP_COMPARE_TRUE: {
1042             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1043                           "[%" APR_PID_T_FMT "] auth_ldap authorize: "
1044                           "require dn: authorization successful", getpid());
1045             set_request_vars(r, LDAP_AUTHZ);
1046             return AUTHZ_GRANTED;
1047         }
1048         default: {
1049             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1050                           "[%" APR_PID_T_FMT "] auth_ldap authorize: "
1051                           "require dn \"%s\": LDAP error [%s][%s]",
1052                           getpid(), t, ldc->reason, ldap_err2string(result));
1053         }
1054     }
1055
1056
1057     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1058                   "[%" APR_PID_T_FMT "] auth_ldap authorize dn: authorization denied for user %s to %s",
1059                   getpid(), r->user, r->uri);
1060
1061     return AUTHZ_DENIED;
1062 }
1063
1064 static authz_status ldapattribute_check_authorization(request_rec *r,
1065                                              const char *require_args)
1066 {
1067     int result = 0;
1068     authn_ldap_request_t *req =
1069         (authn_ldap_request_t *)ap_get_module_config(r->request_config, &authnz_ldap_module);
1070     authn_ldap_config_t *sec =
1071         (authn_ldap_config_t *)ap_get_module_config(r->per_dir_config, &authnz_ldap_module);
1072
1073     util_ldap_connection_t *ldc = NULL;
1074
1075     const char *t;
1076     char *w, *value;
1077
1078     char filtbuf[FILTER_LENGTH];
1079     const char *dn = NULL;
1080
1081     if (!sec->have_ldap_url) {
1082         return AUTHZ_DENIED;
1083     }
1084
1085     if (sec->host) {
1086         ldc = get_connection_for_authz(r, LDAP_COMPARE);
1087         apr_pool_cleanup_register(r->pool, ldc,
1088                                   authnz_ldap_cleanup_connection_close,
1089                                   apr_pool_cleanup_null);
1090     }
1091     else {
1092         ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
1093                       "[%" APR_PID_T_FMT "] auth_ldap authorize: no sec->host - weird...?", getpid());
1094         return AUTHZ_DENIED;
1095     }
1096
1097     /*
1098      * If we have been authenticated by some other module than mod_auth_ldap,
1099      * the req structure needed for authorization needs to be created
1100      * and populated with the userid and DN of the account in LDAP
1101      */
1102
1103     /* Check that we have a userid to start with */
1104     if (!r->user) {
1105         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1106             "access to %s failed, reason: no authenticated user", r->uri);
1107         return AUTHZ_DENIED;
1108     }
1109
1110     if (!strlen(r->user)) {
1111         ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
1112             "ldap authorize: Userid is blank, AuthType=%s",
1113             r->ap_auth_type);
1114     }
1115
1116     if(!req) {
1117         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1118             "ldap authorize: Creating LDAP req structure");
1119
1120         /* Build the username filter */
1121         authn_ldap_build_filter(filtbuf, r, r->user, NULL, sec);
1122
1123         /* Search for the user DN */
1124         result = util_ldap_cache_getuserdn(r, ldc, sec->url, sec->basedn,
1125              sec->scope, sec->attributes, filtbuf, &dn, &(req->vals));
1126
1127         /* Search failed, log error and return failure */
1128         if(result != LDAP_SUCCESS) {
1129             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1130                 "auth_ldap authorise: User DN not found, %s", ldc->reason);
1131             return AUTHZ_DENIED;
1132         }
1133
1134         req = (authn_ldap_request_t *)apr_pcalloc(r->pool,
1135             sizeof(authn_ldap_request_t));
1136         ap_set_module_config(r->request_config, &authnz_ldap_module, req);
1137         req->dn = apr_pstrdup(r->pool, dn);
1138         req->user = r->user;
1139     }
1140
1141     if (req->dn == NULL || strlen(req->dn) == 0) {
1142         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1143                       "[%" APR_PID_T_FMT "] auth_ldap authorize: "
1144                       "require ldap-attribute: user's DN has not been defined; failing authorization",
1145                       getpid());
1146         return AUTHZ_DENIED;
1147     }
1148
1149     t = require_args;
1150     while (t[0]) {
1151         w = ap_getword(r->pool, &t, '=');
1152         value = ap_getword_conf(r->pool, &t);
1153
1154         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1155                       "[%" APR_PID_T_FMT "] auth_ldap authorize: checking attribute"
1156                       " %s has value %s", getpid(), w, value);
1157         result = util_ldap_cache_compare(r, ldc, sec->url, req->dn, w, value);
1158         switch(result) {
1159             case LDAP_COMPARE_TRUE: {
1160                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG,
1161                               0, r, "[%" APR_PID_T_FMT "] auth_ldap authorize: "
1162                               "require attribute: authorization successful", 
1163                               getpid());
1164                 set_request_vars(r, LDAP_AUTHZ);
1165                 return AUTHZ_GRANTED;
1166             }
1167             default: {
1168                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG,
1169                               0, r, "[%" APR_PID_T_FMT "] auth_ldap authorize: "
1170                               "require attribute: authorization failed [%s][%s]", 
1171                               getpid(), ldc->reason, ldap_err2string(result));
1172             }
1173         }
1174     }
1175
1176     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1177                   "[%" APR_PID_T_FMT "] auth_ldap authorize attribute: authorization denied for user %s to %s",
1178                   getpid(), r->user, r->uri);
1179
1180     return AUTHZ_DENIED;
1181 }
1182
1183 static authz_status ldapfilter_check_authorization(request_rec *r,
1184                                              const char *require_args)
1185 {
1186     int result = 0;
1187     authn_ldap_request_t *req =
1188         (authn_ldap_request_t *)ap_get_module_config(r->request_config, &authnz_ldap_module);
1189     authn_ldap_config_t *sec =
1190         (authn_ldap_config_t *)ap_get_module_config(r->per_dir_config, &authnz_ldap_module);
1191
1192     util_ldap_connection_t *ldc = NULL;
1193     const char *t;
1194
1195     char filtbuf[FILTER_LENGTH];
1196     const char *dn = NULL;
1197
1198     if (!sec->have_ldap_url) {
1199         return AUTHZ_DENIED;
1200     }
1201
1202     if (sec->host) {
1203         ldc = get_connection_for_authz(r, LDAP_SEARCH);
1204         apr_pool_cleanup_register(r->pool, ldc,
1205                                   authnz_ldap_cleanup_connection_close,
1206                                   apr_pool_cleanup_null);
1207     }
1208     else {
1209         ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
1210                       "[%" APR_PID_T_FMT "] auth_ldap authorize: no sec->host - weird...?", getpid());
1211         return AUTHZ_DENIED;
1212     }
1213
1214     /*
1215      * If we have been authenticated by some other module than mod_auth_ldap,
1216      * the req structure needed for authorization needs to be created
1217      * and populated with the userid and DN of the account in LDAP
1218      */
1219
1220     /* Check that we have a userid to start with */
1221     if (!r->user) {
1222         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1223             "access to %s failed, reason: no authenticated user", r->uri);
1224         return AUTHZ_DENIED;
1225     }
1226
1227     if (!strlen(r->user)) {
1228         ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
1229             "ldap authorize: Userid is blank, AuthType=%s",
1230             r->ap_auth_type);
1231     }
1232
1233     if(!req) {
1234         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1235             "ldap authorize: Creating LDAP req structure");
1236
1237         /* Build the username filter */
1238         authn_ldap_build_filter(filtbuf, r, r->user, NULL, sec);
1239
1240         /* Search for the user DN */
1241         result = util_ldap_cache_getuserdn(r, ldc, sec->url, sec->basedn,
1242              sec->scope, sec->attributes, filtbuf, &dn, &(req->vals));
1243
1244         /* Search failed, log error and return failure */
1245         if(result != LDAP_SUCCESS) {
1246             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1247                 "auth_ldap authorise: User DN not found, %s", ldc->reason);
1248             return AUTHZ_DENIED;
1249         }
1250
1251         req = (authn_ldap_request_t *)apr_pcalloc(r->pool,
1252             sizeof(authn_ldap_request_t));
1253         ap_set_module_config(r->request_config, &authnz_ldap_module, req);
1254         req->dn = apr_pstrdup(r->pool, dn);
1255         req->user = r->user;
1256     }
1257
1258     if (req->dn == NULL || strlen(req->dn) == 0) {
1259         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1260                       "[%" APR_PID_T_FMT "] auth_ldap authorize: "
1261                       "require ldap-filter: user's DN has not been defined; failing authorization",
1262                       getpid());
1263         return AUTHZ_DENIED;
1264     }
1265
1266     t = require_args;
1267
1268     if (t[0]) {
1269         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1270                       "[%" APR_PID_T_FMT "] auth_ldap authorize: checking filter %s",
1271                       getpid(), t);
1272
1273         /* Build the username filter */
1274         authn_ldap_build_filter(filtbuf, r, req->user, t, sec);
1275
1276         /* Search for the user DN */
1277         result = util_ldap_cache_getuserdn(r, ldc, sec->url, sec->basedn,
1278              sec->scope, sec->attributes, filtbuf, &dn, &(req->vals));
1279
1280         /* Make sure that the filtered search returned the correct user dn */
1281         if (result == LDAP_SUCCESS) {
1282             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1283                           "[%" APR_PID_T_FMT "] auth_ldap authorize: checking dn match %s",
1284                           getpid(), dn);
1285             if (sec->compare_as_user) {
1286                 /* ldap-filter is the only authz that requires a search and a compare */
1287                 apr_pool_cleanup_kill(r->pool, ldc, authnz_ldap_cleanup_connection_close);
1288                 authnz_ldap_cleanup_connection_close(ldc);
1289                 ldc = get_connection_for_authz(r, LDAP_COMPARE);
1290             }
1291             result = util_ldap_cache_comparedn(r, ldc, sec->url, req->dn, dn,
1292                                                sec->compare_dn_on_server);
1293         }
1294
1295         switch(result) {
1296             case LDAP_COMPARE_TRUE: {
1297                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG,
1298                               0, r, "[%" APR_PID_T_FMT "] auth_ldap authorize: "
1299                               "require ldap-filter: authorization "
1300                               "successful", getpid());
1301                 set_request_vars(r, LDAP_AUTHZ);
1302                 return AUTHZ_GRANTED;
1303             }
1304             case LDAP_FILTER_ERROR: {
1305                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG,
1306                               0, r, "[%" APR_PID_T_FMT "] auth_ldap authorize: "
1307                               "require ldap-filter: %s authorization "
1308                               "failed [%s][%s]", getpid(),
1309                               filtbuf, ldc->reason, ldap_err2string(result));
1310                 break;
1311             }
1312             default: {
1313                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG,
1314                               0, r, "[%" APR_PID_T_FMT "] auth_ldap authorize: "
1315                               "require ldap-filter: authorization "
1316                               "failed [%s][%s]", getpid(),
1317                               ldc->reason, ldap_err2string(result));
1318             }
1319         }
1320     }
1321
1322     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1323                   "[%" APR_PID_T_FMT "] auth_ldap authorize filter: authorization denied for user %s to %s",
1324                   getpid(), r->user, r->uri);
1325
1326     return AUTHZ_DENIED;
1327 }
1328
1329
1330 /*
1331  * Use the ldap url parsing routines to break up the ldap url into
1332  * host and port.
1333  */
1334 static const char *mod_auth_ldap_parse_url(cmd_parms *cmd,
1335                                     void *config,
1336                                     const char *url,
1337                                     const char *mode)
1338 {
1339     int rc;
1340     apr_ldap_url_desc_t *urld;
1341     apr_ldap_err_t *result;
1342
1343     authn_ldap_config_t *sec = config;
1344
1345     rc = apr_ldap_url_parse(cmd->pool, url, &(urld), &(result));
1346     if (rc != APR_SUCCESS) {
1347         return result->reason;
1348     }
1349     sec->url = apr_pstrdup(cmd->pool, url);
1350
1351     /* Set all the values, or at least some sane defaults */
1352     if (sec->host) {
1353         sec->host = apr_pstrcat(cmd->pool, urld->lud_host, " ", sec->host, NULL);
1354     }
1355     else {
1356         sec->host = urld->lud_host? apr_pstrdup(cmd->pool, urld->lud_host) : "localhost";
1357     }
1358     sec->basedn = urld->lud_dn? apr_pstrdup(cmd->pool, urld->lud_dn) : "";
1359     if (urld->lud_attrs && urld->lud_attrs[0]) {
1360         int i = 1;
1361         while (urld->lud_attrs[i]) {
1362             i++;
1363         }
1364         sec->attributes = apr_pcalloc(cmd->pool, sizeof(char *) * (i+1));
1365         i = 0;
1366         while (urld->lud_attrs[i]) {
1367             sec->attributes[i] = apr_pstrdup(cmd->pool, urld->lud_attrs[i]);
1368             i++;
1369         }
1370         sec->attribute = sec->attributes[0];
1371     }
1372     else {
1373         sec->attribute = "uid";
1374     }
1375
1376     sec->scope = urld->lud_scope == LDAP_SCOPE_ONELEVEL ?
1377         LDAP_SCOPE_ONELEVEL : LDAP_SCOPE_SUBTREE;
1378
1379     if (urld->lud_filter) {
1380         if (urld->lud_filter[0] == '(') {
1381             /*
1382              * Get rid of the surrounding parens; later on when generating the
1383              * filter, they'll be put back.
1384              */
1385             sec->filter = apr_pstrdup(cmd->pool, urld->lud_filter+1);
1386             sec->filter[strlen(sec->filter)-1] = '\0';
1387         }
1388         else {
1389             sec->filter = apr_pstrdup(cmd->pool, urld->lud_filter);
1390         }
1391     }
1392     else {
1393         sec->filter = "objectclass=*";
1394     }
1395
1396     if (mode) {
1397         if (0 == strcasecmp("NONE", mode)) {
1398             sec->secure = APR_LDAP_NONE;
1399         }
1400         else if (0 == strcasecmp("SSL", mode)) {
1401             sec->secure = APR_LDAP_SSL;
1402         }
1403         else if (0 == strcasecmp("TLS", mode) || 0 == strcasecmp("STARTTLS", mode)) {
1404             sec->secure = APR_LDAP_STARTTLS;
1405         }
1406         else {
1407             return "Invalid LDAP connection mode setting: must be one of NONE, "
1408                    "SSL, or TLS/STARTTLS";
1409         }
1410     }
1411
1412       /* "ldaps" indicates secure ldap connections desired
1413       */
1414     if (strncasecmp(url, "ldaps", 5) == 0)
1415     {
1416         sec->secure = APR_LDAP_SSL;
1417         sec->port = urld->lud_port? urld->lud_port : LDAPS_PORT;
1418     }
1419     else
1420     {
1421         sec->port = urld->lud_port? urld->lud_port : LDAP_PORT;
1422     }
1423
1424     sec->have_ldap_url = 1;
1425
1426     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
1427                  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",
1428                  getpid(),
1429                  url,
1430                  urld->lud_host,
1431                  urld->lud_port,
1432                  urld->lud_dn,
1433                  urld->lud_attrs? urld->lud_attrs[0] : "(null)",
1434                  (urld->lud_scope == LDAP_SCOPE_SUBTREE? "subtree" :
1435                   urld->lud_scope == LDAP_SCOPE_BASE? "base" :
1436                   urld->lud_scope == LDAP_SCOPE_ONELEVEL? "onelevel" : "unknown"),
1437                  urld->lud_filter,
1438                  sec->secure == APR_LDAP_SSL  ? "using SSL": "not using SSL"
1439                  );
1440
1441     return NULL;
1442 }
1443
1444 static const char *mod_auth_ldap_set_deref(cmd_parms *cmd, void *config, const char *arg)
1445 {
1446     authn_ldap_config_t *sec = config;
1447
1448     if (strcmp(arg, "never") == 0 || strcasecmp(arg, "off") == 0) {
1449         sec->deref = never;
1450     }
1451     else if (strcmp(arg, "searching") == 0) {
1452         sec->deref = searching;
1453     }
1454     else if (strcmp(arg, "finding") == 0) {
1455         sec->deref = finding;
1456     }
1457     else if (strcmp(arg, "always") == 0 || strcasecmp(arg, "on") == 0) {
1458         sec->deref = always;
1459     }
1460     else {
1461         return "Unrecognized value for AuthLDAPAliasDereference directive";
1462     }
1463     return NULL;
1464 }
1465
1466 static const char *mod_auth_ldap_add_subgroup_attribute(cmd_parms *cmd, void *config, const char *arg)
1467 {
1468     int i = 0;
1469
1470     authn_ldap_config_t *sec = config;
1471
1472     for (i = 0; sec->sgAttributes[i]; i++) {
1473         ;
1474     }
1475     if (i == GROUPATTR_MAX_ELTS)
1476         return "Too many AuthLDAPSubGroupAttribute values";
1477
1478     sec->sgAttributes[i] = apr_pstrdup(cmd->pool, arg);
1479
1480     return NULL;
1481 }
1482
1483 static const char *mod_auth_ldap_add_subgroup_class(cmd_parms *cmd, void *config, const char *arg)
1484 {
1485     struct mod_auth_ldap_groupattr_entry_t *new;
1486
1487     authn_ldap_config_t *sec = config;
1488
1489     if (sec->subgroupclasses->nelts > GROUPATTR_MAX_ELTS)
1490         return "Too many AuthLDAPSubGroupClass values";
1491
1492     new = apr_array_push(sec->subgroupclasses);
1493     new->name = apr_pstrdup(cmd->pool, arg);
1494
1495     return NULL;
1496 }
1497
1498 static const char *mod_auth_ldap_set_subgroup_maxdepth(cmd_parms *cmd,
1499                                                        void *config,
1500                                                        const char *max_depth)
1501 {
1502     authn_ldap_config_t *sec = config;
1503
1504     sec->maxNestingDepth = atol(max_depth);
1505
1506     return NULL;
1507 }
1508
1509 static const char *mod_auth_ldap_add_group_attribute(cmd_parms *cmd, void *config, const char *arg)
1510 {
1511     struct mod_auth_ldap_groupattr_entry_t *new;
1512
1513     authn_ldap_config_t *sec = config;
1514
1515     if (sec->groupattr->nelts > GROUPATTR_MAX_ELTS)
1516         return "Too many AuthLDAPGroupAttribute directives";
1517
1518     new = apr_array_push(sec->groupattr);
1519     new->name = apr_pstrdup(cmd->pool, arg);
1520
1521     return NULL;
1522 }
1523
1524 static const char *set_charset_config(cmd_parms *cmd, void *config, const char *arg)
1525 {
1526     ap_set_module_config(cmd->server->module_config, &authnz_ldap_module,
1527                          (void *)arg);
1528     return NULL;
1529 }
1530
1531 static const char *set_bind_pattern(cmd_parms *cmd, void *_cfg, const char *exp, const char *subst)
1532 {
1533     authn_ldap_config_t *sec = _cfg;
1534     ap_regex_t *regexp;
1535
1536     regexp = ap_pregcomp(cmd->pool, exp, AP_REG_EXTENDED);
1537
1538     if (!regexp) {
1539         return apr_pstrcat(cmd->pool, "AuthLDAPInitialBindPattern: cannot compile regular "
1540                                       "expression '", exp, "'", NULL);
1541     }
1542
1543     sec->bind_regex = regexp;
1544     sec->bind_subst = apr_pstrdup(cmd->pool, subst);
1545
1546     return NULL;
1547 }
1548
1549 static const command_rec authnz_ldap_cmds[] =
1550 {
1551     AP_INIT_TAKE12("AuthLDAPURL", mod_auth_ldap_parse_url, NULL, OR_AUTHCFG,
1552                   "URL to define LDAP connection. This should be an RFC 2255 compliant\n"
1553                   "URL of the form ldap://host[:port]/basedn[?attrib[?scope[?filter]]].\n"
1554                   "<ul>\n"
1555                   "<li>Host is the name of the LDAP server. Use a space separated list of hosts \n"
1556                   "to specify redundant servers.\n"
1557                   "<li>Port is optional, and specifies the port to connect to.\n"
1558                   "<li>basedn specifies the base DN to start searches from\n"
1559                   "<li>Attrib specifies what attribute to search for in the directory. If not "
1560                   "provided, it defaults to <b>uid</b>.\n"
1561                   "<li>Scope is the scope of the search, and can be either <b>sub</b> or "
1562                   "<b>one</b>. If not provided, the default is <b>sub</b>.\n"
1563                   "<li>Filter is a filter to use in the search. If not provided, "
1564                   "defaults to <b>(objectClass=*)</b>.\n"
1565                   "</ul>\n"
1566                   "Searches are performed using the attribute and the filter combined. "
1567                   "For example, assume that the\n"
1568                   "LDAP URL is <b>ldap://ldap.airius.com/ou=People, o=Airius?uid?sub?(posixid=*)</b>. "
1569                   "Searches will\n"
1570                   "be done using the filter <b>(&((posixid=*))(uid=<i>username</i>))</b>, "
1571                   "where <i>username</i>\n"
1572                   "is the user name passed by the HTTP client. The search will be a subtree "
1573                   "search on the branch <b>ou=People, o=Airius</b>."),
1574
1575     AP_INIT_TAKE1("AuthLDAPBindDN", ap_set_string_slot,
1576                   (void *)APR_OFFSETOF(authn_ldap_config_t, binddn), OR_AUTHCFG,
1577                   "DN to use to bind to LDAP server. If not provided, will do an anonymous bind."),
1578
1579     AP_INIT_TAKE1("AuthLDAPBindPassword", ap_set_string_slot,
1580                   (void *)APR_OFFSETOF(authn_ldap_config_t, bindpw), OR_AUTHCFG,
1581                   "Password to use to bind to LDAP server. If not provided, will do an anonymous bind."),
1582
1583     AP_INIT_FLAG("AuthLDAPBindAuthoritative", ap_set_flag_slot,
1584                   (void *)APR_OFFSETOF(authn_ldap_config_t, bind_authoritative), OR_AUTHCFG,
1585                   "Set to 'on' to return failures when user-specific bind fails - defaults to on."),
1586
1587     AP_INIT_FLAG("AuthLDAPRemoteUserIsDN", ap_set_flag_slot,
1588                  (void *)APR_OFFSETOF(authn_ldap_config_t, user_is_dn), OR_AUTHCFG,
1589                  "Set to 'on' to set the REMOTE_USER environment variable to be the full "
1590                  "DN of the remote user. By default, this is set to off, meaning that "
1591                  "the REMOTE_USER variable will contain whatever value the remote user sent."),
1592
1593     AP_INIT_TAKE1("AuthLDAPRemoteUserAttribute", ap_set_string_slot,
1594                  (void *)APR_OFFSETOF(authn_ldap_config_t, remote_user_attribute), OR_AUTHCFG,
1595                  "Override the user supplied username and place the "
1596                  "contents of this attribute in the REMOTE_USER "
1597                  "environment variable."),
1598
1599     AP_INIT_FLAG("AuthLDAPCompareDNOnServer", ap_set_flag_slot,
1600                  (void *)APR_OFFSETOF(authn_ldap_config_t, compare_dn_on_server), OR_AUTHCFG,
1601                  "Set to 'on' to force auth_ldap to do DN compares (for the \"require dn\" "
1602                  "directive) using the server, and set it 'off' to do the compares locally "
1603                  "(at the expense of possible false matches). See the documentation for "
1604                  "a complete description of this option."),
1605
1606     AP_INIT_ITERATE("AuthLDAPSubGroupAttribute", mod_auth_ldap_add_subgroup_attribute, NULL, OR_AUTHCFG,
1607                     "Attribute labels used to define sub-group (or nested group) membership in groups - "
1608                     "defaults to member and uniqueMember"),
1609
1610     AP_INIT_ITERATE("AuthLDAPSubGroupClass", mod_auth_ldap_add_subgroup_class, NULL, OR_AUTHCFG,
1611                      "LDAP objectClass values used to identify sub-group instances - "
1612                      "defaults to groupOfNames and groupOfUniqueNames"),
1613
1614     AP_INIT_TAKE1("AuthLDAPMaxSubGroupDepth", mod_auth_ldap_set_subgroup_maxdepth, NULL, OR_AUTHCFG,
1615                       "Maximum subgroup nesting depth to be evaluated - defaults to 10 (top-level group = 0)"),
1616
1617     AP_INIT_ITERATE("AuthLDAPGroupAttribute", mod_auth_ldap_add_group_attribute, NULL, OR_AUTHCFG,
1618                     "A list of attribute labels used to identify the user members of groups - defaults to "
1619                     "member and uniquemember"),
1620
1621     AP_INIT_FLAG("AuthLDAPGroupAttributeIsDN", ap_set_flag_slot,
1622                  (void *)APR_OFFSETOF(authn_ldap_config_t, group_attrib_is_dn), OR_AUTHCFG,
1623                  "If set to 'on', auth_ldap uses the DN that is retrieved from the server for"
1624                  "subsequent group comparisons. If set to 'off', auth_ldap uses the string"
1625                  "provided by the client directly. Defaults to 'on'."),
1626
1627     AP_INIT_TAKE1("AuthLDAPDereferenceAliases", mod_auth_ldap_set_deref, NULL, OR_AUTHCFG,
1628                   "Determines how aliases are handled during a search. Can be one of the"
1629                   "values \"never\", \"searching\", \"finding\", or \"always\". "
1630                   "Defaults to always."),
1631
1632     AP_INIT_TAKE1("AuthLDAPCharsetConfig", set_charset_config, NULL, RSRC_CONF,
1633                   "Character set conversion configuration file. If omitted, character set"
1634                   "conversion is disabled."),
1635
1636     AP_INIT_TAKE1("AuthLDAPAuthorizePrefix", ap_set_string_slot,
1637                   (void *)APR_OFFSETOF(authn_ldap_config_t, authz_prefix), OR_AUTHCFG,
1638                   "The prefix to add to environment variables set during "
1639                   "successful authorization, default '" AUTHZ_PREFIX "'"),
1640
1641     AP_INIT_FLAG("AuthLDAPInitialBindAsUser", ap_set_flag_slot,
1642                  (void *)APR_OFFSETOF(authn_ldap_config_t, initial_bind_as_user), OR_AUTHCFG,
1643                  "Set to 'on' to perform the initial DN lookup with the basic auth credentials "
1644                  "instead of anonymous or hard-coded credentials"),
1645
1646      AP_INIT_TAKE2("AuthLDAPInitialBindPattern", set_bind_pattern, NULL, OR_AUTHCFG,
1647                    "The regex and substitution to determine a username that can bind based on an HTTP basic auth username"),
1648
1649      AP_INIT_FLAG("AuthLDAPSearchAsUser", ap_set_flag_slot,
1650                   (void *)APR_OFFSETOF(authn_ldap_config_t, search_as_user), OR_AUTHCFG,
1651                    "Set to 'on' to perform authorization-based searches with the users credentials, when this module"
1652                    " has also performed authentication.  Does not affect nested groups lookup."),
1653      AP_INIT_FLAG("AuthLDAPCompareAsUser", ap_set_flag_slot,
1654                   (void *)APR_OFFSETOF(authn_ldap_config_t, compare_as_user), OR_AUTHCFG,
1655                   "Set to 'on' to perform authorization-based compares with the users credentials, when this module"
1656                   " has also performed authentication.  Does not affect nested groups lookups."),
1657     {NULL}
1658 };
1659
1660 static int authnz_ldap_post_config(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
1661 {
1662     ap_configfile_t *f;
1663     char l[MAX_STRING_LEN];
1664     const char *charset_confname = ap_get_module_config(s->module_config,
1665                                                       &authnz_ldap_module);
1666     apr_status_t status;
1667
1668     /*
1669     authn_ldap_config_t *sec = (authn_ldap_config_t *)
1670                                     ap_get_module_config(s->module_config,
1671                                                          &authnz_ldap_module);
1672
1673     if (sec->secure)
1674     {
1675         if (!util_ldap_ssl_supported(s))
1676         {
1677             ap_log_error(APLOG_MARK, APLOG_CRIT, 0, s,
1678                      "LDAP: SSL connections (ldaps://) not supported by utilLDAP");
1679             return(!OK);
1680         }
1681     }
1682     */
1683
1684     /* make sure that mod_ldap (util_ldap) is loaded */
1685     if (ap_find_linked_module("util_ldap.c") == NULL) {
1686         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
1687                      "Module mod_ldap missing. Mod_ldap (aka. util_ldap) "
1688                      "must be loaded in order for mod_authnz_ldap to function properly");
1689         return HTTP_INTERNAL_SERVER_ERROR;
1690
1691     }
1692
1693     if (!charset_confname) {
1694         return OK;
1695     }
1696
1697     charset_confname = ap_server_root_relative(p, charset_confname);
1698     if (!charset_confname) {
1699         ap_log_error(APLOG_MARK, APLOG_ERR, APR_EBADPATH, s,
1700                      "Invalid charset conversion config path %s",
1701                      (const char *)ap_get_module_config(s->module_config,
1702                                                         &authnz_ldap_module));
1703         return HTTP_INTERNAL_SERVER_ERROR;
1704     }
1705     if ((status = ap_pcfg_openfile(&f, ptemp, charset_confname))
1706                 != APR_SUCCESS) {
1707         ap_log_error(APLOG_MARK, APLOG_ERR, status, s,
1708                      "could not open charset conversion config file %s.",
1709                      charset_confname);
1710         return HTTP_INTERNAL_SERVER_ERROR;
1711     }
1712
1713     charset_conversions = apr_hash_make(p);
1714
1715     while (!(ap_cfg_getline(l, MAX_STRING_LEN, f))) {
1716         const char *ll = l;
1717         char *lang;
1718
1719         if (l[0] == '#') {
1720             continue;
1721         }
1722         lang = ap_getword_conf(p, &ll);
1723         ap_str_tolower(lang);
1724
1725         if (ll[0]) {
1726             char *charset = ap_getword_conf(p, &ll);
1727             apr_hash_set(charset_conversions, lang, APR_HASH_KEY_STRING, charset);
1728         }
1729     }
1730     ap_cfg_closefile(f);
1731
1732     to_charset = derive_codepage_from_lang (p, "utf-8");
1733     if (to_charset == NULL) {
1734         ap_log_error(APLOG_MARK, APLOG_ERR, status, s,
1735                      "could not find the UTF-8 charset in the file %s.",
1736                      charset_confname);
1737         return HTTP_INTERNAL_SERVER_ERROR;
1738     }
1739
1740     return OK;
1741 }
1742
1743 static const authn_provider authn_ldap_provider =
1744 {
1745     &authn_ldap_check_password,
1746 };
1747
1748 static const authz_provider authz_ldapuser_provider =
1749 {
1750     &ldapuser_check_authorization,
1751 };
1752 static const authz_provider authz_ldapgroup_provider =
1753 {
1754     &ldapgroup_check_authorization,
1755 };
1756
1757 static const authz_provider authz_ldapdn_provider =
1758 {
1759     &ldapdn_check_authorization,
1760 };
1761
1762 static const authz_provider authz_ldapattribute_provider =
1763 {
1764     &ldapattribute_check_authorization,
1765 };
1766
1767 static const authz_provider authz_ldapfilter_provider =
1768 {
1769     &ldapfilter_check_authorization,
1770 };
1771
1772 static void ImportULDAPOptFn(void)
1773 {
1774     util_ldap_connection_close  = APR_RETRIEVE_OPTIONAL_FN(uldap_connection_close);
1775     util_ldap_connection_find   = APR_RETRIEVE_OPTIONAL_FN(uldap_connection_find);
1776     util_ldap_cache_comparedn   = APR_RETRIEVE_OPTIONAL_FN(uldap_cache_comparedn);
1777     util_ldap_cache_compare     = APR_RETRIEVE_OPTIONAL_FN(uldap_cache_compare);
1778     util_ldap_cache_checkuserid = APR_RETRIEVE_OPTIONAL_FN(uldap_cache_checkuserid);
1779     util_ldap_cache_getuserdn   = APR_RETRIEVE_OPTIONAL_FN(uldap_cache_getuserdn);
1780     util_ldap_ssl_supported     = APR_RETRIEVE_OPTIONAL_FN(uldap_ssl_supported);
1781     util_ldap_cache_check_subgroups = APR_RETRIEVE_OPTIONAL_FN(uldap_cache_check_subgroups);
1782 }
1783
1784 static void register_hooks(apr_pool_t *p)
1785 {
1786     /* Register authn provider */
1787     ap_register_auth_provider(p, AUTHN_PROVIDER_GROUP, "ldap",
1788                               AUTHN_PROVIDER_VERSION,
1789                               &authn_ldap_provider, AP_AUTH_INTERNAL_PER_CONF);
1790
1791     /* Register authz providers */
1792     ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "ldap-user",
1793                               AUTHZ_PROVIDER_VERSION,
1794                               &authz_ldapuser_provider,
1795                               AP_AUTH_INTERNAL_PER_CONF);
1796     ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "ldap-group",
1797                               AUTHZ_PROVIDER_VERSION,
1798                               &authz_ldapgroup_provider,
1799                               AP_AUTH_INTERNAL_PER_CONF);
1800     ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "ldap-dn",
1801                               AUTHZ_PROVIDER_VERSION,
1802                               &authz_ldapdn_provider,
1803                               AP_AUTH_INTERNAL_PER_CONF);
1804     ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "ldap-attribute",
1805                               AUTHZ_PROVIDER_VERSION,
1806                               &authz_ldapattribute_provider,
1807                               AP_AUTH_INTERNAL_PER_CONF);
1808     ap_register_auth_provider(p, AUTHZ_PROVIDER_GROUP, "ldap-filter",
1809                               AUTHZ_PROVIDER_VERSION,
1810                               &authz_ldapfilter_provider,
1811                               AP_AUTH_INTERNAL_PER_CONF);
1812
1813     ap_hook_post_config(authnz_ldap_post_config,NULL,NULL,APR_HOOK_MIDDLE);
1814
1815     ap_hook_optional_fn_retrieve(ImportULDAPOptFn,NULL,NULL,APR_HOOK_MIDDLE);
1816 }
1817
1818 module AP_MODULE_DECLARE_DATA authnz_ldap_module =
1819 {
1820     STANDARD20_MODULE_STUFF,
1821     create_authnz_ldap_dir_config,   /* dir config creater */
1822     NULL,                            /* dir merger --- default is to override */
1823     NULL,                            /* server config */
1824     NULL,                            /* merge server config */
1825     authnz_ldap_cmds,                /* command apr_table_t */
1826     register_hooks                   /* register hooks */
1827 };