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