added support for CA cert verification;
[platform/upstream/curl.git] / lib / ldap.c
1 /***************************************************************************
2  *                      _   _ ____  _
3  *  Project         ___| | | |  _ \| |
4  *                 / __| | | | |_) | |
5  *                | (__| |_| |  _ <| |___
6  *                 \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2007, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at http://curl.haxx.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  * $Id$
22  ***************************************************************************/
23
24 #include "setup.h"
25
26 #ifndef CURL_DISABLE_LDAP
27 /* -- WIN32 approved -- */
28 #include <stdio.h>
29 #include <string.h>
30 #include <stdarg.h>
31 #include <stdlib.h>
32 #include <ctype.h>
33 #ifdef NEED_MALLOC_H
34 #include <malloc.h>
35 #endif
36 #include <errno.h>
37
38 #ifdef CURL_LDAP_HYBRID         /* If W$ definitions are needed. */
39 # include <windows.h>
40   /* Remember we are NOT in a W$ compiler! */
41 # undef WIN32
42 # undef _WIN32
43 # undef __WIN32__
44 #endif
45
46 #ifdef CURL_LDAP_WIN            /* Use W$ LDAP implementation. */
47 # include <winldap.h>
48 #else
49 #define LDAP_DEPRECATED 1       /* Be sure ldap_init() is defined. */
50 # include <ldap.h>
51 #if (defined(HAVE_LDAP_SSL) && defined(HAVE_LDAP_SSL_H))
52 # include <ldap_ssl.h>
53 #endif /* HAVE_LDAP_SSL && HAVE_LDAP_SSL_H */
54 #endif
55
56 #ifdef HAVE_UNISTD_H
57 # include <unistd.h>
58 #endif
59
60 #include "urldata.h"
61 #include <curl/curl.h>
62 #include "sendf.h"
63 #include "escape.h"
64 #include "transfer.h"
65 #include "strequal.h"
66 #include "strtok.h"
67 #include "curl_ldap.h"
68 #include "memory.h"
69 #include "base64.h"
70
71 #define _MPRINTF_REPLACE /* use our functions only */
72 #include <curl/mprintf.h>
73
74 #include "memdebug.h"
75
76 #ifndef HAVE_LDAP_URL_PARSE
77
78 /* Use our own implementation. */
79
80 typedef struct {
81     char   *lud_host;
82     int     lud_port;
83     char   *lud_dn;
84     char  **lud_attrs;
85     int     lud_scope;
86     char   *lud_filter;
87     char  **lud_exts;
88 } CURL_LDAPURLDesc;
89
90 #undef LDAPURLDesc
91 #define LDAPURLDesc             CURL_LDAPURLDesc
92
93 static int  _ldap_url_parse (const struct connectdata *conn,
94                              LDAPURLDesc **ludp);
95 static void _ldap_free_urldesc (LDAPURLDesc *ludp);
96
97 #undef ldap_free_urldesc
98 #define ldap_free_urldesc       _ldap_free_urldesc
99 #endif
100
101 #ifdef DEBUG_LDAP
102   #define LDAP_TRACE(x)   do { \
103                             _ldap_trace ("%u: ", __LINE__); \
104                             _ldap_trace x; \
105                           } while (0)
106
107   static void _ldap_trace (const char *fmt, ...);
108 #else
109   #define LDAP_TRACE(x)   ((void)0)
110 #endif
111
112
113 CURLcode Curl_ldap(struct connectdata *conn, bool *done)
114 {
115   CURLcode status = CURLE_OK;
116   int rc = 0;
117   LDAP *server = NULL;
118   LDAPURLDesc *ludp = NULL;
119   LDAPMessage *result = NULL;
120   LDAPMessage *entryIterator;
121   int num = 0;
122   struct SessionHandle *data=conn->data;
123   int ldap_proto;
124   int ldap_ssl = 0;
125   char *val_b64;
126   size_t val_b64_sz;
127 #ifdef LDAP_OPT_NETWORK_TIMEOUT
128   struct timeval ldap_timeout = {10,0}; /* 10 sec connection/search timeout */
129 #endif
130
131   *done = TRUE; /* unconditionally */
132   infof(data, "LDAP local: LDAP Vendor = %s ; LDAP Version = %d\n",
133           LDAP_VENDOR_NAME, LDAP_VENDOR_VERSION);
134   infof(data, "LDAP local: %s\n", data->change.url);
135
136 #ifdef HAVE_LDAP_URL_PARSE
137   rc = ldap_url_parse(data->change.url, &ludp);
138 #else
139   rc = _ldap_url_parse(conn, &ludp);
140 #endif
141   if (rc != 0) {
142     failf(data, "LDAP local: %s", ldap_err2string(rc));
143     status = CURLE_LDAP_INVALID_URL;
144     goto quit;
145   }
146
147   /* Get the URL scheme ( either ldap or ldaps ) */
148   if (strequal(conn->protostr, "LDAPS"))
149     ldap_ssl = 1;
150   infof(data, "LDAP local: trying to establish %s connection\n",
151           ldap_ssl ? "encrypted" : "cleartext");
152
153 #ifdef LDAP_OPT_NETWORK_TIMEOUT
154   ldap_set_option(NULL, LDAP_OPT_NETWORK_TIMEOUT, &ldap_timeout);
155 #endif
156   ldap_proto = LDAP_VERSION3;
157   ldap_set_option(NULL, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto);
158
159   if (ldap_ssl) {
160 #ifdef HAVE_LDAP_SSL
161 #ifdef CURL_LDAP_WIN
162     /* Win32 LDAP SDK doesnt support insecure mode without CA! */
163     server = ldap_sslinit(conn->host.name, (int)conn->port, 1);
164     ldap_set_option(server, LDAP_OPT_SSL, LDAP_OPT_ON);
165 #else
166     int ldap_option;
167     char* ldap_ca = data->set.str[STRING_SSL_CAFILE];
168 #if defined(CURL_HAS_NOVELL_LDAPSDK)
169     rc = ldapssl_client_init(NULL, NULL);
170     if (rc != LDAP_SUCCESS) {
171       failf(data, "LDAP local: ldapssl_client_init %s", ldap_err2string(rc));
172       status = CURLE_SSL_CERTPROBLEM;
173       goto quit;
174     }
175     if (data->set.ssl.verifypeer) {
176       /* Novell SDK supports DER or BASE64 files. */
177       int cert_type = LDAPSSL_CERT_FILETYPE_B64;
178       if ((data->set.str[STRING_CERT_TYPE]) &&
179               (strequal(data->set.str[STRING_CERT_TYPE], "DER")))
180         cert_type = LDAPSSL_CERT_FILETYPE_DER;
181       if (!ldap_ca) {
182         failf(data, "LDAP local: ERROR %s CA cert not set!",
183               (cert_type == LDAPSSL_CERT_FILETYPE_DER ? "DER" : "PEM"));
184         status = CURLE_SSL_CERTPROBLEM;
185         goto quit;
186       }
187       infof(data, "LDAP local: using %s CA cert '%s'\n",
188               (cert_type == LDAPSSL_CERT_FILETYPE_DER ? "DER" : "PEM"),
189               ldap_ca);
190       rc = ldapssl_add_trusted_cert(ldap_ca, cert_type);
191       if (rc != LDAP_SUCCESS) {
192         failf(data, "LDAP local: ERROR setting %s CA cert: %s",
193                 (cert_type == LDAPSSL_CERT_FILETYPE_DER ? "DER" : "PEM"),
194                 ldap_err2string(rc));
195         status = CURLE_SSL_CERTPROBLEM;
196         goto quit;
197       }
198       ldap_option = LDAPSSL_VERIFY_SERVER;
199     } else {
200       ldap_option = LDAPSSL_VERIFY_NONE;
201     }
202     rc = ldapssl_set_verify_mode(ldap_option);
203     if (rc != LDAP_SUCCESS) {
204       failf(data, "LDAP local: ERROR setting cert verify mode: %s",
205               ldap_err2string(rc));
206       status = CURLE_SSL_CERTPROBLEM;
207       goto quit;
208     }
209     server = ldapssl_init(conn->host.name, (int)conn->port, 1);
210     if (server == NULL) {
211       failf(data, "LDAP local: Cannot connect to %s:%d",
212               conn->host.name, conn->port);
213       status = CURLE_COULDNT_CONNECT;
214       goto quit;
215     }
216 #elif defined(LDAP_OPT_X_TLS)
217     if (data->set.ssl.verifypeer) {
218       /* OpenLDAP SDK supports BASE64 files. */
219       if (!ldap_ca) {
220         failf(data, "LDAP local: ERROR PEM CA cert not set!");
221         status = CURLE_SSL_CERTPROBLEM;
222         goto quit;
223       }
224       infof(data, "LDAP local: using PEM CA cert: %s\n", ldap_ca);
225       rc = ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTFILE, ldap_ca);
226       if (rc != LDAP_SUCCESS) {
227         failf(data, "LDAP local: ERROR setting PEM CA cert: %s",
228                 ldap_err2string(rc));
229         status = CURLE_SSL_CERTPROBLEM;
230         goto quit;
231       }
232       ldap_option = LDAP_OPT_X_TLS_DEMAND;
233     } else {
234       ldap_option = LDAP_OPT_X_TLS_NEVER;
235     }
236     rc = ldap_set_option(NULL, LDAP_OPT_X_TLS_REQUIRE_CERT, &ldap_option);
237     if (rc != LDAP_SUCCESS) {
238       failf(data, "LDAP local: ERROR setting cert verify mode: %s",
239               ldap_err2string(rc));
240       status = CURLE_SSL_CERTPROBLEM;
241       goto quit;
242     }
243     server = ldap_init(conn->host.name, (int)conn->port);
244     if (server == NULL) {
245       failf(data, "LDAP local: Cannot connect to %s:%d",
246               conn->host.name, conn->port);
247       status = CURLE_COULDNT_CONNECT;
248       goto quit;
249     }
250     ldap_option = LDAP_OPT_X_TLS_HARD;
251     rc = ldap_set_option(server, LDAP_OPT_X_TLS, &ldap_option);
252     if (rc != LDAP_SUCCESS) {
253       failf(data, "LDAP local: ERROR setting SSL/TLS mode: %s",
254               ldap_err2string(rc));
255       status = CURLE_SSL_CERTPROBLEM;
256       goto quit;
257     }
258 /*
259     rc = ldap_start_tls_s(server, NULL, NULL);
260     if (rc != LDAP_SUCCESS) {
261       failf(data, "LDAP local: ERROR starting SSL/TLS mode: %s",
262               ldap_err2string(rc));
263       status = CURLE_SSL_CERTPROBLEM;
264       goto quit;
265     }
266 */
267 #else
268     /* we should probably never come up to here since configure
269        should check in first place if we can support LDAP SSL/TLS */
270     failf(data, "LDAP local: SSL/TLS not supported with this version "
271             "of the OpenLDAP toolkit\n");
272     status = CURLE_SSL_CERTPROBLEM;
273     goto quit;
274 #endif
275 #endif
276 #endif /* CURL_LDAP_USE_SSL */
277   } else {
278     server = ldap_init(conn->host.name, (int)conn->port);
279     if (server == NULL) {
280       failf(data, "LDAP local: Cannot connect to %s:%d",
281               conn->host.name, conn->port);
282       status = CURLE_COULDNT_CONNECT;
283       goto quit;
284     }
285   }
286
287   rc = ldap_simple_bind_s(server,
288                           conn->bits.user_passwd ? conn->user : NULL,
289                           conn->bits.user_passwd ? conn->passwd : NULL);
290   if (!ldap_ssl && rc != 0) {
291     ldap_proto = LDAP_VERSION2;
292     ldap_set_option(server, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto);
293     rc = ldap_simple_bind_s(server,
294                             conn->bits.user_passwd ? conn->user : NULL,
295                             conn->bits.user_passwd ? conn->passwd : NULL);
296   }
297   if (rc != 0) {
298      failf(data, "LDAP local: ldap_simple_bind_s %s", ldap_err2string(rc));
299      status = CURLE_LDAP_CANNOT_BIND;
300      goto quit;
301   }
302
303   rc = ldap_search_s(server, ludp->lud_dn, ludp->lud_scope,
304                      ludp->lud_filter, ludp->lud_attrs, 0, &result);
305
306   if (rc != 0 && rc != LDAP_SIZELIMIT_EXCEEDED) {
307     failf(data, "LDAP remote: %s", ldap_err2string(rc));
308     status = CURLE_LDAP_SEARCH_FAILED;
309     goto quit;
310   }
311
312   for(num = 0, entryIterator = ldap_first_entry(server, result);
313       entryIterator;
314       entryIterator = ldap_next_entry(server, entryIterator), num++)
315   {
316     BerElement *ber = NULL;
317     char  *attribute;       /*! suspicious that this isn't 'const' */
318     char  *dn = ldap_get_dn(server, entryIterator);
319     int i;
320
321     Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"DN: ", 4);
322     Curl_client_write(conn, CLIENTWRITE_BODY, (char *)dn, 0);
323     Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 1);
324
325     for (attribute = ldap_first_attribute(server, entryIterator, &ber);
326          attribute;
327          attribute = ldap_next_attribute(server, entryIterator, ber))
328     {
329       BerValue **vals = ldap_get_values_len(server, entryIterator, attribute);
330
331       if (vals != NULL)
332       {
333         for (i = 0; (vals[i] != NULL); i++)
334         {
335           Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\t", 1);
336           Curl_client_write(conn, CLIENTWRITE_BODY, (char *) attribute, 0);
337           Curl_client_write(conn, CLIENTWRITE_BODY, (char *)": ", 2);
338           if ((strlen(attribute) > 7) &&
339               (strcmp(";binary",
340                       (char *)attribute +
341                       (strlen((char *)attribute) - 7)) == 0)) {
342             /* Binary attribute, encode to base64. */
343             val_b64_sz = Curl_base64_encode(conn->data,
344                                             vals[i]->bv_val,
345                                             vals[i]->bv_len,
346                                             &val_b64);
347             if (val_b64_sz > 0) {
348               Curl_client_write(conn, CLIENTWRITE_BODY, val_b64, val_b64_sz);
349               free(val_b64);
350             }
351           } else
352             Curl_client_write(conn, CLIENTWRITE_BODY, vals[i]->bv_val,
353                               vals[i]->bv_len);
354           Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 0);
355         }
356
357         /* Free memory used to store values */
358         ldap_value_free_len(vals);
359       }
360       Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 1);
361
362       ldap_memfree(attribute);
363     }
364     ldap_memfree(dn);
365     if (ber)
366        ber_free(ber, 0);
367   }
368
369 quit:
370   if (result) {
371     ldap_msgfree(result);
372     LDAP_TRACE (("Received %d entries\n", num));
373   }
374   if (rc == LDAP_SIZELIMIT_EXCEEDED)
375     infof(data, "There are more than %d entries\n", num);
376   if (ludp)
377     ldap_free_urldesc(ludp);
378   if (server)
379     ldap_unbind_s(server);
380 #if defined(HAVE_LDAP_SSL) && defined(CURL_HAS_NOVELL_LDAPSDK)
381   if (ldap_ssl)
382     ldapssl_client_deinit();
383 #endif /* HAVE_LDAP_SSL && CURL_HAS_NOVELL_LDAPSDK */
384
385   /* no data to transfer */
386   Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
387   conn->bits.close = TRUE;
388
389   return status;
390 }
391
392 #ifdef DEBUG_LDAP
393 static void _ldap_trace (const char *fmt, ...)
394 {
395   static int do_trace = -1;
396   va_list args;
397
398   if (do_trace == -1) {
399     const char *env = getenv("CURL_TRACE");
400     do_trace = (env && atoi(env) > 0);
401   }
402   if (!do_trace)
403     return;
404
405   va_start (args, fmt);
406   vfprintf (stderr, fmt, args);
407   va_end (args);
408 }
409 #endif
410
411 #ifndef HAVE_LDAP_URL_PARSE
412
413 /*
414  * Return scope-value for a scope-string.
415  */
416 static int str2scope (const char *p)
417 {
418   if (!stricmp(p, "one"))
419      return LDAP_SCOPE_ONELEVEL;
420   if (!stricmp(p, "onetree"))
421      return LDAP_SCOPE_ONELEVEL;
422   if (!stricmp(p, "base"))
423      return LDAP_SCOPE_BASE;
424   if (!stricmp(p, "sub"))
425      return LDAP_SCOPE_SUBTREE;
426   if (!stricmp( p, "subtree"))
427      return LDAP_SCOPE_SUBTREE;
428   return (-1);
429 }
430
431 /*
432  * Split 'str' into strings separated by commas.
433  * Note: res[] points into 'str'.
434  */
435 static char **split_str (char *str)
436 {
437   char **res, *lasts, *s;
438   int  i;
439
440   for (i = 2, s = strchr(str,','); s; i++)
441      s = strchr(++s,',');
442
443   res = calloc(i, sizeof(char*));
444   if (!res)
445     return NULL;
446
447   for (i = 0, s = strtok_r(str, ",", &lasts); s;
448        s = strtok_r(NULL, ",", &lasts), i++)
449     res[i] = s;
450   return res;
451 }
452
453 /*
454  * Unescape the LDAP-URL components
455  */
456 static bool unescape_elements (void *data, LDAPURLDesc *ludp)
457 {
458   int i;
459
460   if (ludp->lud_filter) {
461     ludp->lud_filter = curl_easy_unescape(data, ludp->lud_filter, 0, NULL);
462     if (!ludp->lud_filter)
463        return (FALSE);
464   }
465
466   for (i = 0; ludp->lud_attrs && ludp->lud_attrs[i]; i++) {
467     ludp->lud_attrs[i] = curl_easy_unescape(data, ludp->lud_attrs[i], 0, NULL);
468     if (!ludp->lud_attrs[i])
469        return (FALSE);
470   }
471
472   for (i = 0; ludp->lud_exts && ludp->lud_exts[i]; i++) {
473     ludp->lud_exts[i] = curl_easy_unescape(data, ludp->lud_exts[i], 0, NULL);
474     if (!ludp->lud_exts[i])
475        return (FALSE);
476   }
477
478   if (ludp->lud_dn) {
479     char *dn = ludp->lud_dn;
480     char *new_dn = curl_easy_unescape(data, dn, 0, NULL);
481
482     free(dn);
483     ludp->lud_dn = new_dn;
484     if (!new_dn)
485        return (FALSE);
486   }
487   return (TRUE);
488 }
489
490 /*
491  * Break apart the pieces of an LDAP URL.
492  * Syntax:
493  *   ldap://<hostname>:<port>/<base_dn>?<attributes>?<scope>?<filter>?<ext>
494  *
495  * <hostname> already known from 'conn->host.name'.
496  * <port>     already known from 'conn->remote_port'.
497  * extract the rest from 'conn->data->reqdata.path+1'. All fields are optional.
498  * e.g.
499  *   ldap://<hostname>:<port>/?<attributes>?<scope>?<filter>
500  * yields ludp->lud_dn = "".
501  *
502  * Ref. http://developer.netscape.com/docs/manuals/dirsdk/csdk30/url.htm#2831915
503  */
504 static int _ldap_url_parse2 (const struct connectdata *conn, LDAPURLDesc *ludp)
505 {
506   char *p, *q;
507   int i;
508
509   if (!conn->data ||
510       !conn->data->reqdata.path ||
511       conn->data->reqdata.path[0] != '/' ||
512       !checkprefix(conn->protostr, conn->data->change.url))
513     return LDAP_INVALID_SYNTAX;
514
515   ludp->lud_scope = LDAP_SCOPE_BASE;
516   ludp->lud_port  = conn->remote_port;
517   ludp->lud_host  = conn->host.name;
518
519   /* parse DN (Distinguished Name).
520    */
521   ludp->lud_dn = strdup(conn->data->reqdata.path+1);
522   if (!ludp->lud_dn)
523     return LDAP_NO_MEMORY;
524
525   p = strchr(ludp->lud_dn, '?');
526   LDAP_TRACE (("DN '%.*s'\n", p ? (size_t)(p-ludp->lud_dn) :
527                strlen(ludp->lud_dn), ludp->lud_dn));
528
529   if (!p)
530     goto success;
531
532   *p++ = '\0';
533
534   /* parse attributes. skip "??".
535    */
536   q = strchr(p, '?');
537   if (q)
538     *q++ = '\0';
539
540   if (*p && *p != '?') {
541     ludp->lud_attrs = split_str(p);
542     if (!ludp->lud_attrs)
543       return LDAP_NO_MEMORY;
544
545     for (i = 0; ludp->lud_attrs[i]; i++)
546       LDAP_TRACE (("attr[%d] '%s'\n", i, ludp->lud_attrs[i]));
547   }
548
549   p = q;
550   if (!p)
551     goto success;
552
553   /* parse scope. skip "??"
554    */
555   q = strchr(p, '?');
556   if (q)
557     *q++ = '\0';
558
559   if (*p && *p != '?') {
560     ludp->lud_scope = str2scope(p);
561     if (ludp->lud_scope == -1)
562       return LDAP_INVALID_SYNTAX;
563     LDAP_TRACE (("scope %d\n", ludp->lud_scope));
564   }
565
566   p = q;
567   if (!p)
568     goto success;
569
570   /* parse filter
571    */
572   q = strchr(p, '?');
573   if (q)
574     *q++ = '\0';
575   if (!*p)
576     return LDAP_INVALID_SYNTAX;
577
578   ludp->lud_filter = p;
579   LDAP_TRACE (("filter '%s'\n", ludp->lud_filter));
580
581   p = q;
582   if (!p)
583     goto success;
584
585   /* parse extensions
586    */
587   ludp->lud_exts = split_str(p);
588   if (!ludp->lud_exts)
589     return LDAP_NO_MEMORY;
590
591   for (i = 0; ludp->lud_exts[i]; i++)
592     LDAP_TRACE (("exts[%d] '%s'\n", i, ludp->lud_exts[i]));
593
594   success:
595   if (!unescape_elements(conn->data, ludp))
596     return LDAP_NO_MEMORY;
597   return LDAP_SUCCESS;
598 }
599
600 static int _ldap_url_parse (const struct connectdata *conn,
601                             LDAPURLDesc **ludpp)
602 {
603   LDAPURLDesc *ludp = calloc(sizeof(*ludp), 1);
604   int rc;
605
606   *ludpp = NULL;
607   if (!ludp)
608      return LDAP_NO_MEMORY;
609
610   rc = _ldap_url_parse2 (conn, ludp);
611   if (rc != LDAP_SUCCESS) {
612     _ldap_free_urldesc(ludp);
613     ludp = NULL;
614   }
615   *ludpp = ludp;
616   return (rc);
617 }
618
619 static void _ldap_free_urldesc (LDAPURLDesc *ludp)
620 {
621   int i;
622
623   if (!ludp)
624      return;
625
626   if (ludp->lud_dn)
627      free(ludp->lud_dn);
628
629   if (ludp->lud_filter)
630      free(ludp->lud_filter);
631
632   if (ludp->lud_attrs) {
633     for (i = 0; ludp->lud_attrs[i]; i++)
634        free(ludp->lud_attrs[i]);
635     free(ludp->lud_attrs);
636   }
637
638   if (ludp->lud_exts) {
639     for (i = 0; ludp->lud_exts[i]; i++)
640        free(ludp->lud_exts[i]);
641     free(ludp->lud_exts);
642   }
643   free (ludp);
644 }
645 #endif  /* !HAVE_LDAP_URL_PARSE */
646 #endif  /* CURL_DISABLE_LDAP */