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