Start
[exim.git] / src / src / lookups / ldap.c
CommitLineData
0756eb3c
PH
1/* $Cambridge: exim/src/src/lookups/ldap.c,v 1.1 2004/10/07 13:10:01 ph10 Exp $ */
2
3/*************************************************
4* Exim - an Internet mail transport agent *
5*************************************************/
6
7/* Copyright (c) University of Cambridge 1995 - 2004 */
8/* See the file NOTICE for conditions of use and distribution. */
9
10/* Many thanks to Stuart Lynne for contributing the original code for this
11driver. Further contibutions from Michael Haardt, Brian Candler, Barry
12Pederson, Peter Savitch and Christian Kellner. Particular thanks to Brian for
13researching how to handle the different kinds of error. */
14
15
16#include "../exim.h"
17#include "lf_functions.h"
18#include "ldap.h"
19
20
21/* We can't just compile this code and allow the library mechanism to omit the
22functions if they are not wanted, because we need to have the LDAP headers
23available for compiling. Therefore, compile these functions only if LOOKUP_LDAP
24is defined. However, some compilers don't like compiling empty modules, so keep
25them happy with a dummy when skipping the rest. Make it reference itself to
26stop picky compilers complaining that it is unused, and put in a dummy argument
27to stop even pickier compilers complaining about infinite loops. */
28
29#ifndef LOOKUP_LDAP
30static void dummy(int x) { dummy(x-1); }
31#else
32
33
34/* Include LDAP headers */
35
36#include <lber.h>
37#include <ldap.h>
38
39
40/* Annoyingly, the different LDAP libraries handle errors in different ways,
41and some other things too. There doesn't seem to be an automatic way of
42distinguishing between them. Local/Makefile should contain a setting of
43LDAP_LIB_TYPE, which in turn causes appropriate macros to be defined for the
44different kinds. Those that matter are:
45
46LDAP_LIB_NETSCAPE
47LDAP_LIB_SOLARIS with synonym LDAP_LIB_SOLARIS7
48LDAP_LIB_OPENLDAP2
49
50These others may be defined, but are in fact the default, so are not tested:
51
52LDAP_LIB_UMICHIGAN
53LDAP_LIB_OPENLDAP1
54*/
55
56#if defined(LDAP_LIB_SOLARIS7) && ! defined(LDAP_LIB_SOLARIS)
57#define LDAP_LIB_SOLARIS
58#endif
59
60
61/* Just in case LDAP_NO_LIMIT is not defined by some of these libraries. */
62
63#ifndef LDAP_NO_LIMIT
64#define LDAP_NO_LIMIT 0
65#endif
66
67
68/* Just in case LDAP_DEREF_NEVER is not defined */
69
70#ifndef LDAP_DEREF_NEVER
71#define LDAP_DEREF_NEVER 0
72#endif
73
74
75/* For libraries without TCP connect timeouts */
76
77#ifndef LDAP_X_IO_TIMEOUT_NO_TIMEOUT
78#define LDAP_X_IO_TIMEOUT_NO_TIMEOUT (-1)
79#endif
80
81
82/* Four types of LDAP search are implemented */
83
84#define SEARCH_LDAP_MULTIPLE 0 /* Get attributes from multiple entries */
85#define SEARCH_LDAP_SINGLE 1 /* Get attributes from one entry only */
86#define SEARCH_LDAP_DN 2 /* Get just the DN from one entry */
87#define SEARCH_LDAP_AUTH 3 /* Just checking for authentication */
88
89/* In all 4 cases, the DN is left in $ldap_dn (which post-dates the
90SEARCH_LDAP_DN lookup). */
91
92
93/* Structure and anchor for caching connections. */
94
95typedef struct ldap_connection {
96 struct ldap_connection *next;
97 uschar *host;
98 uschar *user;
99 uschar *password;
100 BOOL bound;
101 int port;
102 LDAP *ld;
103} LDAP_CONNECTION;
104
105static LDAP_CONNECTION *ldap_connections = NULL;
106
107
108
109/*************************************************
110* Internal search function *
111*************************************************/
112
113/* This is the function that actually does the work. It is called (indirectly
114via control_ldap_search) from eldap_find(), eldapauth_find(), eldapdn_find(),
115and eldapm_find(), with a difference in the "search_type" argument.
116
117The case of eldapauth_find() is special in that all it does is do
118authentication, returning OK or FAIL as appropriate. This isn't used as a
119lookup. Instead, it is called from expand.c as an expansion condition test.
120
121The DN from a successful lookup is placed in $ldap_dn. This feature postdates
122the provision of the SEARCH_LDAP_DN facility for returning just the DN as the
123data.
124
125Arguments:
126 ldap_url the URL to be looked up
127 server server host name, when URL contains none
128 s_port server port, used when URL contains no name
129 search_type SEARCH_LDAP_MULTIPLE allows values from multiple entries
130 SEARCH_LDAP_SINGLE allows values from one entry only
131 SEARCH_LDAP_DN gets the DN from one entry
132 res set to point at the result (not used for ldapauth)
133 errmsg set to point a message if result is not OK
134 defer_break set TRUE if no more servers to be tried after a DEFER
135 user user name for authentication, or NULL
136 password password for authentication, or NULL
137 sizelimit max number of entries returned, or 0 for no limit
138 timelimit max time to wait, or 0 for no limit
139 tcplimit max time to connect, or NULL for OS default
140 deference the dereference option, which is one of
141 LDAP_DEREF_{NEVER,SEARCHING,FINDING,ALWAYS}
142
143Returns: OK or FAIL or DEFER
144 FAIL is given only if a lookup was performed successfully, but
145 returned no data.
146*/
147
148static int
149perform_ldap_search(uschar *ldap_url, uschar *server, int s_port, int search_type,
150 uschar **res, uschar **errmsg, BOOL *defer_break, uschar *user, uschar *password,
151 int sizelimit, int timelimit, int tcplimit, int dereference)
152{
153LDAPURLDesc *ludp = NULL;
154LDAPMessage *result = NULL;
155BerElement *ber;
156LDAP_CONNECTION *lcp;
157
158struct timeval timeout;
159struct timeval *timeoutptr = NULL;
160
161uschar *attr;
162uschar **attrp;
163uschar *data = NULL;
164uschar *dn = NULL;
165uschar *host;
166uschar **values;
167uschar **firstval;
168uschar porttext[16];
169
170uschar *error1 = NULL; /* string representation of errcode (static) */
171uschar *error2 = NULL; /* error message from the server */
172uschar *matched = NULL; /* partially matched DN */
173
174int attr_count = 0;
175int error_yield = DEFER;
176int msgid;
177int rc;
178int port;
179int ptr = 0;
180int rescount = 0;
181int size = 0;
182BOOL attribute_found = FALSE;
183BOOL ldapi = FALSE;
184
185DEBUG(D_lookup)
186 debug_printf("perform_ldap_search: ldap%s URL = \"%s\" server=%s port=%d "
187 "sizelimit=%d timelimit=%d tcplimit=%d\n",
188 (search_type == SEARCH_LDAP_MULTIPLE)? "m" :
189 (search_type == SEARCH_LDAP_DN)? "dn" :
190 (search_type == SEARCH_LDAP_AUTH)? "auth" : "",
191 ldap_url, server, s_port, sizelimit, timelimit, tcplimit);
192
193/* Check if LDAP thinks the URL is a valid LDAP URL. We assume that if the LDAP
194library that is in use doesn't recognize, say, "ldapi", it will barf here. */
195
196if (!ldap_is_ldap_url(CS ldap_url))
197 {
198 *errmsg = string_sprintf("ldap_is_ldap_url: not an LDAP url \"%s\"\n",
199 ldap_url);
200 goto RETURN_ERROR_BREAK;
201 }
202
203/* Parse the URL */
204
205if ((rc = ldap_url_parse(CS ldap_url, &ludp)) != 0)
206 {
207 *errmsg = string_sprintf("ldap_url_parse: (error %d) parsing \"%s\"\n", rc,
208 ldap_url);
209 goto RETURN_ERROR_BREAK;
210 }
211
212/* If the host name is empty, take it from the separate argument, if one is
213given. OpenLDAP 2.0.6 sets an unset hostname to "" rather than empty, but
214expects NULL later in ldap_init() to mean "default", annoyingly. In OpenLDAP
2152.0.11 this has changed (it uses NULL). */
216
217if ((ludp->lud_host == NULL || ludp->lud_host[0] == 0) && server != NULL)
218 {
219 host = server;
220 port = s_port;
221 }
222else
223 {
224 host = US ludp->lud_host;
225 if (host != NULL && host[0] == 0) host = NULL;
226 port = ludp->lud_port;
227 }
228
229DEBUG(D_lookup) debug_printf("after ldap_url_parse: host=%s port=%d\n",
230 host, port);
231
232if (port == 0) port = LDAP_PORT; /* Default if none given */
233sprintf(CS porttext, ":%d", port); /* For messages */
234
235/* If the "host name" is actually a path, we are going to connect using a Unix
236socket, regardless of whether "ldapi" was actually specified or not. This means
237that a Unix socket can be declared in eldap_default_servers, and "traditional"
238LDAP queries using just "ldap" can be used ("ldaps" is similarly overridden).
239The path may start with "/" or it may already be escaped as "%2F" if it was
240actually declared that way in eldap_default_servers. (I did it that way the
241first time.) If the host name is not a path, the use of "ldapi" causes an
242error, except in the default case. (But lud_scheme doesn't seem to exist in
243older libraries.) */
244
245if (host != NULL)
246 {
247 if ((host[0] == '/' || Ustrncmp(host, "%2F", 3) == 0))
248 {
249 ldapi = TRUE;
250 porttext[0] = 0; /* Remove port from messages */
251 }
252
253 #if defined LDAP_LIB_OPENLDAP2
254 else if (strncmp(ludp->lud_scheme, "ldapi", 5) == 0)
255 {
256 *errmsg = string_sprintf("ldapi requires an absolute path (\"%s\" given)",
257 host);
258 goto RETURN_ERROR;
259 }
260 #endif
261 }
262
263/* Count the attributes; we need this later to tell us how to format results */
264
265for (attrp = USS ludp->lud_attrs; attrp != NULL && *attrp != NULL; attrp++)
266 attr_count++;
267
268/* See if we can find a cached connection to this host. The port is not
269relevant for ldapi. The host name pointer is set to NULL if no host was given
270(implying the library default), rather than to the empty string. Note that in
271this case, there is no difference between ldap and ldapi. */
272
273for (lcp = ldap_connections; lcp != NULL; lcp = lcp->next)
274 {
275 if ((host == NULL) != (lcp->host == NULL) ||
276 (host != NULL && strcmpic(lcp->host, host) != 0))
277 continue;
278 if (ldapi || port == lcp->port) break;
279 }
280
281/* If no cached connection found, we must open a connection to the server. If
282the server name is actually an absolute path, we set ldapi=TRUE above. This
283requests connection via a Unix socket. However, as far as I know, only OpenLDAP
284supports the use of sockets, and the use of ldap_initialize(). */
285
286if (lcp == NULL)
287 {
288 LDAP *ld;
289
290
291 /* --------------------------- OpenLDAP ------------------------ */
292
293 /* There seems to be a preference under OpenLDAP for ldap_initialize()
294 instead of ldap_init(), though I have as yet been unable to find
295 documentation that says this. (OpenLDAP documentation is sparse to
296 non-existent). So we handle OpenLDAP differently here. Also, support for
297 ldapi seems to be OpenLDAP-only at present. */
298
299 #ifdef LDAP_LIB_OPENLDAP2
300
301 /* We now need an empty string for the default host. Get some store in which
302 to build a URL for ldap_initialize(). In the ldapi case, it can't be bigger
303 than (9 + 3*Ustrlen(shost)), whereas in the other cases it can't be bigger
304 than the host name + "ldaps:///" plus : and a port number, say 20 + the
305 length of the host name. What we get should accommodate both, easily. */
306
307 uschar *shost = (host == NULL)? US"" : host;
308 uschar *init_url = store_get(20 + 3 * Ustrlen(shost));
309 uschar *init_ptr;
310
311 /* Handle connection via Unix socket ("ldapi"). We build a basic LDAP URI to
312 contain the path name, with slashes escaped as %2F. */
313
314 if (ldapi)
315 {
316 int ch;
317 init_ptr = init_url + 8;
318 Ustrcpy(init_url, "ldapi://");
319 while ((ch = *shost++) != 0)
320 {
321 if (ch == '/')
322 {
323 Ustrncpy(init_ptr, "%2F", 3);
324 init_ptr += 3;
325 }
326 else *init_ptr++ = ch;
327 }
328 *init_ptr = 0;
329 }
330
331 /* This is not an ldapi call. Just build a URI with the protocol type, host
332 name, and port. */
333
334 else
335 {
336 init_ptr = Ustrchr(ldap_url, '/');
337 Ustrncpy(init_url, ldap_url, init_ptr - ldap_url);
338 init_ptr = init_url + (init_ptr - ldap_url);
339 sprintf(CS init_ptr, "//%s:%d/", shost, port);
340 }
341
342 /* Call ldap_initialize() and check the result */
343
344 DEBUG(D_lookup) debug_printf("ldap_initialize with URL %s\n", init_url);
345 rc = ldap_initialize(&ld, CS init_url);
346 if (rc != LDAP_SUCCESS)
347 {
348 *errmsg = string_sprintf("ldap_initialize: (error %d) URL \"%s\"\n",
349 rc, init_url);
350 goto RETURN_ERROR;
351 }
352 store_reset(init_url); /* Might as well save memory when we can */
353
354
355 /* ------------------------- Not OpenLDAP ---------------------- */
356
357 /* For libraries other than OpenLDAP, use ldap_init(). */
358
359 #else /* LDAP_LIB_OPENLDAP2 */
360 ld = ldap_init(CS host, port);
361 #endif /* LDAP_LIB_OPENLDAP2 */
362
363 /* -------------------------------------------------------------- */
364
365
366 /* Handle failure to initialize */
367
368 if (ld == NULL)
369 {
370 *errmsg = string_sprintf("failed to initialize for LDAP server %s%s - %s",
371 host, porttext, strerror(errno));
372 goto RETURN_ERROR;
373 }
374
375 /* Set the TCP connect time limit if available. This is something that is
376 in Netscape SDK v4.1; I don't know about other libraries. */
377
378 #ifdef LDAP_X_OPT_CONNECT_TIMEOUT
379 ldap_set_option(ld, LDAP_X_OPT_CONNECT_TIMEOUT, (void *)&tcplimit);
380 #endif
381
382 /* I could not get TLS to work until I set the version to 3. That version
383 seems to be the default nowadays. The RFC is dated 1997, so I would hope
384 that all the LDAP libraries support it. Therefore, if eldap_version hasn't
385 been set, go for v3 if we can. */
386
387 if (eldap_version < 0)
388 {
389 #ifdef LDAP_VERSION3
390 eldap_version = LDAP_VERSION3;
391 #else
392 eldap_version = 2;
393 #endif
394 }
395
396 #ifdef LDAP_OPT_PROTOCOL_VERSION
397 ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, (void *)&eldap_version);
398 #endif
399
400 DEBUG(D_lookup) debug_printf("initialized for LDAP (v%d) server %s%s\n",
401 eldap_version, host, porttext);
402
403 /* If not using ldapi and TLS is available, set appropriate TLS options: hard
404 for "ldaps" and soft otherwise. */
405
406 #ifdef LDAP_OPT_X_TLS
407 if (!ldapi)
408 {
409 int tls_option;
410 if (strncmp(ludp->lud_scheme, "ldaps", 5) == 0)
411 {
412 tls_option = LDAP_OPT_X_TLS_HARD;
413 DEBUG(D_lookup) debug_printf("LDAP_OPT_X_TLS_HARD set\n");
414 }
415 else
416 {
417 tls_option = LDAP_OPT_X_TLS_TRY;
418 DEBUG(D_lookup) debug_printf("LDAP_OPT_X_TLS_TRY set\n");
419 }
420 ldap_set_option(ld, LDAP_OPT_X_TLS, (void *)&tls_option);
421 }
422 #endif /* LDAP_OPT_X_TLS */
423
424 /* Now add this connection to the chain of cached connections */
425
426 lcp = store_get(sizeof(LDAP_CONNECTION));
427 lcp->host = (host == NULL)? NULL : string_copy(host);
428 lcp->bound = FALSE;
429 lcp->user = NULL;
430 lcp->password = NULL;
431 lcp->port = port;
432 lcp->ld = ld;
433 lcp->next = ldap_connections;
434 ldap_connections = lcp;
435 }
436
437/* Found cached connection */
438
439else
440 {
441 DEBUG(D_lookup)
442 debug_printf("re-using cached connection to LDAP server %s%s\n",
443 host, porttext);
444 }
445
446/* Bind with the user/password supplied, or an anonymous bind if these values
447are NULL, unless a cached connection is already bound with the same values. */
448
449if (!lcp->bound ||
450 (lcp->user == NULL && user != NULL) ||
451 (lcp->user != NULL && user == NULL) ||
452 (lcp->user != NULL && user != NULL && Ustrcmp(lcp->user, user) != 0) ||
453 (lcp->password == NULL && password != NULL) ||
454 (lcp->password != NULL && password == NULL) ||
455 (lcp->password != NULL && password != NULL &&
456 Ustrcmp(lcp->password, password) != 0))
457 {
458 DEBUG(D_lookup) debug_printf("%sbinding with user=%s password=%s\n",
459 (lcp->bound)? "re-" : "", user, password);
460 if ((rc = ldap_bind_s(lcp->ld, CS user, CS password, LDAP_AUTH_SIMPLE))
461 != LDAP_SUCCESS)
462 {
463 /* Invalid credentials when just checking credentials returns FAIL. This
464 stops any further servers being tried. */
465
466 if (search_type == SEARCH_LDAP_AUTH && rc == LDAP_INVALID_CREDENTIALS)
467 {
468 DEBUG(D_lookup)
469 debug_printf("Invalid credentials: ldapauth returns FAIL\n");
470 error_yield = FAIL;
471 goto RETURN_ERROR_NOMSG;
472 }
473
474 /* Otherwise we have a problem that doesn't stop further servers from being
475 tried. */
476
477 *errmsg = string_sprintf("failed to bind the LDAP connection to server "
478 "%s%s - LDAP error %d: %s", host, porttext, rc, ldap_err2string(rc));
479 goto RETURN_ERROR;
480 }
481
482 /* Successful bind */
483
484 lcp->bound = TRUE;
485 lcp->user = (user == NULL)? NULL : string_copy(user);
486 lcp->password = (password == NULL)? NULL : string_copy(password);
487 }
488
489/* If we are just checking credentials, return OK. */
490
491if (search_type == SEARCH_LDAP_AUTH)
492 {
493 DEBUG(D_lookup) debug_printf("Bind succeeded: ldapauth returns OK\n");
494 goto RETURN_OK;
495 }
496
497/* Before doing the search, set the time and size limits (if given). Here again
498the different implementations of LDAP have chosen to do things differently. */
499
500#if defined(LDAP_OPT_SIZELIMIT)
501ldap_set_option(lcp->ld, LDAP_OPT_SIZELIMIT, (void *)&sizelimit);
502ldap_set_option(lcp->ld, LDAP_OPT_TIMELIMIT, (void *)&timelimit);
503#else
504lcp->ld->ld_sizelimit = sizelimit;
505lcp->ld->ld_timelimit = timelimit;
506#endif
507
508/* Similarly for dereferencing aliases. Don't know if this is possible on
509an LDAP library without LDAP_OPT_DEREF. */
510
511#if defined(LDAP_OPT_DEREF)
512ldap_set_option(lcp->ld, LDAP_OPT_DEREF, (void *)&dereference);
513#endif
514
515/* Start the search on the server. */
516
517DEBUG(D_lookup) debug_printf("Start search\n");
518
519msgid = ldap_search(lcp->ld, ludp->lud_dn, ludp->lud_scope, ludp->lud_filter,
520 ludp->lud_attrs, 0);
521
522if (msgid == -1)
523 {
524 *errmsg = string_sprintf("ldap search initiation failed");
525 goto RETURN_ERROR;
526 }
527
528/* Loop to pick up results as they come in, setting a timeout if one was
529given. */
530
531if (timelimit > 0)
532 {
533 timeout.tv_sec = timelimit;
534 timeout.tv_usec = 0;
535 timeoutptr = &timeout;
536 }
537
538while ((rc = ldap_result(lcp->ld, msgid, 0, timeoutptr, &result)) ==
539 LDAP_RES_SEARCH_ENTRY)
540 {
541 LDAPMessage *e;
542
543 DEBUG(D_lookup) debug_printf("ldap_result loop\n");
544
545 for(e = ldap_first_entry(lcp->ld, result);
546 e != NULL;
547 e = ldap_next_entry(lcp->ld, e))
548 {
549 uschar *new_dn;
550 BOOL insert_space = FALSE;
551
552 DEBUG(D_lookup) debug_printf("LDAP entry loop\n");
553
554 rescount++; /* Count results */
555
556 /* Results for multiple entries values are separated by newlines. */
557
558 if (data != NULL) data = string_cat(data, &size, &ptr, US"\n", 1);
559
560 /* Get the DN from the last result. */
561
562 new_dn = US ldap_get_dn(lcp->ld, e);
563 if (new_dn != NULL)
564 {
565 if (dn != NULL)
566 {
567 #if defined LDAP_LIB_NETSCAPE || defined LDAP_LIB_OPENLDAP2
568 ldap_memfree(dn);
569 #else /* OPENLDAP 1, UMich, Solaris */
570 free(dn);
571 #endif
572 }
573 /* Save for later */
574 dn = new_dn;
575 }
576
577 /* If the data we want is actually the DN rather than any attribute values,
578 (an "ldapdn" search) add it to the data string. If there are multiple
579 entries, the DNs will be concatenated, but we test for this case below, as
580 for SEARCH_LDAP_SINGLE, and give an error. */
581
582 if (search_type == SEARCH_LDAP_DN) /* Do not amalgamate these into one */
583 { /* condition, because of the else */
584 if (new_dn != NULL) /* below, that's for the first only */
585 {
586 data = string_cat(data, &size, &ptr, new_dn, Ustrlen(new_dn));
587 data[ptr] = 0;
588 attribute_found = TRUE;
589 }
590 }
591
592 /* Otherwise, loop through the entry, grabbing attribute values. If there's
593 only one attribute being retrieved, no attribute name is given, and the
594 result is not quoted. Multiple values are separated by (comma, space).
595 If more than one attribute is being retrieved, the data is given as a
596 sequence of name=value pairs, with the value always in quotes. If there are
597 multiple values, they are given within the quotes, comma separated. */
598
599 else for (attr = US ldap_first_attribute(lcp->ld, e, &ber);
600 attr != NULL;
601 attr = US ldap_next_attribute(lcp->ld, e, ber))
602 {
603 if (attr[0] != 0)
604 {
605 /* Get array of values for this attribute. */
606
607 if ((firstval = values = USS ldap_get_values(lcp->ld, e, CS attr))
608 != NULL)
609 {
610 if (attr_count != 1)
611 {
612 if (insert_space)
613 data = string_cat(data, &size, &ptr, US" ", 1);
614 else
615 insert_space = TRUE;
616 data = string_cat(data, &size, &ptr, attr, Ustrlen(attr));
617 data = string_cat(data, &size, &ptr, US"=\"", 2);
618 }
619
620 while (*values != NULL)
621 {
622 uschar *value = *values;
623 int len = Ustrlen(value);
624
625 DEBUG(D_lookup) debug_printf("LDAP attr loop %s:%s\n", attr, value);
626
627 if (values != firstval)
628 data = string_cat(data, &size, &ptr, US", ", 2);
629
630 /* For multiple attributes, the data is in quotes. We must escape
631 internal quotes, backslashes, newlines. */
632
633 if (attr_count != 1)
634 {
635 int j;
636 for (j = 0; j < len; j++)
637 {
638 if (value[j] == '\n')
639 data = string_cat(data, &size, &ptr, US"\\n", 2);
640 else
641 {
642 if (value[j] == '\"' || value[j] == '\\')
643 data = string_cat(data, &size, &ptr, US"\\", 1);
644 data = string_cat(data, &size, &ptr, value+j, 1);
645 }
646 }
647 }
648
649 /* For single attributes, copy the value verbatim */
650
651 else data = string_cat(data, &size, &ptr, value, len);
652
653 /* Move on to the next value */
654
655 values++;
656 attribute_found = TRUE;
657 }
658
659 /* Closing quote at the end of the data for a named attribute. */
660
661 if (attr_count != 1)
662 data = string_cat(data, &size, &ptr, US"\"", 1);
663
664 /* Free the values */
665
666 ldap_value_free(CSS firstval);
667 }
668 }
669
670 #if defined LDAP_LIB_NETSCAPE || defined LDAP_LIB_OPENLDAP2
671
672 /* Netscape and OpenLDAP2 LDAP's attrs are dynamically allocated and need
673 to be freed. UMich LDAP stores them in static storage and does not require
674 this. */
675
676 ldap_memfree(attr);
677 #endif
678 } /* End "for" loop for extracting attributes from an entry */
679 } /* End "for" loop for extracting entries from a result */
680
681 /* Free the result */
682
683 ldap_msgfree(result);
684 result = NULL;
685 } /* End "while" loop for multiple results */
686
687/* Terminate the dynamic string that we have built and reclaim unused store */
688
689if (data != NULL)
690 {
691 data[ptr] = 0;
692 store_reset(data + ptr + 1);
693 }
694
695/* Copy the last dn into eldap_dn */
696
697if (dn != NULL)
698 {
699 eldap_dn = string_copy(dn);
700 #if defined LDAP_LIB_NETSCAPE || defined LDAP_LIB_OPENLDAP2
701 ldap_memfree(dn);
702 #else /* OPENLDAP 1, UMich, Solaris */
703 free(dn);
704 #endif
705 }
706
707DEBUG(D_lookup) debug_printf("search ended by ldap_result yielding %d\n",rc);
708
709if (rc == 0)
710 {
711 *errmsg = US"ldap_result timed out";
712 goto RETURN_ERROR;
713 }
714
715/* A return code of -1 seems to mean "ldap_result failed internally or couldn't
716provide you with a message". Other error states seem to exist where
717ldap_result() didn't give us any message from the server at all, leaving result
718set to NULL. Apparently, "the error parameters of the LDAP session handle will
719be set accordingly". That's the best we can do to retrieve an error status; we
720can't use functions like ldap_result2error because they parse a message from
721the server, which we didn't get.
722
723Annoyingly, the different implementations of LDAP have gone for different
724methods of handling error codes and generating error messages. */
725
726if (rc == -1 || result == NULL)
727 {
728 int err;
729 DEBUG(D_lookup) debug_printf("ldap_result failed\n");
730
731 #if defined LDAP_LIB_SOLARIS || defined LDAP_LIB_OPENLDAP2
732 ldap_get_option(lcp->ld, LDAP_OPT_ERROR_NUMBER, &err);
733 *errmsg = string_sprintf("ldap_result failed: %d, %s",
734 err, ldap_err2string(err));
735
736 #elif defined LDAP_LIB_NETSCAPE
737 /* Dubious (surely 'matched' is spurious here?) */
738 (void)ldap_get_lderrno(lcp->ld, &matched, &error1);
739 *errmsg = string_sprintf("ldap_result failed: %s (%s)", error1, matched);
740
741 #else /* UMich LDAP aka OpenLDAP 1.x */
742 *errmsg = string_sprintf("ldap_result failed: %d, %s",
743 lcp->ld->ld_errno, ldap_err2string(lcp->ld->ld_errno));
744 #endif
745
746 goto RETURN_ERROR;
747 }
748
749/* A return code that isn't -1 doesn't necessarily mean there were no problems
750with the search. The message must be an LDAP_RES_SEARCH_RESULT or else it's
751something we can't handle. */
752
753if (rc != LDAP_RES_SEARCH_RESULT)
754 {
755 *errmsg = string_sprintf("ldap_result returned unexpected code %d", rc);
756 goto RETURN_ERROR;
757 }
758
759/* We have a result message from the server. This doesn't yet mean all is well.
760We need to parse the message to find out exactly what's happened. */
761
762 #if defined LDAP_LIB_SOLARIS || defined LDAP_LIB_OPENLDAP2
763 if (ldap_parse_result(lcp->ld, result, &rc, CSS &matched, CSS &error2, NULL,
764 NULL, 0) < 0)
765 {
766 *errmsg = US"ldap_parse_result failed";
767 goto RETURN_ERROR;
768 }
769 error1 = US ldap_err2string(rc);
770
771#elif defined LDAP_LIB_NETSCAPE
772 /* Dubious (it doesn't reference 'result' at all!) */
773 rc = ldap_get_lderrno(lcp->ld, &matched, &error1);
774
775#else /* UMich LDAP aka OpenLDAP 1.x */
776 rc = ldap_result2error(lcp->ld, result, 0);
777 error1 = ldap_err2string(rc);
778 error2 = lcp->ld->ld_error;
779 matched = lcp->ld->ld_matched;
780#endif
781
782/* Process the status as follows:
783
784 (1) If we get LDAP_SIZELIMIT_EXCEEDED, just carry on, to return the
785 truncated result list.
786
787 (2) The range of errors defined by LDAP_NAME_ERROR generally mean "that
788 object does not, or cannot, exist in the database". For those cases we
789 fail the lookup.
790
791 (3) All other non-successes here are treated as some kind of problem with
792 the lookup, so return DEFER (which is the default in error_yield).
793*/
794
795DEBUG(D_lookup) debug_printf("ldap_parse_result yielded %d: %s\n",
796 rc, ldap_err2string(rc));
797
798if (rc != LDAP_SUCCESS && rc != LDAP_SIZELIMIT_EXCEEDED)
799 {
800 *errmsg = string_sprintf("LDAP search failed - error %d: %s%s%s%s%s",
801 rc,
802 (error1 != NULL)? error1 : US"",
803 (error2 != NULL && error2[0] != 0)? US"/" : US"",
804 (error2 != NULL)? error2 : US"",
805 (matched != NULL && matched[0] != 0)? US"/" : US"",
806 (matched != NULL)? matched : US"");
807
808 #if defined LDAP_NAME_ERROR
809 if (LDAP_NAME_ERROR(rc))
810 #elif defined NAME_ERROR /* OPENLDAP1 calls it this */
811 if (NAME_ERROR(rc))
812 #else
813 if (rc == LDAP_NO_SUCH_OBJECT)
814 #endif
815
816 {
817 DEBUG(D_lookup) debug_printf("lookup failure forced\n");
818 error_yield = FAIL;
819 }
820 goto RETURN_ERROR;
821 }
822
823/* The search succeeded. Check if we have too many results */
824
825if (search_type != SEARCH_LDAP_MULTIPLE && rescount > 1)
826 {
827 *errmsg = string_sprintf("LDAP search: more than one entry (%d) was returned "
828 "(filter not specific enough?)", rescount);
829 goto RETURN_ERROR_BREAK;
830 }
831
832/* Check if we have too few (zero) entries */
833
834if (rescount < 1)
835 {
836 *errmsg = string_sprintf("LDAP search: no results");
837 error_yield = FAIL;
838 goto RETURN_ERROR_BREAK;
839 }
840
841/* If an entry was found, but it had no attributes, we behave as if no entries
842were found, that is, the lookup failed. */
843
844if (!attribute_found)
845 {
846 *errmsg = US"LDAP search: found no attributes";
847 error_yield = FAIL;
848 goto RETURN_ERROR;
849 }
850
851/* Otherwise, it's all worked */
852
853DEBUG(D_lookup) debug_printf("LDAP search: returning: %s\n", data);
854*res = data;
855
856RETURN_OK:
857if (result != NULL) ldap_msgfree(result);
858ldap_free_urldesc(ludp);
859return OK;
860
861/* Error returns */
862
863RETURN_ERROR_BREAK:
864*defer_break = TRUE;
865
866RETURN_ERROR:
867DEBUG(D_lookup) debug_printf("%s\n", *errmsg);
868
869RETURN_ERROR_NOMSG:
870if (result != NULL) ldap_msgfree(result);
871if (ludp != NULL) ldap_free_urldesc(ludp);
872
873#if defined LDAP_LIB_OPENLDAP2
874 if (error2 != NULL) ldap_memfree(error2);
875 if (matched != NULL) ldap_memfree(matched);
876#endif
877
878return error_yield;
879}
880
881
882
883/*************************************************
884* Internal search control function *
885*************************************************/
886
887/* This function is called from eldap_find(), eldapauth_find(), eldapdn_find(),
888and eldapm_find() with a difference in the "search_type" argument. It controls
889calls to perform_ldap_search() which actually does the work. We call that
890repeatedly for certain types of defer in the case when the URL contains no host
891name and eldap_default_servers is set to a list of servers to try. This gives
892more control than just passing over a list of hosts to ldap_open() because it
893handles other kinds of defer as well as just a failure to open. Note that the
894URL is defined to contain either zero or one "hostport" only.
895
896Parameter data in addition to the URL can be passed as preceding text in the
897string, as items of the form XXX=yyy. The URL itself can be detected because it
898must begin "ldapx://", where x is empty, s, or i.
899
900Arguments:
901 ldap_url the URL to be looked up, optionally preceded by other parameter
902 settings
903 search_type SEARCH_LDAP_MULTIPLE allows values from multiple entries
904 SEARCH_LDAP_SINGLE allows values from one entry only
905 SEARCH_LDAP_DN gets the DN from one entry
906 res set to point at the result
907 errmsg set to point a message if result is not OK
908
909Returns: OK or FAIL or DEFER
910*/
911
912static int
913control_ldap_search(uschar *ldap_url, int search_type, uschar **res,
914 uschar **errmsg)
915{
916BOOL defer_break = FALSE;
917int timelimit = LDAP_NO_LIMIT;
918int sizelimit = LDAP_NO_LIMIT;
919int tcplimit = LDAP_X_IO_TIMEOUT_NO_TIMEOUT;
920int dereference = LDAP_DEREF_NEVER;
921int sep = 0;
922uschar *url = ldap_url;
923uschar *p;
924uschar *user = NULL;
925uschar *password = NULL;
926uschar *server, *list;
927uschar buffer[512];
928
929while (isspace(*url)) url++;
930
931/* Until the string begins "ldap", search for the other parameter settings that
932are recognized. They are of the form NAME=VALUE, with the value being
933optionally double-quoted. There must still be a space after it, however. No
934NAME has the value "ldap". */
935
936while (strncmpic(url, US"ldap", 4) != 0)
937 {
938 uschar *name = url;
939 while (*url != 0 && *url != '=') url++;
940 if (*url == '=')
941 {
942 int namelen;
943 uschar *value;
944 namelen = ++url - name;
945 value = string_dequote(&url);
946 if (isspace(*url))
947 {
948 if (strncmpic(name, US"USER=", namelen) == 0) user = value;
949 else if (strncmpic(name, US"PASS=", namelen) == 0) password = value;
950 else if (strncmpic(name, US"SIZE=", namelen) == 0) sizelimit = Uatoi(value);
951 else if (strncmpic(name, US"TIME=", namelen) == 0) timelimit = Uatoi(value);
952 else if (strncmpic(name, US"CONNECT=", namelen) == 0) tcplimit = Uatoi(value) * 1000;
953
954 /* Don't know if all LDAP libraries have LDAP_OPT_DEREF */
955
956 #ifdef LDAP_OPT_DEREF
957 else if (strncmpic(name, US"DEREFERENCE=", namelen) == 0)
958 {
959 if (strcmpic(value, US"never") == 0) dereference = LDAP_DEREF_NEVER;
960 else if (strcmpic(value, US"searching") == 0)
961 dereference = LDAP_DEREF_SEARCHING;
962 else if (strcmpic(value, US"finding") == 0)
963 dereference = LDAP_DEREF_FINDING;
964 if (strcmpic(value, US"always") == 0) dereference = LDAP_DEREF_ALWAYS;
965 }
966 #else
967 else if (strncmpic(name, US"DEREFERENCE=", namelen) == 0)
968 {
969 *errmsg = string_sprintf("LDAP_OP_DEREF not defined in this LDAP "
970 "library - cannot use \"dereference\"");
971 DEBUG(D_lookup) debug_printf("%s\n", *errmsg);
972 return DEFER;
973 }
974
975 #endif
976
977 else
978 {
979 *errmsg =
980 string_sprintf("unknown parameter \"%.*s\" precedes LDAP URL",
981 namelen, name);
982 DEBUG(D_lookup) debug_printf("LDAP query error: %s\n", *errmsg);
983 return DEFER;
984 }
985 while (isspace(*url)) url++;
986 continue;
987 }
988 }
989 *errmsg = US"malformed parameter setting precedes LDAP URL";
990 DEBUG(D_lookup) debug_printf("LDAP query error: %s\n", *errmsg);
991 return DEFER;
992 }
993
994/* If user is set, de-URL-quote it. Some LDAP libraries do this for themselves,
995but it seems that not all behave like this. The DN for the user is often the
996result of ${quote_ldap_dn:...} quoting, which does apply URL quoting, because
997that is needed when the DN is used as a base DN in a query. Sigh. This is all
998far too complicated. */
999
1000if (user != NULL)
1001 {
1002 uschar *s;
1003 uschar *t = user;
1004 for (s = user; *s != 0; s++)
1005 {
1006 int c, d;
1007 if (*s == '%' && isxdigit(c=s[1]) && isxdigit(d=s[2]))
1008 {
1009 c = tolower(c);
1010 d = tolower(d);
1011 *t++ =
1012 (((c >= 'a')? (10 + c - 'a') : c - '0') << 4) |
1013 ((d >= 'a')? (10 + d - 'a') : d - '0');
1014 s += 2;
1015 }
1016 else *t++ = *s;
1017 }
1018 *t = 0;
1019 }
1020
1021DEBUG(D_lookup)
1022 debug_printf("LDAP parameters: user=%s pass=%s size=%d time=%d connect=%d "
1023 "dereference=%d\n", user, password, sizelimit, timelimit, tcplimit,
1024 dereference);
1025
1026/* If the request is just to check authentication, some credentials must
1027be given. The password must not be empty because LDAP binds with an empty
1028password are considered anonymous, and will succeed on most installations. */
1029
1030if (search_type == SEARCH_LDAP_AUTH)
1031 {
1032 if (user == NULL || password == NULL)
1033 {
1034 *errmsg = US"ldapauth lookups must specify the username and password";
1035 return DEFER;
1036 }
1037 if (password[0] == 0)
1038 {
1039 DEBUG(D_lookup) debug_printf("Empty password: ldapauth returns FAIL\n");
1040 return FAIL;
1041 }
1042 }
1043
1044/* Check for valid ldap url starters */
1045
1046p = url + 4;
1047if (tolower(*p) == 's' || tolower(*p) == 'i') p++;
1048if (Ustrncmp(p, "://", 3) != 0)
1049 {
1050 *errmsg = string_sprintf("LDAP URL does not start with \"ldap://\", "
1051 "\"ldaps://\", or \"ldapi://\" (it starts with \"%.16s...\")", url);
1052 DEBUG(D_lookup) debug_printf("LDAP query error: %s\n", *errmsg);
1053 return DEFER;
1054 }
1055
1056/* No default servers, or URL contains a server name: just one attempt */
1057
1058if (eldap_default_servers == NULL || p[3] != '/')
1059 {
1060 return perform_ldap_search(url, NULL, 0, search_type, res, errmsg,
1061 &defer_break, user, password, sizelimit, timelimit, tcplimit, dereference);
1062 }
1063
1064/* Loop through the default servers until OK or FAIL */
1065
1066list = eldap_default_servers;
1067while ((server = string_nextinlist(&list, &sep, buffer, sizeof(buffer))) != NULL)
1068 {
1069 int rc;
1070 int port = 0;
1071 uschar *colon = Ustrchr(server, ':');
1072 if (colon != NULL)
1073 {
1074 *colon = 0;
1075 port = Uatoi(colon+1);
1076 }
1077 rc = perform_ldap_search(url, server, port, search_type, res, errmsg,
1078 &defer_break, user, password, sizelimit, timelimit, tcplimit, dereference);
1079 if (rc != DEFER || defer_break) return rc;
1080 }
1081
1082return DEFER;
1083}
1084
1085
1086
1087/*************************************************
1088* Find entry point *
1089*************************************************/
1090
1091/* See local README for interface description. The different kinds of search
1092are handled by a common function, with a flag to differentiate between them.
1093The handle and filename arguments are not used. */
1094
1095int
1096eldap_find(void *handle, uschar *filename, uschar *ldap_url, int length,
1097 uschar **result, uschar **errmsg, BOOL *do_cache)
1098{
1099/* Keep picky compilers happy */
1100do_cache = do_cache;
1101return(control_ldap_search(ldap_url, SEARCH_LDAP_SINGLE, result, errmsg));
1102}
1103
1104int
1105eldapm_find(void *handle, uschar *filename, uschar *ldap_url, int length,
1106 uschar **result, uschar **errmsg, BOOL *do_cache)
1107{
1108/* Keep picky compilers happy */
1109do_cache = do_cache;
1110return(control_ldap_search(ldap_url, SEARCH_LDAP_MULTIPLE, result, errmsg));
1111}
1112
1113int
1114eldapdn_find(void *handle, uschar *filename, uschar *ldap_url, int length,
1115 uschar **result, uschar **errmsg, BOOL *do_cache)
1116{
1117/* Keep picky compilers happy */
1118do_cache = do_cache;
1119return(control_ldap_search(ldap_url, SEARCH_LDAP_DN, result, errmsg));
1120}
1121
1122int
1123eldapauth_find(void *handle, uschar *filename, uschar *ldap_url, int length,
1124 uschar **result, uschar **errmsg, BOOL *do_cache)
1125{
1126/* Keep picky compilers happy */
1127do_cache = do_cache;
1128return(control_ldap_search(ldap_url, SEARCH_LDAP_AUTH, result, errmsg));
1129}
1130
1131
1132
1133/*************************************************
1134* Open entry point *
1135*************************************************/
1136
1137/* See local README for interface description. */
1138
1139void *
1140eldap_open(uschar *filename, uschar **errmsg)
1141{
1142return (void *)(1); /* Just return something non-null */
1143}
1144
1145
1146
1147/*************************************************
1148* Tidy entry point *
1149*************************************************/
1150
1151/* See local README for interface description.
1152Make sure that eldap_dn does not refer to reclaimed or worse, freed store */
1153
1154void
1155eldap_tidy(void)
1156{
1157LDAP_CONNECTION *lcp = NULL;
1158eldap_dn = NULL;
1159
1160while ((lcp = ldap_connections) != NULL)
1161 {
1162 DEBUG(D_lookup) debug_printf("unbind LDAP connection to %s:%d\n", lcp->host,
1163 lcp->port);
1164 ldap_unbind(lcp->ld);
1165 ldap_connections = lcp->next;
1166 }
1167}
1168
1169
1170
1171/*************************************************
1172* Quote entry point *
1173*************************************************/
1174
1175/* LDAP quoting is unbelievably messy. For a start, two different levels of
1176quoting have to be done: LDAP quoting, and URL quoting. The current
1177specification is the result of a suggestion by Brian Candler. It recognizes
1178two separate cases:
1179
1180(1) For text that appears in a search filter, the following escapes are
1181 required (see RFC 2254):
1182
1183 * -> \2A
1184 ( -> \28
1185 ) -> \29
1186 \ -> \5C
1187 NULL -> \00
1188
1189 Then the entire filter text must be URL-escaped. This kind of quoting is
1190 implemented by ${quote_ldap:....}. Note that we can never have a NULL
1191 in the input string, because that's a terminator.
1192
1193(2) For a DN that is part of a URL (i.e. the base DN), the characters
1194
1195 , + " \ < > ;
1196
1197 must be quoted by backslashing. See RFC 2253. Leading and trailing spaces
1198 must be escaped, as must a leading #. Then the string must be URL-quoted.
1199 This type of quoting is implemented by ${quote_ldap_dn:....}.
1200
1201For URL quoting, the only characters that need not be quoted are the
1202alphamerics and
1203
1204 ! $ ' ( ) * + - . _
1205
1206All the others must be hexified and preceded by %. This includes the
1207backslashes used for LDAP quoting.
1208
1209For a DN that is given in the USER parameter for authentication, we need the
1210same initial quoting as (2) but in this case, the result must NOT be
1211URL-escaped, because it isn't a URL. The way this is handled is by
1212de-URL-quoting the text when processing the USER parameter in
1213control_ldap_search() above. That means that the same quote operator can be
1214used. This has the additional advantage that spaces in the DN won't cause
1215parsing problems. For example:
1216
1217 USER=cn=${quote_ldap_dn:$1},%20dc=example,%20dc=com
1218
1219should be safe if there are spaces in $1.
1220
1221
1222Arguments:
1223 s the string to be quoted
1224 opt additional option text or NULL if none
1225 only "dn" is recognized
1226
1227Returns: the processed string or NULL for a bad option
1228*/
1229
1230
1231
1232/* The characters in this string, together with alphanumerics, never need
1233quoting in any way. */
1234
1235#define ALWAYS_LITERAL "!$'-._"
1236
1237/* The special characters in this string do not need to be URL-quoted. The set
1238is a bit larger than the general literals. */
1239
1240#define URL_NONQUOTE ALWAYS_LITERAL "()*+"
1241
1242/* The following macros define the characters that are quoted by quote_ldap and
1243quote_ldap_dn, respectively. */
1244
1245#define LDAP_QUOTE "*()\\"
1246#define LDAP_DN_QUOTE ",+\"\\<>;"
1247
1248
1249
1250uschar *
1251eldap_quote(uschar *s, uschar *opt)
1252{
1253register int c;
1254int count = 0;
1255int len = 0;
1256BOOL dn = FALSE;
1257uschar *t = s;
1258uschar *quoted;
1259
1260/* Test for a DN quotation. */
1261
1262if (opt != NULL)
1263 {
1264 if (Ustrcmp(opt, "dn") != 0) return NULL; /* No others recognized */
1265 dn = TRUE;
1266 }
1267
1268/* Compute how much extra store we need for the string. This doesn't have to be
1269exact as long as it isn't an underestimate. The worst case is the addition of 5
1270extra bytes for a single character. This occurs for certain characters in DNs,
1271where, for example, < turns into %5C%3C. For simplicity, we just add 5 for each
1272possibly escaped character. The really fast way would be just to test for
1273non-alphanumerics, but it is probably better to spot a few others that are
1274never escaped, because if there are no specials at all, we can avoid copying
1275the string. */
1276
1277while ((c = *t++) != 0)
1278 {
1279 len++;
1280 if (!isalnum(c) && Ustrchr(ALWAYS_LITERAL, c) == NULL) count += 5;
1281 }
1282if (count == 0) return s;
1283
1284/* Get sufficient store to hold the quoted string */
1285
1286t = quoted = store_get(len + count + 1);
1287
1288/* Handle plain quote_ldap */
1289
1290if (!dn)
1291 {
1292 while ((c = *s++) != 0)
1293 {
1294 if (!isalnum(c))
1295 {
1296 if (Ustrchr(LDAP_QUOTE, c) != NULL)
1297 {
1298 sprintf(CS t, "%%5C%02X", c); /* e.g. * => %5C2A */
1299 t += 5;
1300 continue;
1301 }
1302 if (Ustrchr(URL_NONQUOTE, c) == NULL) /* e.g. ] => %5D */
1303 {
1304 sprintf(CS t, "%%%02X", c);
1305 t += 3;
1306 continue;
1307 }
1308 }
1309 *t++ = c; /* unquoted character */
1310 }
1311 }
1312
1313/* Handle quote_ldap_dn */
1314
1315else
1316 {
1317 uschar *ss = s + len;
1318
1319 /* Find the last char before any trailing spaces */
1320
1321 while (ss > s && ss[-1] == ' ') ss--;
1322
1323 /* Quote leading spaces and sharps */
1324
1325 for (; s < ss; s++)
1326 {
1327 if (*s != ' ' && *s != '#') break;
1328 sprintf(CS t, "%%5C%%%02X", *s);
1329 t += 6;
1330 }
1331
1332 /* Handle the rest of the string, up to the trailing spaces */
1333
1334 while (s < ss)
1335 {
1336 c = *s++;
1337 if (!isalnum(c))
1338 {
1339 if (Ustrchr(LDAP_DN_QUOTE, c) != NULL)
1340 {
1341 Ustrncpy(t, "%5C", 3); /* insert \ where needed */
1342 t += 3; /* fall through to check URL */
1343 }
1344 if (Ustrchr(URL_NONQUOTE, c) == NULL) /* e.g. ] => %5D */
1345 {
1346 sprintf(CS t, "%%%02X", c);
1347 t += 3;
1348 continue;
1349 }
1350 }
1351 *t++ = c; /* unquoted character, or non-URL quoted after %5C */
1352 }
1353
1354 /* Handle the trailing spaces */
1355
1356 while (*ss++ != 0)
1357 {
1358 Ustrncpy(t, "%5C%20", 6);
1359 t += 6;
1360 }
1361 }
1362
1363/* Terminate the new string and return */
1364
1365*t = 0;
1366return quoted;
1367}
1368
1369#endif /* LOOKUP_LDAP */
1370
1371/* End of lookups/ldap.c */