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