]> granicus.if.org Git - apache/blob - modules/experimental/mod_auth_ldap.c
dc5cc929b42f82ea84b96f9418d2a3046bd92b06
[apache] / modules / experimental / mod_auth_ldap.c
1 /* Copyright 2001-2004 The Apache Software Foundation
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 /*
17  * mod_auth_ldap.c: LDAP authentication module
18  * 
19  * Original code from auth_ldap module for Apache v1.3:
20  * Copyright 1998, 1999 Enbridge Pipelines Inc. 
21  * Copyright 1999-2001 Dave Carrigan
22  */
23
24 #include <apr_ldap.h>
25 #include <apr_strings.h>
26 #include <apr_xlate.h>
27 #define APR_WANT_STRFUNC
28 #include <apr_want.h>
29
30 #include "ap_config.h"
31 #if APR_HAVE_UNISTD_H
32 /* for getpid() */
33 #include <unistd.h>
34 #endif
35 #include <ctype.h>
36
37 #include "httpd.h"
38 #include "http_config.h"
39 #include "http_core.h"
40 #include "http_log.h"
41 #include "http_protocol.h"
42 #include "http_request.h"
43 #include "util_ldap.h"
44
45 #if !APR_HAS_LDAP
46 #error mod_auth_ldap requires APR-util to have LDAP support built in
47 #endif
48
49 /* per directory configuration */
50 typedef struct {
51     apr_pool_t *pool;                   /* Pool that this config is allocated from */
52 #if APR_HAS_THREADS
53     apr_thread_mutex_t *lock;           /* Lock for this config */
54 #endif
55     int auth_authoritative;             /* Is this auth method the one and only? */
56     int enabled;                        /* Is auth_ldap enabled in this directory? */
57
58     /* These parameters are all derived from the AuthLDAPURL directive */
59     char *url;                          /* String representation of the URL */
60
61     char *host;                         /* Name of the LDAP server (or space separated list) */
62     int port;                           /* Port of the LDAP server */
63     char *basedn;                       /* Base DN to do all searches from */
64     char *attribute;                    /* Attribute to search for */
65     char **attributes;                  /* Array of all the attributes to return */
66     int scope;                          /* Scope of the search */
67     char *filter;                       /* Filter to further limit the search  */
68     deref_options deref;                /* how to handle alias dereferening */
69     char *binddn;                       /* DN to bind to server (can be NULL) */
70     char *bindpw;                       /* Password to bind to server (can be NULL) */
71
72     int frontpage_hack;                 /* Hack for frontpage support */
73     int user_is_dn;                     /* If true, connection->user is DN instead of userid */
74     int compare_dn_on_server;           /* If true, will use server to do DN compare */
75
76     int have_ldap_url;                  /* Set if we have found an LDAP url */
77  
78     apr_array_header_t *groupattr;      /* List of Group attributes */
79     int group_attrib_is_dn;             /* If true, the group attribute is the DN, otherwise, 
80                                            it's the exact string passed by the HTTP client */
81
82     int secure;                     /* True if SSL connections are requested */
83 } mod_auth_ldap_config_t;
84
85 typedef struct mod_auth_ldap_request_t {
86     char *dn;                           /* The saved dn from a successful search */
87     char *user;                         /* The username provided by the client */
88 } mod_auth_ldap_request_t;
89
90 /* maximum group elements supported */
91 #define GROUPATTR_MAX_ELTS 10
92
93 struct mod_auth_ldap_groupattr_entry_t {
94     char *name;
95 };
96
97 module AP_MODULE_DECLARE_DATA auth_ldap_module;
98
99 /* function prototypes */
100 void mod_auth_ldap_build_filter(char *filtbuf, 
101                                 request_rec *r, 
102                                 mod_auth_ldap_config_t *sec);
103 int mod_auth_ldap_check_user_id(request_rec *r);
104 int mod_auth_ldap_auth_checker(request_rec *r);
105 void *mod_auth_ldap_create_dir_config(apr_pool_t *p, char *d);
106
107 /* ---------------------------------------- */
108
109 static apr_hash_t *charset_conversions = NULL;
110 static char *to_charset = NULL;           /* UTF-8 identifier derived from the charset.conv file */
111
112 /* Derive a code page ID give a language name or ID */
113 static char* derive_codepage_from_lang (apr_pool_t *p, char *language)
114 {
115     int lang_len;
116     char *charset;
117     
118     if (!language)          /* our default codepage */
119         return apr_pstrdup(p, "ISO-8859-1");
120     else
121         lang_len = strlen(language);
122     
123     charset = (char*) apr_hash_get(charset_conversions, language, APR_HASH_KEY_STRING);
124
125     if (!charset) {
126         language[2] = '\0';
127         charset = (char*) apr_hash_get(charset_conversions, language, APR_HASH_KEY_STRING);
128     }
129
130     if (charset) {
131         charset = apr_pstrdup(p, charset);
132     }
133
134     return charset;
135 }
136
137 static apr_xlate_t* get_conv_set (request_rec *r)
138 {
139     char *lang_line = (char*)apr_table_get(r->headers_in, "accept-language");
140     char *lang;
141     apr_xlate_t *convset;
142
143     if (lang_line) {
144         lang_line = apr_pstrdup(r->pool, lang_line);
145         for (lang = lang_line;*lang;lang++) {
146             if ((*lang == ',') || (*lang == ';')) {
147                 *lang = '\0';
148                 break;
149             }
150         }
151         lang = derive_codepage_from_lang(r->pool, lang_line);
152
153         if (lang && (apr_xlate_open(&convset, to_charset, lang, r->pool) == APR_SUCCESS)) {
154             return convset;
155         }
156     }
157
158     return NULL;
159 }
160
161
162 /*
163  * Build the search filter, or at least as much of the search filter that
164  * will fit in the buffer. We don't worry about the buffer not being able
165  * to hold the entire filter. If the buffer wasn't big enough to hold the
166  * filter, ldap_search_s will complain, but the only situation where this
167  * is likely to happen is if the client sent a really, really long
168  * username, most likely as part of an attack.
169  *
170  * The search filter consists of the filter provided with the URL,
171  * combined with a filter made up of the attribute provided with the URL,
172  * and the actual username passed by the HTTP client. For example, assume
173  * that the LDAP URL is
174  * 
175  *   ldap://ldap.airius.com/ou=People, o=Airius?uid??(posixid=*)
176  *
177  * Further, assume that the userid passed by the client was `userj'.  The
178  * search filter will be (&(posixid=*)(uid=userj)).
179  */
180 #define FILTER_LENGTH MAX_STRING_LEN
181 void mod_auth_ldap_build_filter(char *filtbuf, 
182                                 request_rec *r, 
183                                 mod_auth_ldap_config_t *sec)
184 {
185     char *p, *q, *filtbuf_end;
186     char *user;
187     apr_xlate_t *convset = NULL;
188     apr_size_t inbytes;
189     apr_size_t outbytes;
190     char *outbuf;
191
192     if (r->user != NULL) {
193         user = apr_pstrdup (r->pool, r->user);
194     }
195     else
196         return;
197
198     if (charset_conversions) {
199         convset = get_conv_set(r);
200     }
201
202     if (convset) {
203         inbytes = strlen(user);
204         outbytes = (inbytes+1)*3;
205         outbuf = apr_pcalloc(r->pool, outbytes);
206
207         /* Convert the user name to UTF-8.  This is only valid for LDAP v3 */
208         if (apr_xlate_conv_buffer(convset, user, &inbytes, outbuf, &outbytes) == APR_SUCCESS) {
209             user = apr_pstrdup(r->pool, outbuf);
210         }
211     }
212
213     /* 
214      * Create the first part of the filter, which consists of the 
215      * config-supplied portions.
216      */
217     apr_snprintf(filtbuf, FILTER_LENGTH, "(&(%s)(%s=", sec->filter, sec->attribute);
218
219     /* 
220      * Now add the client-supplied username to the filter, ensuring that any
221      * LDAP filter metachars are escaped.
222      */
223     filtbuf_end = filtbuf + FILTER_LENGTH - 1;
224     for (p = user, q=filtbuf + strlen(filtbuf);
225          *p && q < filtbuf_end; *q++ = *p++) {
226 #if APR_HAS_MICROSOFT_LDAPSDK
227         /* Note: The Microsoft SDK escapes for us, so is not necessary */
228 #else
229         if (strchr("*()\\", *p) != NULL) {
230             *q++ = '\\';
231             if (q >= filtbuf_end) {
232                 break;
233             }
234         }
235 #endif
236     }
237     *q = '\0';
238
239     /* 
240      * Append the closing parens of the filter, unless doing so would 
241      * overrun the buffer.
242      */
243     if (q + 2 <= filtbuf_end)
244         strcat(filtbuf, "))");
245 }
246
247 static apr_status_t mod_auth_ldap_cleanup_connection_close(void *param)
248 {
249     util_ldap_connection_t *ldc = param;
250     util_ldap_connection_close(ldc);
251     return APR_SUCCESS;
252 }
253
254
255 /*
256  * Authentication Phase
257  * --------------------
258  *
259  * This phase authenticates the credentials the user has sent with
260  * the request (ie the username and password are checked). This is done
261  * by making an attempt to bind to the LDAP server using this user's
262  * DN and the supplied password.
263  *
264  */
265 int mod_auth_ldap_check_user_id(request_rec *r)
266 {
267     int failures = 0;
268     const char **vals = NULL;
269     char filtbuf[FILTER_LENGTH];
270     mod_auth_ldap_config_t *sec =
271         (mod_auth_ldap_config_t *)ap_get_module_config(r->per_dir_config, &auth_ldap_module);
272
273     util_ldap_connection_t *ldc = NULL;
274     const char *sent_pw;
275     int result = 0;
276     const char *dn = NULL;
277
278     mod_auth_ldap_request_t *req =
279         (mod_auth_ldap_request_t *)apr_pcalloc(r->pool, sizeof(mod_auth_ldap_request_t));
280     ap_set_module_config(r->request_config, &auth_ldap_module, req);
281
282     if (!sec->enabled) {
283         return DECLINED;
284     }
285
286     /* 
287      * Basic sanity checks before any LDAP operations even happen.
288      */
289     if (!sec->have_ldap_url) {
290         return DECLINED;
291     }
292
293 start_over:
294
295     /* There is a good AuthLDAPURL, right? */
296     if (sec->host) {
297         ldc = util_ldap_connection_find(r, sec->host, sec->port,
298                                        sec->binddn, sec->bindpw, sec->deref,
299                                        sec->secure);
300     }
301     else {
302         ap_log_rerror(APLOG_MARK, APLOG_WARNING|APLOG_NOERRNO, 0, r, 
303                       "[%d] auth_ldap authenticate: no sec->host - weird...?", getpid());
304         return sec->auth_authoritative? HTTP_UNAUTHORIZED : DECLINED;
305     }
306
307     ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, r,
308                   "[%d] auth_ldap authenticate: using URL %s", getpid(), sec->url);
309
310     /* Get the password that the client sent */
311     if ((result = ap_get_basic_auth_pw(r, &sent_pw))) {
312         ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, r,
313                       "[%d] auth_ldap authenticate: "
314                       "ap_get_basic_auth_pw() returns %d", getpid(), result);
315         util_ldap_connection_close(ldc);
316         return result;
317     }
318
319     if (r->user == NULL) {
320         ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, r,
321                       "[%d] auth_ldap authenticate: no user specified", getpid());
322         util_ldap_connection_close(ldc);
323         return sec->auth_authoritative? HTTP_UNAUTHORIZED : DECLINED;
324     }
325
326     /* build the username filter */
327     mod_auth_ldap_build_filter(filtbuf, r, sec);
328
329     /* do the user search */
330     result = util_ldap_cache_checkuserid(r, ldc, sec->url, sec->basedn, sec->scope,
331                                          sec->attributes, filtbuf, sent_pw, &dn, &vals);
332     util_ldap_connection_close(ldc);
333
334     /* sanity check - if server is down, retry it up to 5 times */
335     if (result == LDAP_SERVER_DOWN) {
336         if (failures++ <= 5) {
337             goto start_over;
338         }
339     }
340
341     /* handle bind failure */
342     if (result != LDAP_SUCCESS) {
343         ap_log_rerror(APLOG_MARK, APLOG_WARNING|APLOG_NOERRNO, 0, r, 
344                       "[%d] auth_ldap authenticate: "
345                       "user %s authentication failed; URI %s [%s][%s]",
346                       getpid(), r->user, r->uri, ldc->reason, ldap_err2string(result));
347         if ((LDAP_INVALID_CREDENTIALS == result) || sec->auth_authoritative) {
348             ap_note_basic_auth_failure(r);
349             return HTTP_UNAUTHORIZED;
350         }
351         else {
352             return DECLINED;
353         }
354     }
355
356     /* mark the user and DN */
357     req->dn = apr_pstrdup(r->pool, dn);
358     req->user = r->user;
359     if (sec->user_is_dn) {
360         r->user = req->dn;
361     }
362
363     /* add environment variables */
364     if (sec->attributes && vals) {
365         apr_table_t *e = r->subprocess_env;
366         int i = 0;
367         while (sec->attributes[i]) {
368             char *str = apr_pstrcat(r->pool, "AUTHENTICATE_", sec->attributes[i], NULL);
369             int j = 13;
370             while (str[j]) {
371                 if (str[j] >= 'a' && str[j] <= 'z') {
372                     str[j] = str[j] - ('a' - 'A');
373                 }
374                 j++;
375             }
376             apr_table_setn(e, str, vals[i]);
377             i++;
378         }
379     }
380
381     ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, r, 
382                   "[%d] auth_ldap authenticate: accepting %s", getpid(), r->user);
383
384     return OK;
385 }
386
387
388 /*
389  * Authorisation Phase
390  * -------------------
391  *
392  * After checking whether the username and password are correct, we need
393  * to check whether that user is authorised to view this resource. The
394  * require directive is used to do this:
395  *
396  *  require valid-user          Any authenticated is allowed in.
397  *  require user <username>     This particular user is allowed in.
398  *  require group <groupname>   The user must be a member of this group
399  *                              in order to be allowed in.
400  *  require dn <dn>             The user must have the following DN in the
401  *                              LDAP tree to be let in.
402  *
403  */
404 int mod_auth_ldap_auth_checker(request_rec *r)
405 {
406     int result = 0;
407     mod_auth_ldap_request_t *req =
408         (mod_auth_ldap_request_t *)ap_get_module_config(r->request_config,
409         &auth_ldap_module);
410     mod_auth_ldap_config_t *sec =
411         (mod_auth_ldap_config_t *)ap_get_module_config(r->per_dir_config, 
412         &auth_ldap_module);
413
414     util_ldap_connection_t *ldc = NULL;
415     int m = r->method_number;
416
417     const apr_array_header_t *reqs_arr = ap_requires(r);
418     require_line *reqs = reqs_arr ? (require_line *)reqs_arr->elts : NULL;
419
420     register int x;
421     const char *t;
422     char *w;
423     int method_restricted = 0;
424
425     if (!sec->enabled) {
426         return DECLINED;
427     }
428
429     if (!sec->have_ldap_url) {
430         return DECLINED;
431     }
432
433     if (sec->host) {
434         ldc = util_ldap_connection_find(r, sec->host, sec->port,
435                                        sec->binddn, sec->bindpw, sec->deref,
436                                        sec->secure);
437         apr_pool_cleanup_register(r->pool, ldc,
438                                   mod_auth_ldap_cleanup_connection_close,
439                                   apr_pool_cleanup_null);
440     }
441     else {
442         ap_log_rerror(APLOG_MARK, APLOG_WARNING|APLOG_NOERRNO, 0, r, 
443                       "[%d] auth_ldap authorise: no sec->host - weird...?", getpid());
444         return sec->auth_authoritative? HTTP_UNAUTHORIZED : DECLINED;
445     }
446
447     /* 
448      * If there are no elements in the group attribute array, the default should be
449      * member and uniquemember; populate the array now.
450      */
451     if (sec->groupattr->nelts == 0) {
452         struct mod_auth_ldap_groupattr_entry_t *grp;
453 #if APR_HAS_THREADS
454         apr_thread_mutex_lock(sec->lock);
455 #endif
456         grp = apr_array_push(sec->groupattr);
457         grp->name = "member";
458         grp = apr_array_push(sec->groupattr);
459         grp->name = "uniquemember";
460 #if APR_HAS_THREADS
461         apr_thread_mutex_unlock(sec->lock);
462 #endif
463     }
464
465     if (!reqs_arr) {
466         ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, r,
467                       "[%d] auth_ldap authorise: no requirements array", getpid());
468         return sec->auth_authoritative? HTTP_UNAUTHORIZED : DECLINED;
469     }
470
471     /* Loop through the requirements array until there's no elements
472      * left, or something causes a return from inside the loop */
473     for(x=0; x < reqs_arr->nelts; x++) {
474         if (! (reqs[x].method_mask & (1 << m))) {
475             continue;
476         }
477         method_restricted = 1;
478         
479         t = reqs[x].requirement;
480         w = ap_getword_white(r->pool, &t);
481     
482         if (strcmp(w, "valid-user") == 0) {
483             /*
484              * Valid user will always be true if we authenticated with ldap,
485              * but when using front page, valid user should only be true if
486              * he exists in the frontpage password file. This hack will get
487              * auth_ldap to look up the user in the the pw file to really be
488              * sure that he's valid. Naturally, it requires mod_auth to be
489              * compiled in, but if mod_auth wasn't in there, then the need
490              * for this hack wouldn't exist anyway.
491              */
492             if (sec->frontpage_hack) {
493                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, r, 
494                               "[%d] auth_ldap authorise: "
495                               "deferring authorisation to mod_auth (FP Hack)", 
496                               getpid());
497                 return OK;
498             }
499             else {
500                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, r, 
501                               "[%d] auth_ldap authorise: "
502                               "successful authorisation because user "
503                               "is valid-user", getpid());
504                 return OK;
505             }
506         }
507         else if (strcmp(w, "user") == 0) {
508             if (req->dn == NULL || strlen(req->dn) == 0) {
509                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, r,
510                               "[%d] auth_ldap authorise: "
511                               "require user: user's DN has not been defined; failing authorisation", 
512                               getpid());
513                 return sec->auth_authoritative? HTTP_UNAUTHORIZED : DECLINED;
514             }
515             /* 
516              * First do a whole-line compare, in case it's something like
517              *   require user Babs Jensen
518              */
519             result = util_ldap_cache_compare(r, ldc, sec->url, req->dn, sec->attribute, t);
520             switch(result) {
521                 case LDAP_COMPARE_TRUE: {
522                     ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, r, 
523                                   "[%d] auth_ldap authorise: "
524                                   "require user: authorisation successful", getpid());
525                     return OK;
526                 }
527                 default: {
528                     ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, r, 
529                                   "[%d] auth_ldap authorise: require user: "
530                                   "authorisation failed [%s][%s]", getpid(),
531                                   ldc->reason, ldap_err2string(result));
532                 }
533             }
534             /* 
535              * Now break apart the line and compare each word on it 
536              */
537             while (t[0]) {
538                 w = ap_getword_conf(r->pool, &t);
539                 result = util_ldap_cache_compare(r, ldc, sec->url, req->dn, sec->attribute, w);
540                 switch(result) {
541                     case LDAP_COMPARE_TRUE: {
542                         ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, r, 
543                                       "[%d] auth_ldap authorise: "
544                                       "require user: authorisation successful", getpid());
545                         return OK;
546                     }
547                     default: {
548                         ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, r, 
549                                       "[%d] auth_ldap authorise: "
550                                       "require user: authorisation failed [%s][%s]",
551                                       getpid(), ldc->reason, ldap_err2string(result));
552                     }
553                 }
554             }
555         }
556         else if (strcmp(w, "dn") == 0) {
557             if (req->dn == NULL || strlen(req->dn) == 0) {
558                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, r,
559                               "[%d] auth_ldap authorise: "
560                               "require dn: user's DN has not been defined; failing authorisation", 
561                               getpid());
562                 return sec->auth_authoritative? HTTP_UNAUTHORIZED : DECLINED;
563             }
564
565             result = util_ldap_cache_comparedn(r, ldc, sec->url, req->dn, t, sec->compare_dn_on_server);
566             switch(result) {
567                 case LDAP_COMPARE_TRUE: {
568                     ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, r, 
569                                   "[%d] auth_ldap authorise: "
570                                   "require dn: authorisation successful", getpid());
571                     return OK;
572                 }
573                 default: {
574                     ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, r, 
575                                   "[%d] auth_ldap authorise: "
576                                   "require dn \"%s\": LDAP error [%s][%s]",
577                                   getpid(), t, ldc->reason, ldap_err2string(result));
578                 }
579             }
580         }
581         else if (strcmp(w, "group") == 0) {
582             struct mod_auth_ldap_groupattr_entry_t *ent = (struct mod_auth_ldap_groupattr_entry_t *) sec->groupattr->elts;
583             int i;
584
585             if (sec->group_attrib_is_dn) {
586                 if (req->dn == NULL || strlen(req->dn) == 0) {
587                     ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, r,
588                                   "[%d] auth_ldap authorise: require group: user's DN has not been defined; failing authorisation", 
589                                   getpid());
590                     return sec->auth_authoritative? HTTP_UNAUTHORIZED : DECLINED;
591                 }
592             }
593             else {
594                 if (req->user == NULL || strlen(req->user) == 0) {
595                     /* We weren't called in the authentication phase, so we didn't have a 
596                      * chance to set the user field. Do so now. */
597                     req->user = r->user;
598                 }
599             }
600
601             ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, r, 
602                           "[%d] auth_ldap authorise: require group: testing for group membership in \"%s\"", 
603                           getpid(), t);
604
605             for (i = 0; i < sec->groupattr->nelts; i++) {
606                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, r, 
607                               "[%d] auth_ldap authorise: require group: testing for %s: %s (%s)", getpid(),
608                               ent[i].name, sec->group_attrib_is_dn ? req->dn : req->user, t);
609
610                 result = util_ldap_cache_compare(r, ldc, sec->url, t, ent[i].name, 
611                                      sec->group_attrib_is_dn ? req->dn : req->user);
612                 switch(result) {
613                     case LDAP_COMPARE_TRUE: {
614                         ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, r, 
615                                       "[%d] auth_ldap authorise: require group: "
616                                       "authorisation successful (attribute %s) [%s][%s]",
617                                       getpid(), ent[i].name, ldc->reason, ldap_err2string(result));
618                         return OK;
619                     }
620                     default: {
621                         ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, r, 
622                                       "[%d] auth_ldap authorise: require group \"%s\": "
623                                       "authorisation failed [%s][%s]",
624                                       getpid(), t, ldc->reason, ldap_err2string(result));
625                     }
626                 }
627             }
628         }
629     }
630
631     if (!method_restricted) {
632         ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, r, 
633                       "[%d] auth_ldap authorise: agreeing because non-restricted", 
634                       getpid());
635         return OK;
636     }
637
638     if (!sec->auth_authoritative) {
639         ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, r, 
640                       "[%d] auth_ldap authorise: declining to authorise", getpid());
641         return DECLINED;
642     }
643
644     ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, r, 
645                   "[%d] auth_ldap authorise: authorisation denied", getpid());
646     ap_note_basic_auth_failure (r);
647
648     return HTTP_UNAUTHORIZED;
649 }
650
651
652 /* ---------------------------------------- */
653 /* config directives */
654
655
656 void *mod_auth_ldap_create_dir_config(apr_pool_t *p, char *d)
657 {
658     mod_auth_ldap_config_t *sec = 
659         (mod_auth_ldap_config_t *)apr_pcalloc(p, sizeof(mod_auth_ldap_config_t));
660
661     sec->pool = p;
662 #if APR_HAS_THREADS
663     apr_thread_mutex_create(&sec->lock, APR_THREAD_MUTEX_DEFAULT, p);
664 #endif
665     sec->auth_authoritative = 1;
666     sec->enabled = 1;
667     sec->groupattr = apr_array_make(p, GROUPATTR_MAX_ELTS, 
668                                    sizeof(struct mod_auth_ldap_groupattr_entry_t));
669
670     sec->have_ldap_url = 0;
671     sec->url = "";
672     sec->host = NULL;
673     sec->binddn = NULL;
674     sec->bindpw = NULL;
675     sec->deref = always;
676     sec->group_attrib_is_dn = 1;
677
678     sec->frontpage_hack = 0;
679     sec->secure = 0;
680
681     sec->user_is_dn = 0;
682     sec->compare_dn_on_server = 0;
683
684     return sec;
685 }
686
687 /* 
688  * Use the ldap url parsing routines to break up the ldap url into
689  * host and port.
690  */
691 static const char *mod_auth_ldap_parse_url(cmd_parms *cmd, 
692                                     void *config,
693                                     const char *url)
694 {
695     int result;
696     apr_ldap_url_desc_t *urld;
697
698     mod_auth_ldap_config_t *sec = config;
699
700     ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0,
701                  cmd->server, "[%d] auth_ldap url parse: `%s'", 
702                  getpid(), url);
703
704     result = apr_ldap_url_parse(url, &(urld));
705     if (result != LDAP_SUCCESS) {
706         switch (result) {
707         case LDAP_URL_ERR_NOTLDAP:
708             return "LDAP URL does not begin with ldap://";
709         case LDAP_URL_ERR_NODN:
710             return "LDAP URL does not have a DN";
711         case LDAP_URL_ERR_BADSCOPE:
712             return "LDAP URL has an invalid scope";
713         case LDAP_URL_ERR_MEM:
714             return "Out of memory parsing LDAP URL";
715         default:
716             return "Could not parse LDAP URL";
717         }
718     }
719     sec->url = apr_pstrdup(cmd->pool, url);
720
721     ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0,
722                  cmd->server, "[%d] auth_ldap url parse: Host: %s", getpid(), urld->lud_host);
723     ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0,
724                  cmd->server, "[%d] auth_ldap url parse: Port: %d", getpid(), urld->lud_port);
725     ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0,
726                  cmd->server, "[%d] auth_ldap url parse: DN: %s", getpid(), urld->lud_dn);
727     ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0,
728                  cmd->server, "[%d] auth_ldap url parse: attrib: %s", getpid(), urld->lud_attrs? urld->lud_attrs[0] : "(null)");
729     ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0,
730                  cmd->server, "[%d] auth_ldap url parse: scope: %s", getpid(), 
731                  (urld->lud_scope == LDAP_SCOPE_SUBTREE? "subtree" : 
732                  urld->lud_scope == LDAP_SCOPE_BASE? "base" : 
733                  urld->lud_scope == LDAP_SCOPE_ONELEVEL? "onelevel" : "unknown"));
734     ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0,
735                  cmd->server, "[%d] auth_ldap url parse: filter: %s", getpid(), urld->lud_filter);
736
737     /* Set all the values, or at least some sane defaults */
738     if (sec->host) {
739         char *p = apr_palloc(cmd->pool, strlen(sec->host) + strlen(urld->lud_host) + 2);
740         strcpy(p, urld->lud_host);
741         strcat(p, " ");
742         strcat(p, sec->host);
743         sec->host = p;
744     }
745     else {
746         sec->host = urld->lud_host? apr_pstrdup(cmd->pool, urld->lud_host) : "localhost";
747     }
748     sec->basedn = urld->lud_dn? apr_pstrdup(cmd->pool, urld->lud_dn) : "";
749     if (urld->lud_attrs && urld->lud_attrs[0]) {
750         int i = 1;
751         while (urld->lud_attrs[i]) {
752             i++;
753         }
754         sec->attributes = apr_pcalloc(cmd->pool, sizeof(char *) * (i+1));
755         i = 0;
756         while (urld->lud_attrs[i]) {
757             sec->attributes[i] = apr_pstrdup(cmd->pool, urld->lud_attrs[i]);
758             i++;
759         }
760         sec->attribute = sec->attributes[0];
761     }
762     else {
763         sec->attribute = "uid";
764     }
765
766     sec->scope = urld->lud_scope == LDAP_SCOPE_ONELEVEL ?
767         LDAP_SCOPE_ONELEVEL : LDAP_SCOPE_SUBTREE;
768
769     if (urld->lud_filter) {
770         if (urld->lud_filter[0] == '(') {
771             /* 
772              * Get rid of the surrounding parens; later on when generating the
773              * filter, they'll be put back.
774              */
775             sec->filter = apr_pstrdup(cmd->pool, urld->lud_filter+1);
776             sec->filter[strlen(sec->filter)-1] = '\0';
777         }
778         else {
779             sec->filter = apr_pstrdup(cmd->pool, urld->lud_filter);
780         }
781     }
782     else {
783         sec->filter = "objectclass=*";
784     }
785
786       /* "ldaps" indicates secure ldap connections desired
787       */
788     if (strncasecmp(url, "ldaps", 5) == 0)
789     {
790         sec->secure = 1;
791         sec->port = urld->lud_port? urld->lud_port : LDAPS_PORT;
792         ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, cmd->server,
793                      "LDAP: auth_ldap using SSL connections");
794     }
795     else
796     {
797         sec->secure = 0;
798         sec->port = urld->lud_port? urld->lud_port : LDAP_PORT;
799         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, cmd->server, 
800                      "LDAP: auth_ldap not using SSL connections");
801     }
802
803     sec->have_ldap_url = 1;
804     apr_ldap_free_urldesc(urld);
805     return NULL;
806 }
807
808 static const char *mod_auth_ldap_set_deref(cmd_parms *cmd, void *config, const char *arg)
809 {
810     mod_auth_ldap_config_t *sec = config;
811
812     if (strcmp(arg, "never") == 0 || strcasecmp(arg, "off") == 0) {
813         sec->deref = never;
814     }
815     else if (strcmp(arg, "searching") == 0) {
816         sec->deref = searching;
817     }
818     else if (strcmp(arg, "finding") == 0) {
819         sec->deref = finding;
820     }
821     else if (strcmp(arg, "always") == 0 || strcasecmp(arg, "on") == 0) {
822         sec->deref = always;
823     }
824     else {
825         return "Unrecognized value for AuthLDAPAliasDereference directive";
826     }
827     return NULL;
828 }
829
830 static const char *mod_auth_ldap_add_group_attribute(cmd_parms *cmd, void *config, const char *arg)
831 {
832     struct mod_auth_ldap_groupattr_entry_t *new;
833
834     mod_auth_ldap_config_t *sec = config;
835
836     if (sec->groupattr->nelts > GROUPATTR_MAX_ELTS)
837         return "Too many AuthLDAPGroupAttribute directives";
838
839     new = apr_array_push(sec->groupattr);
840     new->name = apr_pstrdup(cmd->pool, arg);
841   
842     return NULL;
843 }
844
845 static const char *set_charset_config(cmd_parms *cmd, void *config, const char *arg)
846 {
847     ap_set_module_config(cmd->server->module_config, &auth_ldap_module,
848                          (void *)arg);
849     return NULL;
850 }
851
852
853 command_rec mod_auth_ldap_cmds[] = {
854     AP_INIT_TAKE1("AuthLDAPURL", mod_auth_ldap_parse_url, NULL, OR_AUTHCFG, 
855                   "URL to define LDAP connection. This should be an RFC 2255 complaint\n"
856                   "URL of the form ldap://host[:port]/basedn[?attrib[?scope[?filter]]].\n"
857                   "<ul>\n"
858                   "<li>Host is the name of the LDAP server. Use a space separated list of hosts \n"
859                   "to specify redundant servers.\n"
860                   "<li>Port is optional, and specifies the port to connect to.\n"
861                   "<li>basedn specifies the base DN to start searches from\n"
862                   "<li>Attrib specifies what attribute to search for in the directory. If not "
863                   "provided, it defaults to <b>uid</b>.\n"
864                   "<li>Scope is the scope of the search, and can be either <b>sub</b> or "
865                   "<b>one</b>. If not provided, the default is <b>sub</b>.\n"
866                   "<li>Filter is a filter to use in the search. If not provided, "
867                   "defaults to <b>(objectClass=*)</b>.\n"
868                   "</ul>\n"
869                   "Searches are performed using the attribute and the filter combined. "
870                   "For example, assume that the\n"
871                   "LDAP URL is <b>ldap://ldap.airius.com/ou=People, o=Airius?uid?sub?(posixid=*)</b>. "
872                   "Searches will\n"
873                   "be done using the filter <b>(&((posixid=*))(uid=<i>username</i>))</b>, "
874                   "where <i>username</i>\n"
875                   "is the user name passed by the HTTP client. The search will be a subtree "
876                   "search on the branch <b>ou=People, o=Airius</b>."),
877
878     AP_INIT_TAKE1("AuthLDAPBindDN", ap_set_string_slot,
879                   (void *)APR_OFFSETOF(mod_auth_ldap_config_t, binddn), OR_AUTHCFG,
880                   "DN to use to bind to LDAP server. If not provided, will do an anonymous bind."),
881
882     AP_INIT_TAKE1("AuthLDAPBindPassword", ap_set_string_slot,
883                   (void *)APR_OFFSETOF(mod_auth_ldap_config_t, bindpw), OR_AUTHCFG,
884                   "Password to use to bind to LDAP server. If not provided, will do an anonymous bind."),
885
886     AP_INIT_FLAG("AuthLDAPRemoteUserIsDN", ap_set_flag_slot,
887                  (void *)APR_OFFSETOF(mod_auth_ldap_config_t, user_is_dn), OR_AUTHCFG,
888                  "Set to 'on' to set the REMOTE_USER environment variable to be the full "
889                  "DN of the remote user. By default, this is set to off, meaning that "
890                  "the REMOTE_USER variable will contain whatever value the remote user sent."),
891
892     AP_INIT_FLAG("AuthLDAPAuthoritative", ap_set_flag_slot,
893                  (void *)APR_OFFSETOF(mod_auth_ldap_config_t, auth_authoritative), OR_AUTHCFG,
894                  "Set to 'off' to allow access control to be passed along to lower modules if "
895                  "the UserID and/or group is not known to this module"),
896
897     AP_INIT_FLAG("AuthLDAPCompareDNOnServer", ap_set_flag_slot,
898                  (void *)APR_OFFSETOF(mod_auth_ldap_config_t, compare_dn_on_server), OR_AUTHCFG,
899                  "Set to 'on' to force auth_ldap to do DN compares (for the \"require dn\" "
900                  "directive) using the server, and set it 'off' to do the compares locally "
901                  "(at the expense of possible false matches). See the documentation for "
902                  "a complete description of this option."),
903
904     AP_INIT_ITERATE("AuthLDAPGroupAttribute", mod_auth_ldap_add_group_attribute, NULL, OR_AUTHCFG,
905                     "A list of attributes used to define group membership - defaults to "
906                     "member and uniquemember"),
907
908     AP_INIT_FLAG("AuthLDAPGroupAttributeIsDN", ap_set_flag_slot,
909                  (void *)APR_OFFSETOF(mod_auth_ldap_config_t, group_attrib_is_dn), OR_AUTHCFG,
910                  "If set to 'on', auth_ldap uses the DN that is retrieved from the server for"
911                  "subsequent group comparisons. If set to 'off', auth_ldap uses the string"
912                  "provided by the client directly. Defaults to 'on'."),
913
914     AP_INIT_TAKE1("AuthLDAPDereferenceAliases", mod_auth_ldap_set_deref, NULL, OR_AUTHCFG,
915                   "Determines how aliases are handled during a search. Can bo one of the"
916                   "values \"never\", \"searching\", \"finding\", or \"always\". "
917                   "Defaults to always."),
918
919     AP_INIT_FLAG("AuthLDAPEnabled", ap_set_flag_slot,
920                  (void *)APR_OFFSETOF(mod_auth_ldap_config_t, enabled), OR_AUTHCFG,
921                  "Set to off to disable auth_ldap, even if it's been enabled in a higher tree"),
922  
923     AP_INIT_FLAG("AuthLDAPFrontPageHack", ap_set_flag_slot,
924                  (void *)APR_OFFSETOF(mod_auth_ldap_config_t, frontpage_hack), OR_AUTHCFG,
925                  "Set to 'on' to support Microsoft FrontPage"),
926
927     AP_INIT_TAKE1("AuthLDAPCharsetConfig", set_charset_config, NULL, RSRC_CONF,
928                   "Character set conversion configuration file. If omitted, character set"
929                   "conversion is disabled."),
930
931     {NULL}
932 };
933
934 static int auth_ldap_post_config(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
935 {
936     ap_configfile_t *f;
937     char l[MAX_STRING_LEN];
938     const char *charset_confname = ap_get_module_config(s->module_config,
939                                                       &auth_ldap_module);
940     apr_status_t status;
941     
942     /*
943     mod_auth_ldap_config_t *sec = (mod_auth_ldap_config_t *)
944                                     ap_get_module_config(s->module_config, 
945                                                          &auth_ldap_module);
946
947     if (sec->secure)
948     {
949         if (!util_ldap_ssl_supported(s))
950         {
951             ap_log_error(APLOG_MARK, APLOG_CRIT, 0, s, 
952                      "LDAP: SSL connections (ldaps://) not supported by utilLDAP");
953             return(!OK);
954         }
955     }
956     */
957
958     /* make sure that mod_ldap (util_ldap) is loaded */
959     if (ap_find_linked_module("util_ldap.c") == NULL) {
960         ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, s,
961                      "Module mod_ldap missing. Mod_ldap (aka. util_ldap) "
962                      "must be loaded in order for mod_auth_ldap to function properly");
963         return HTTP_INTERNAL_SERVER_ERROR;
964
965     }
966
967     if (!charset_confname) {
968         return OK;
969     }
970
971     charset_confname = ap_server_root_relative(p, charset_confname);
972     if (!charset_confname) {
973         ap_log_error(APLOG_MARK, APLOG_ERR, APR_EBADPATH, s,
974                      "Invalid charset conversion config path %s", 
975                      (const char *)ap_get_module_config(s->module_config,
976                                                         &auth_ldap_module));
977         return HTTP_INTERNAL_SERVER_ERROR;
978     }
979     if ((status = ap_pcfg_openfile(&f, ptemp, charset_confname)) 
980                 != APR_SUCCESS) {
981         ap_log_error(APLOG_MARK, APLOG_ERR, status, s,
982                      "could not open charset conversion config file %s.", 
983                      charset_confname);
984         return HTTP_INTERNAL_SERVER_ERROR;
985     }
986
987     charset_conversions = apr_hash_make(p);
988
989     while (!(ap_cfg_getline(l, MAX_STRING_LEN, f))) {
990         const char *ll = l;
991         char *lang;
992
993         if (l[0] == '#') {
994             continue;
995         }
996         lang = ap_getword_conf(p, &ll);
997         ap_str_tolower(lang);
998
999         if (ll[0]) {
1000             char *charset = ap_getword_conf(p, &ll);
1001             apr_hash_set(charset_conversions, lang, APR_HASH_KEY_STRING, charset);
1002         }
1003     }
1004     ap_cfg_closefile(f);
1005     
1006     to_charset = derive_codepage_from_lang (p, "utf-8");
1007     if (to_charset == NULL) {
1008         ap_log_error(APLOG_MARK, APLOG_ERR, status, s,
1009                      "could not find the UTF-8 charset in the file %s.", 
1010                      charset_confname);
1011         return HTTP_INTERNAL_SERVER_ERROR;
1012     }
1013
1014     return OK;
1015 }
1016
1017 static void mod_auth_ldap_register_hooks(apr_pool_t *p)
1018 {
1019     ap_hook_post_config(auth_ldap_post_config,NULL,NULL,APR_HOOK_MIDDLE);
1020     ap_hook_check_user_id(mod_auth_ldap_check_user_id, NULL, NULL, APR_HOOK_MIDDLE);
1021     ap_hook_auth_checker(mod_auth_ldap_auth_checker, NULL, NULL, APR_HOOK_MIDDLE);
1022 }
1023
1024 module auth_ldap_module = {
1025    STANDARD20_MODULE_STUFF,
1026    mod_auth_ldap_create_dir_config,     /* dir config creater */
1027    NULL,                                /* dir merger --- default is to override */
1028    NULL,                                /* server config */
1029    NULL,                                /* merge server config */
1030    mod_auth_ldap_cmds,                  /* command table */
1031    mod_auth_ldap_register_hooks,        /* set up request processing hooks */
1032 };