• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /***************************************************************************
2  *                      _   _ ____  _
3  *  Project         ___| | | |  _ \| |
4  *                 / __| | | | |_) | |
5  *                | (__| |_| |  _ <| |___
6  *                 \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2021, 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 https://curl.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  ***************************************************************************/
22 
23 #include "curl_setup.h"
24 
25 #if !defined(CURL_DISABLE_LDAP) && !defined(USE_OPENLDAP)
26 
27 /*
28  * Notice that USE_OPENLDAP is only a source code selection switch. When
29  * libcurl is built with USE_OPENLDAP defined the libcurl source code that
30  * gets compiled is the code from openldap.c, otherwise the code that gets
31  * compiled is the code from ldap.c.
32  *
33  * When USE_OPENLDAP is defined a recent version of the OpenLDAP library
34  * might be required for compilation and runtime. In order to use ancient
35  * OpenLDAP library versions, USE_OPENLDAP shall not be defined.
36  */
37 
38 #ifdef USE_WIN32_LDAP           /* Use Windows LDAP implementation. */
39 # include <winldap.h>
40 # ifndef LDAP_VENDOR_NAME
41 #  error Your Platform SDK is NOT sufficient for LDAP support! \
42          Update your Platform SDK, or disable LDAP support!
43 # else
44 #  include <winber.h>
45 # endif
46 #else
47 # define LDAP_DEPRECATED 1      /* Be sure ldap_init() is defined. */
48 # ifdef HAVE_LBER_H
49 #  include <lber.h>
50 # endif
51 # include <ldap.h>
52 # if (defined(HAVE_LDAP_SSL) && defined(HAVE_LDAP_SSL_H))
53 #  include <ldap_ssl.h>
54 # endif /* HAVE_LDAP_SSL && HAVE_LDAP_SSL_H */
55 #endif
56 
57 #include "urldata.h"
58 #include <curl/curl.h>
59 #include "sendf.h"
60 #include "escape.h"
61 #include "progress.h"
62 #include "transfer.h"
63 #include "strcase.h"
64 #include "strtok.h"
65 #include "curl_ldap.h"
66 #include "curl_multibyte.h"
67 #include "curl_base64.h"
68 #include "connect.h"
69 /* The last 3 #include files should be in this order */
70 #include "curl_printf.h"
71 #include "curl_memory.h"
72 #include "memdebug.h"
73 
74 #ifndef HAVE_LDAP_URL_PARSE
75 
76 /* Use our own implementation. */
77 
78 struct ldap_urldesc {
79   char   *lud_host;
80   int     lud_port;
81 #if defined(USE_WIN32_LDAP)
82   TCHAR  *lud_dn;
83   TCHAR **lud_attrs;
84 #else
85   char   *lud_dn;
86   char  **lud_attrs;
87 #endif
88   int     lud_scope;
89 #if defined(USE_WIN32_LDAP)
90   TCHAR  *lud_filter;
91 #else
92   char   *lud_filter;
93 #endif
94   char  **lud_exts;
95   size_t    lud_attrs_dups; /* how many were dup'ed, this field is not in the
96                                "real" struct so can only be used in code
97                                without HAVE_LDAP_URL_PARSE defined */
98 };
99 
100 #undef LDAPURLDesc
101 #define LDAPURLDesc struct ldap_urldesc
102 
103 static int  _ldap_url_parse(struct Curl_easy *data,
104                             const struct connectdata *conn,
105                             LDAPURLDesc **ludp);
106 static void _ldap_free_urldesc(LDAPURLDesc *ludp);
107 
108 #undef ldap_free_urldesc
109 #define ldap_free_urldesc       _ldap_free_urldesc
110 #endif
111 
112 #ifdef DEBUG_LDAP
113   #define LDAP_TRACE(x)   do { \
114                             _ldap_trace("%u: ", __LINE__); \
115                             _ldap_trace x; \
116                           } while(0)
117 
118   static void _ldap_trace(const char *fmt, ...);
119 #else
120   #define LDAP_TRACE(x)   Curl_nop_stmt
121 #endif
122 
123 #if defined(USE_WIN32_LDAP) && defined(ldap_err2string)
124 /* Use ansi error strings in UNICODE builds */
125 #undef ldap_err2string
126 #define ldap_err2string ldap_err2stringA
127 #endif
128 
129 
130 static CURLcode ldap_do(struct Curl_easy *data, bool *done);
131 
132 /*
133  * LDAP protocol handler.
134  */
135 
136 const struct Curl_handler Curl_handler_ldap = {
137   "LDAP",                               /* scheme */
138   ZERO_NULL,                            /* setup_connection */
139   ldap_do,                              /* do_it */
140   ZERO_NULL,                            /* done */
141   ZERO_NULL,                            /* do_more */
142   ZERO_NULL,                            /* connect_it */
143   ZERO_NULL,                            /* connecting */
144   ZERO_NULL,                            /* doing */
145   ZERO_NULL,                            /* proto_getsock */
146   ZERO_NULL,                            /* doing_getsock */
147   ZERO_NULL,                            /* domore_getsock */
148   ZERO_NULL,                            /* perform_getsock */
149   ZERO_NULL,                            /* disconnect */
150   ZERO_NULL,                            /* readwrite */
151   ZERO_NULL,                            /* connection_check */
152   ZERO_NULL,                            /* attach connection */
153   PORT_LDAP,                            /* defport */
154   CURLPROTO_LDAP,                       /* protocol */
155   CURLPROTO_LDAP,                       /* family */
156   PROTOPT_NONE                          /* flags */
157 };
158 
159 #ifdef HAVE_LDAP_SSL
160 /*
161  * LDAPS protocol handler.
162  */
163 
164 const struct Curl_handler Curl_handler_ldaps = {
165   "LDAPS",                              /* scheme */
166   ZERO_NULL,                            /* setup_connection */
167   ldap_do,                              /* do_it */
168   ZERO_NULL,                            /* done */
169   ZERO_NULL,                            /* do_more */
170   ZERO_NULL,                            /* connect_it */
171   ZERO_NULL,                            /* connecting */
172   ZERO_NULL,                            /* doing */
173   ZERO_NULL,                            /* proto_getsock */
174   ZERO_NULL,                            /* doing_getsock */
175   ZERO_NULL,                            /* domore_getsock */
176   ZERO_NULL,                            /* perform_getsock */
177   ZERO_NULL,                            /* disconnect */
178   ZERO_NULL,                            /* readwrite */
179   ZERO_NULL,                            /* connection_check */
180   ZERO_NULL,                            /* attach connection */
181   PORT_LDAPS,                           /* defport */
182   CURLPROTO_LDAPS,                      /* protocol */
183   CURLPROTO_LDAP,                       /* family */
184   PROTOPT_SSL                           /* flags */
185 };
186 #endif
187 
188 #if defined(USE_WIN32_LDAP)
189 
190 #if defined(USE_WINDOWS_SSPI)
ldap_win_bind_auth(LDAP * server,const char * user,const char * passwd,unsigned long authflags)191 static int ldap_win_bind_auth(LDAP *server, const char *user,
192                               const char *passwd, unsigned long authflags)
193 {
194   ULONG method = 0;
195   SEC_WINNT_AUTH_IDENTITY cred;
196   int rc = LDAP_AUTH_METHOD_NOT_SUPPORTED;
197 
198   memset(&cred, 0, sizeof(cred));
199 
200 #if defined(USE_SPNEGO)
201   if(authflags & CURLAUTH_NEGOTIATE) {
202     method = LDAP_AUTH_NEGOTIATE;
203   }
204   else
205 #endif
206 #if defined(USE_NTLM)
207   if(authflags & CURLAUTH_NTLM) {
208     method = LDAP_AUTH_NTLM;
209   }
210   else
211 #endif
212 #if !defined(CURL_DISABLE_CRYPTO_AUTH)
213   if(authflags & CURLAUTH_DIGEST) {
214     method = LDAP_AUTH_DIGEST;
215   }
216   else
217 #endif
218   {
219     /* required anyway if one of upper preprocessor definitions enabled */
220   }
221 
222   if(method && user && passwd) {
223     rc = Curl_create_sspi_identity(user, passwd, &cred);
224     if(!rc) {
225       rc = ldap_bind_s(server, NULL, (TCHAR *)&cred, method);
226       Curl_sspi_free_identity(&cred);
227     }
228   }
229   else {
230     /* proceed with current user credentials */
231     method = LDAP_AUTH_NEGOTIATE;
232     rc = ldap_bind_s(server, NULL, NULL, method);
233   }
234   return rc;
235 }
236 #endif /* #if defined(USE_WINDOWS_SSPI) */
237 
ldap_win_bind(struct Curl_easy * data,LDAP * server,const char * user,const char * passwd)238 static int ldap_win_bind(struct Curl_easy *data, LDAP *server,
239                          const char *user, const char *passwd)
240 {
241   int rc = LDAP_INVALID_CREDENTIALS;
242 
243   PTCHAR inuser = NULL;
244   PTCHAR inpass = NULL;
245 
246   if(user && passwd && (data->set.httpauth & CURLAUTH_BASIC)) {
247     inuser = curlx_convert_UTF8_to_tchar((char *) user);
248     inpass = curlx_convert_UTF8_to_tchar((char *) passwd);
249 
250     rc = ldap_simple_bind_s(server, inuser, inpass);
251 
252     curlx_unicodefree(inuser);
253     curlx_unicodefree(inpass);
254   }
255 #if defined(USE_WINDOWS_SSPI)
256   else {
257     rc = ldap_win_bind_auth(server, user, passwd, data->set.httpauth);
258   }
259 #endif
260 
261   return rc;
262 }
263 #endif /* #if defined(USE_WIN32_LDAP) */
264 
265 #if defined(USE_WIN32_LDAP)
266 #define FREE_ON_WINLDAP(x) curlx_unicodefree(x)
267 #else
268 #define FREE_ON_WINLDAP(x)
269 #endif
270 
271 
ldap_do(struct Curl_easy * data,bool * done)272 static CURLcode ldap_do(struct Curl_easy *data, bool *done)
273 {
274   CURLcode result = CURLE_OK;
275   int rc = 0;
276   LDAP *server = NULL;
277   LDAPURLDesc *ludp = NULL;
278   LDAPMessage *ldapmsg = NULL;
279   LDAPMessage *entryIterator;
280   int num = 0;
281   struct connectdata *conn = data->conn;
282   int ldap_proto = LDAP_VERSION3;
283   int ldap_ssl = 0;
284   char *val_b64 = NULL;
285   size_t val_b64_sz = 0;
286   curl_off_t dlsize = 0;
287 #ifdef LDAP_OPT_NETWORK_TIMEOUT
288   struct timeval ldap_timeout = {10, 0}; /* 10 sec connection/search timeout */
289 #endif
290 #if defined(USE_WIN32_LDAP)
291   TCHAR *host = NULL;
292 #else
293   char *host = NULL;
294 #endif
295   char *user = NULL;
296   char *passwd = NULL;
297 
298   *done = TRUE; /* unconditionally */
299   infof(data, "LDAP local: LDAP Vendor = %s ; LDAP Version = %d",
300           LDAP_VENDOR_NAME, LDAP_VENDOR_VERSION);
301   infof(data, "LDAP local: %s", data->state.url);
302 
303 #ifdef HAVE_LDAP_URL_PARSE
304   rc = ldap_url_parse(data->state.url, &ludp);
305 #else
306   rc = _ldap_url_parse(data, conn, &ludp);
307 #endif
308   if(rc) {
309     failf(data, "LDAP local: %s", ldap_err2string(rc));
310     result = CURLE_LDAP_INVALID_URL;
311     goto quit;
312   }
313 
314   /* Get the URL scheme (either ldap or ldaps) */
315   if(conn->given->flags & PROTOPT_SSL)
316     ldap_ssl = 1;
317   infof(data, "LDAP local: trying to establish %s connection",
318           ldap_ssl ? "encrypted" : "cleartext");
319 
320 #if defined(USE_WIN32_LDAP)
321   host = curlx_convert_UTF8_to_tchar(conn->host.name);
322   if(!host) {
323     result = CURLE_OUT_OF_MEMORY;
324 
325     goto quit;
326   }
327 #else
328   host = conn->host.name;
329 #endif
330 
331   if(conn->bits.user_passwd) {
332     user = conn->user;
333     passwd = conn->passwd;
334   }
335 
336 #ifdef LDAP_OPT_NETWORK_TIMEOUT
337   ldap_set_option(NULL, LDAP_OPT_NETWORK_TIMEOUT, &ldap_timeout);
338 #endif
339   ldap_set_option(NULL, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto);
340 
341   if(ldap_ssl) {
342 #ifdef HAVE_LDAP_SSL
343 #ifdef USE_WIN32_LDAP
344     /* Win32 LDAP SDK doesn't support insecure mode without CA! */
345     server = ldap_sslinit(host, (int)conn->port, 1);
346     ldap_set_option(server, LDAP_OPT_SSL, LDAP_OPT_ON);
347 #else
348     int ldap_option;
349     char *ldap_ca = conn->ssl_config.CAfile;
350 #if defined(CURL_HAS_NOVELL_LDAPSDK)
351     rc = ldapssl_client_init(NULL, NULL);
352     if(rc != LDAP_SUCCESS) {
353       failf(data, "LDAP local: ldapssl_client_init %s", ldap_err2string(rc));
354       result = CURLE_SSL_CERTPROBLEM;
355       goto quit;
356     }
357     if(conn->ssl_config.verifypeer) {
358       /* Novell SDK supports DER or BASE64 files. */
359       int cert_type = LDAPSSL_CERT_FILETYPE_B64;
360       if((data->set.ssl.cert_type) &&
361          (strcasecompare(data->set.ssl.cert_type, "DER")))
362         cert_type = LDAPSSL_CERT_FILETYPE_DER;
363       if(!ldap_ca) {
364         failf(data, "LDAP local: ERROR %s CA cert not set!",
365               (cert_type == LDAPSSL_CERT_FILETYPE_DER ? "DER" : "PEM"));
366         result = CURLE_SSL_CERTPROBLEM;
367         goto quit;
368       }
369       infof(data, "LDAP local: using %s CA cert '%s'",
370             (cert_type == LDAPSSL_CERT_FILETYPE_DER ? "DER" : "PEM"),
371             ldap_ca);
372       rc = ldapssl_add_trusted_cert(ldap_ca, cert_type);
373       if(rc != LDAP_SUCCESS) {
374         failf(data, "LDAP local: ERROR setting %s CA cert: %s",
375               (cert_type == LDAPSSL_CERT_FILETYPE_DER ? "DER" : "PEM"),
376               ldap_err2string(rc));
377         result = CURLE_SSL_CERTPROBLEM;
378         goto quit;
379       }
380       ldap_option = LDAPSSL_VERIFY_SERVER;
381     }
382     else
383       ldap_option = LDAPSSL_VERIFY_NONE;
384     rc = ldapssl_set_verify_mode(ldap_option);
385     if(rc != LDAP_SUCCESS) {
386       failf(data, "LDAP local: ERROR setting cert verify mode: %s",
387               ldap_err2string(rc));
388       result = CURLE_SSL_CERTPROBLEM;
389       goto quit;
390     }
391     server = ldapssl_init(host, (int)conn->port, 1);
392     if(!server) {
393       failf(data, "LDAP local: Cannot connect to %s:%ld",
394             conn->host.dispname, conn->port);
395       result = CURLE_COULDNT_CONNECT;
396       goto quit;
397     }
398 #elif defined(LDAP_OPT_X_TLS)
399     if(conn->ssl_config.verifypeer) {
400       /* OpenLDAP SDK supports BASE64 files. */
401       if((data->set.ssl.cert_type) &&
402          (!strcasecompare(data->set.ssl.cert_type, "PEM"))) {
403         failf(data, "LDAP local: ERROR OpenLDAP only supports PEM cert-type!");
404         result = CURLE_SSL_CERTPROBLEM;
405         goto quit;
406       }
407       if(!ldap_ca) {
408         failf(data, "LDAP local: ERROR PEM CA cert not set!");
409         result = CURLE_SSL_CERTPROBLEM;
410         goto quit;
411       }
412       infof(data, "LDAP local: using PEM CA cert: %s", ldap_ca);
413       rc = ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTFILE, ldap_ca);
414       if(rc != LDAP_SUCCESS) {
415         failf(data, "LDAP local: ERROR setting PEM CA cert: %s",
416                 ldap_err2string(rc));
417         result = CURLE_SSL_CERTPROBLEM;
418         goto quit;
419       }
420       ldap_option = LDAP_OPT_X_TLS_DEMAND;
421     }
422     else
423       ldap_option = LDAP_OPT_X_TLS_NEVER;
424 
425     rc = ldap_set_option(NULL, LDAP_OPT_X_TLS_REQUIRE_CERT, &ldap_option);
426     if(rc != LDAP_SUCCESS) {
427       failf(data, "LDAP local: ERROR setting cert verify mode: %s",
428               ldap_err2string(rc));
429       result = CURLE_SSL_CERTPROBLEM;
430       goto quit;
431     }
432     server = ldap_init(host, (int)conn->port);
433     if(!server) {
434       failf(data, "LDAP local: Cannot connect to %s:%ld",
435             conn->host.dispname, conn->port);
436       result = CURLE_COULDNT_CONNECT;
437       goto quit;
438     }
439     ldap_option = LDAP_OPT_X_TLS_HARD;
440     rc = ldap_set_option(server, LDAP_OPT_X_TLS, &ldap_option);
441     if(rc != LDAP_SUCCESS) {
442       failf(data, "LDAP local: ERROR setting SSL/TLS mode: %s",
443               ldap_err2string(rc));
444       result = CURLE_SSL_CERTPROBLEM;
445       goto quit;
446     }
447 /*
448     rc = ldap_start_tls_s(server, NULL, NULL);
449     if(rc != LDAP_SUCCESS) {
450       failf(data, "LDAP local: ERROR starting SSL/TLS mode: %s",
451               ldap_err2string(rc));
452       result = CURLE_SSL_CERTPROBLEM;
453       goto quit;
454     }
455 */
456 #else
457     /* we should probably never come up to here since configure
458        should check in first place if we can support LDAP SSL/TLS */
459     failf(data, "LDAP local: SSL/TLS not supported with this version "
460             "of the OpenLDAP toolkit\n");
461     result = CURLE_SSL_CERTPROBLEM;
462     goto quit;
463 #endif
464 #endif
465 #endif /* CURL_LDAP_USE_SSL */
466   }
467   else {
468     server = ldap_init(host, (int)conn->port);
469     if(!server) {
470       failf(data, "LDAP local: Cannot connect to %s:%ld",
471             conn->host.dispname, conn->port);
472       result = CURLE_COULDNT_CONNECT;
473       goto quit;
474     }
475   }
476 #ifdef USE_WIN32_LDAP
477   ldap_set_option(server, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto);
478   rc = ldap_win_bind(data, server, user, passwd);
479 #else
480   rc = ldap_simple_bind_s(server, user, passwd);
481 #endif
482   if(!ldap_ssl && rc) {
483     ldap_proto = LDAP_VERSION2;
484     ldap_set_option(server, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto);
485 #ifdef USE_WIN32_LDAP
486     rc = ldap_win_bind(data, server, user, passwd);
487 #else
488     rc = ldap_simple_bind_s(server, user, passwd);
489 #endif
490   }
491   if(rc) {
492 #ifdef USE_WIN32_LDAP
493     failf(data, "LDAP local: bind via ldap_win_bind %s",
494           ldap_err2string(rc));
495 #else
496     failf(data, "LDAP local: bind via ldap_simple_bind_s %s",
497           ldap_err2string(rc));
498 #endif
499     result = CURLE_LDAP_CANNOT_BIND;
500     goto quit;
501   }
502 
503   rc = ldap_search_s(server, ludp->lud_dn, ludp->lud_scope,
504                      ludp->lud_filter, ludp->lud_attrs, 0, &ldapmsg);
505 
506   if(rc && rc != LDAP_SIZELIMIT_EXCEEDED) {
507     failf(data, "LDAP remote: %s", ldap_err2string(rc));
508     result = CURLE_LDAP_SEARCH_FAILED;
509     goto quit;
510   }
511 
512   for(num = 0, entryIterator = ldap_first_entry(server, ldapmsg);
513       entryIterator;
514       entryIterator = ldap_next_entry(server, entryIterator), num++) {
515     BerElement *ber = NULL;
516 #if defined(USE_WIN32_LDAP)
517     TCHAR *attribute;
518 #else
519     char *attribute;
520 #endif
521     int i;
522 
523     /* Get the DN and write it to the client */
524     {
525       char *name;
526       size_t name_len;
527 #if defined(USE_WIN32_LDAP)
528       TCHAR *dn = ldap_get_dn(server, entryIterator);
529       name = curlx_convert_tchar_to_UTF8(dn);
530       if(!name) {
531         ldap_memfree(dn);
532 
533         result = CURLE_OUT_OF_MEMORY;
534 
535         goto quit;
536       }
537 #else
538       char *dn = name = ldap_get_dn(server, entryIterator);
539 #endif
540       name_len = strlen(name);
541 
542       result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)"DN: ", 4);
543       if(result) {
544         FREE_ON_WINLDAP(name);
545         ldap_memfree(dn);
546         goto quit;
547       }
548 
549       result = Curl_client_write(data, CLIENTWRITE_BODY, (char *) name,
550                                  name_len);
551       if(result) {
552         FREE_ON_WINLDAP(name);
553         ldap_memfree(dn);
554         goto quit;
555       }
556 
557       result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)"\n", 1);
558       if(result) {
559         FREE_ON_WINLDAP(name);
560         ldap_memfree(dn);
561 
562         goto quit;
563       }
564 
565       dlsize += name_len + 5;
566 
567       FREE_ON_WINLDAP(name);
568       ldap_memfree(dn);
569     }
570 
571     /* Get the attributes and write them to the client */
572     for(attribute = ldap_first_attribute(server, entryIterator, &ber);
573         attribute;
574         attribute = ldap_next_attribute(server, entryIterator, ber)) {
575       BerValue **vals;
576       size_t attr_len;
577 #if defined(USE_WIN32_LDAP)
578       char *attr = curlx_convert_tchar_to_UTF8(attribute);
579       if(!attr) {
580         if(ber)
581           ber_free(ber, 0);
582 
583         result = CURLE_OUT_OF_MEMORY;
584 
585         goto quit;
586       }
587 #else
588       char *attr = attribute;
589 #endif
590       attr_len = strlen(attr);
591 
592       vals = ldap_get_values_len(server, entryIterator, attribute);
593       if(vals != NULL) {
594         for(i = 0; (vals[i] != NULL); i++) {
595           result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)"\t", 1);
596           if(result) {
597             ldap_value_free_len(vals);
598             FREE_ON_WINLDAP(attr);
599             ldap_memfree(attribute);
600             if(ber)
601               ber_free(ber, 0);
602 
603             goto quit;
604           }
605 
606           result = Curl_client_write(data, CLIENTWRITE_BODY,
607                                      (char *) attr, attr_len);
608           if(result) {
609             ldap_value_free_len(vals);
610             FREE_ON_WINLDAP(attr);
611             ldap_memfree(attribute);
612             if(ber)
613               ber_free(ber, 0);
614 
615             goto quit;
616           }
617 
618           result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)": ", 2);
619           if(result) {
620             ldap_value_free_len(vals);
621             FREE_ON_WINLDAP(attr);
622             ldap_memfree(attribute);
623             if(ber)
624               ber_free(ber, 0);
625 
626             goto quit;
627           }
628 
629           dlsize += attr_len + 3;
630 
631           if((attr_len > 7) &&
632              (strcmp(";binary", (char *) attr + (attr_len - 7)) == 0)) {
633             /* Binary attribute, encode to base64. */
634             result = Curl_base64_encode(data,
635                                         vals[i]->bv_val,
636                                         vals[i]->bv_len,
637                                         &val_b64,
638                                         &val_b64_sz);
639             if(result) {
640               ldap_value_free_len(vals);
641               FREE_ON_WINLDAP(attr);
642               ldap_memfree(attribute);
643               if(ber)
644                 ber_free(ber, 0);
645 
646               goto quit;
647             }
648 
649             if(val_b64_sz > 0) {
650               result = Curl_client_write(data, CLIENTWRITE_BODY, val_b64,
651                                          val_b64_sz);
652               free(val_b64);
653               if(result) {
654                 ldap_value_free_len(vals);
655                 FREE_ON_WINLDAP(attr);
656                 ldap_memfree(attribute);
657                 if(ber)
658                   ber_free(ber, 0);
659 
660                 goto quit;
661               }
662 
663               dlsize += val_b64_sz;
664             }
665           }
666           else {
667             result = Curl_client_write(data, CLIENTWRITE_BODY, vals[i]->bv_val,
668                                        vals[i]->bv_len);
669             if(result) {
670               ldap_value_free_len(vals);
671               FREE_ON_WINLDAP(attr);
672               ldap_memfree(attribute);
673               if(ber)
674                 ber_free(ber, 0);
675 
676               goto quit;
677             }
678 
679             dlsize += vals[i]->bv_len;
680           }
681 
682           result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)"\n", 1);
683           if(result) {
684             ldap_value_free_len(vals);
685             FREE_ON_WINLDAP(attr);
686             ldap_memfree(attribute);
687             if(ber)
688               ber_free(ber, 0);
689 
690             goto quit;
691           }
692 
693           dlsize++;
694         }
695 
696         /* Free memory used to store values */
697         ldap_value_free_len(vals);
698       }
699 
700       /* Free the attribute as we are done with it */
701       FREE_ON_WINLDAP(attr);
702       ldap_memfree(attribute);
703 
704       result = Curl_client_write(data, CLIENTWRITE_BODY, (char *)"\n", 1);
705       if(result)
706         goto quit;
707       dlsize++;
708       Curl_pgrsSetDownloadCounter(data, dlsize);
709     }
710 
711     if(ber)
712        ber_free(ber, 0);
713   }
714 
715 quit:
716   if(ldapmsg) {
717     ldap_msgfree(ldapmsg);
718     LDAP_TRACE(("Received %d entries\n", num));
719   }
720   if(rc == LDAP_SIZELIMIT_EXCEEDED)
721     infof(data, "There are more than %d entries", num);
722   if(ludp)
723     ldap_free_urldesc(ludp);
724   if(server)
725     ldap_unbind_s(server);
726 #if defined(HAVE_LDAP_SSL) && defined(CURL_HAS_NOVELL_LDAPSDK)
727   if(ldap_ssl)
728     ldapssl_client_deinit();
729 #endif /* HAVE_LDAP_SSL && CURL_HAS_NOVELL_LDAPSDK */
730 
731   FREE_ON_WINLDAP(host);
732 
733   /* no data to transfer */
734   Curl_setup_transfer(data, -1, -1, FALSE, -1);
735   connclose(conn, "LDAP connection always disable re-use");
736 
737   return result;
738 }
739 
740 #ifdef DEBUG_LDAP
_ldap_trace(const char * fmt,...)741 static void _ldap_trace(const char *fmt, ...)
742 {
743   static int do_trace = -1;
744   va_list args;
745 
746   if(do_trace == -1) {
747     const char *env = getenv("CURL_TRACE");
748     do_trace = (env && strtol(env, NULL, 10) > 0);
749   }
750   if(!do_trace)
751     return;
752 
753   va_start(args, fmt);
754   vfprintf(stderr, fmt, args);
755   va_end(args);
756 }
757 #endif
758 
759 #ifndef HAVE_LDAP_URL_PARSE
760 
761 /*
762  * Return scope-value for a scope-string.
763  */
str2scope(const char * p)764 static int str2scope(const char *p)
765 {
766   if(strcasecompare(p, "one"))
767     return LDAP_SCOPE_ONELEVEL;
768   if(strcasecompare(p, "onetree"))
769     return LDAP_SCOPE_ONELEVEL;
770   if(strcasecompare(p, "base"))
771     return LDAP_SCOPE_BASE;
772   if(strcasecompare(p, "sub"))
773     return LDAP_SCOPE_SUBTREE;
774   if(strcasecompare(p, "subtree"))
775     return LDAP_SCOPE_SUBTREE;
776   return (-1);
777 }
778 
779 /*
780  * Split 'str' into strings separated by commas.
781  * Note: out[] points into 'str'.
782  */
split_str(char * str,char *** out,size_t * count)783 static bool split_str(char *str, char ***out, size_t *count)
784 {
785   char **res;
786   char *lasts;
787   char *s;
788   size_t  i;
789   size_t items = 1;
790 
791   s = strchr(str, ',');
792   while(s) {
793     items++;
794     s = strchr(++s, ',');
795   }
796 
797   res = calloc(items, sizeof(char *));
798   if(!res)
799     return FALSE;
800 
801   for(i = 0, s = strtok_r(str, ",", &lasts); s && i < items;
802       s = strtok_r(NULL, ",", &lasts), i++)
803     res[i] = s;
804 
805   *out = res;
806   *count = items;
807 
808   return TRUE;
809 }
810 
811 /*
812  * Break apart the pieces of an LDAP URL.
813  * Syntax:
814  *   ldap://<hostname>:<port>/<base_dn>?<attributes>?<scope>?<filter>?<ext>
815  *
816  * <hostname> already known from 'conn->host.name'.
817  * <port>     already known from 'conn->remote_port'.
818  * extract the rest from 'data->state.path+1'. All fields are optional.
819  * e.g.
820  *   ldap://<hostname>:<port>/?<attributes>?<scope>?<filter>
821  * yields ludp->lud_dn = "".
822  *
823  * Defined in RFC4516 section 2.
824  */
_ldap_url_parse2(struct Curl_easy * data,const struct connectdata * conn,LDAPURLDesc * ludp)825 static int _ldap_url_parse2(struct Curl_easy *data,
826                             const struct connectdata *conn, LDAPURLDesc *ludp)
827 {
828   int rc = LDAP_SUCCESS;
829   char *p;
830   char *path;
831   char *q = NULL;
832   char *query = NULL;
833   size_t i;
834 
835   if(!data ||
836      !data->state.up.path ||
837      data->state.up.path[0] != '/' ||
838      !strncasecompare("LDAP", data->state.up.scheme, 4))
839     return LDAP_INVALID_SYNTAX;
840 
841   ludp->lud_scope = LDAP_SCOPE_BASE;
842   ludp->lud_port  = conn->remote_port;
843   ludp->lud_host  = conn->host.name;
844 
845   /* Duplicate the path */
846   p = path = strdup(data->state.up.path + 1);
847   if(!path)
848     return LDAP_NO_MEMORY;
849 
850   /* Duplicate the query if present */
851   if(data->state.up.query) {
852     q = query = strdup(data->state.up.query);
853     if(!query) {
854       free(path);
855       return LDAP_NO_MEMORY;
856     }
857   }
858 
859   /* Parse the DN (Distinguished Name) */
860   if(*p) {
861     char *dn = p;
862     char *unescaped;
863     CURLcode result;
864 
865     LDAP_TRACE(("DN '%s'\n", dn));
866 
867     /* Unescape the DN */
868     result = Curl_urldecode(data, dn, 0, &unescaped, NULL, REJECT_ZERO);
869     if(result) {
870       rc = LDAP_NO_MEMORY;
871 
872       goto quit;
873     }
874 
875 #if defined(USE_WIN32_LDAP)
876     /* Convert the unescaped string to a tchar */
877     ludp->lud_dn = curlx_convert_UTF8_to_tchar(unescaped);
878 
879     /* Free the unescaped string as we are done with it */
880     free(unescaped);
881 
882     if(!ludp->lud_dn) {
883       rc = LDAP_NO_MEMORY;
884 
885       goto quit;
886     }
887 #else
888     ludp->lud_dn = unescaped;
889 #endif
890   }
891 
892   p = q;
893   if(!p)
894     goto quit;
895 
896   /* Parse the attributes. skip "??" */
897   q = strchr(p, '?');
898   if(q)
899     *q++ = '\0';
900 
901   if(*p) {
902     char **attributes;
903     size_t count = 0;
904 
905     /* Split the string into an array of attributes */
906     if(!split_str(p, &attributes, &count)) {
907       rc = LDAP_NO_MEMORY;
908 
909       goto quit;
910     }
911 
912     /* Allocate our array (+1 for the NULL entry) */
913 #if defined(USE_WIN32_LDAP)
914     ludp->lud_attrs = calloc(count + 1, sizeof(TCHAR *));
915 #else
916     ludp->lud_attrs = calloc(count + 1, sizeof(char *));
917 #endif
918     if(!ludp->lud_attrs) {
919       free(attributes);
920 
921       rc = LDAP_NO_MEMORY;
922 
923       goto quit;
924     }
925 
926     for(i = 0; i < count; i++) {
927       char *unescaped;
928       CURLcode result;
929 
930       LDAP_TRACE(("attr[%zu] '%s'\n", i, attributes[i]));
931 
932       /* Unescape the attribute */
933       result = Curl_urldecode(data, attributes[i], 0, &unescaped, NULL,
934                               REJECT_ZERO);
935       if(result) {
936         free(attributes);
937 
938         rc = LDAP_NO_MEMORY;
939 
940         goto quit;
941       }
942 
943 #if defined(USE_WIN32_LDAP)
944       /* Convert the unescaped string to a tchar */
945       ludp->lud_attrs[i] = curlx_convert_UTF8_to_tchar(unescaped);
946 
947       /* Free the unescaped string as we are done with it */
948       free(unescaped);
949 
950       if(!ludp->lud_attrs[i]) {
951         free(attributes);
952 
953         rc = LDAP_NO_MEMORY;
954 
955         goto quit;
956       }
957 #else
958       ludp->lud_attrs[i] = unescaped;
959 #endif
960 
961       ludp->lud_attrs_dups++;
962     }
963 
964     free(attributes);
965   }
966 
967   p = q;
968   if(!p)
969     goto quit;
970 
971   /* Parse the scope. skip "??" */
972   q = strchr(p, '?');
973   if(q)
974     *q++ = '\0';
975 
976   if(*p) {
977     ludp->lud_scope = str2scope(p);
978     if(ludp->lud_scope == -1) {
979       rc = LDAP_INVALID_SYNTAX;
980 
981       goto quit;
982     }
983     LDAP_TRACE(("scope %d\n", ludp->lud_scope));
984   }
985 
986   p = q;
987   if(!p)
988     goto quit;
989 
990   /* Parse the filter */
991   q = strchr(p, '?');
992   if(q)
993     *q++ = '\0';
994 
995   if(*p) {
996     char *filter = p;
997     char *unescaped;
998     CURLcode result;
999 
1000     LDAP_TRACE(("filter '%s'\n", filter));
1001 
1002     /* Unescape the filter */
1003     result = Curl_urldecode(data, filter, 0, &unescaped, NULL, REJECT_ZERO);
1004     if(result) {
1005       rc = LDAP_NO_MEMORY;
1006 
1007       goto quit;
1008     }
1009 
1010 #if defined(USE_WIN32_LDAP)
1011     /* Convert the unescaped string to a tchar */
1012     ludp->lud_filter = curlx_convert_UTF8_to_tchar(unescaped);
1013 
1014     /* Free the unescaped string as we are done with it */
1015     free(unescaped);
1016 
1017     if(!ludp->lud_filter) {
1018       rc = LDAP_NO_MEMORY;
1019 
1020       goto quit;
1021     }
1022 #else
1023     ludp->lud_filter = unescaped;
1024 #endif
1025   }
1026 
1027   p = q;
1028   if(p && !*p) {
1029     rc = LDAP_INVALID_SYNTAX;
1030 
1031     goto quit;
1032   }
1033 
1034 quit:
1035   free(path);
1036   free(query);
1037 
1038   return rc;
1039 }
1040 
_ldap_url_parse(struct Curl_easy * data,const struct connectdata * conn,LDAPURLDesc ** ludpp)1041 static int _ldap_url_parse(struct Curl_easy *data,
1042                            const struct connectdata *conn,
1043                            LDAPURLDesc **ludpp)
1044 {
1045   LDAPURLDesc *ludp = calloc(1, sizeof(*ludp));
1046   int rc;
1047 
1048   *ludpp = NULL;
1049   if(!ludp)
1050      return LDAP_NO_MEMORY;
1051 
1052   rc = _ldap_url_parse2(data, conn, ludp);
1053   if(rc != LDAP_SUCCESS) {
1054     _ldap_free_urldesc(ludp);
1055     ludp = NULL;
1056   }
1057   *ludpp = ludp;
1058   return (rc);
1059 }
1060 
_ldap_free_urldesc(LDAPURLDesc * ludp)1061 static void _ldap_free_urldesc(LDAPURLDesc *ludp)
1062 {
1063   if(!ludp)
1064     return;
1065 
1066 #if defined(USE_WIN32_LDAP)
1067   curlx_unicodefree(ludp->lud_dn);
1068   curlx_unicodefree(ludp->lud_filter);
1069 #else
1070   free(ludp->lud_dn);
1071   free(ludp->lud_filter);
1072 #endif
1073 
1074   if(ludp->lud_attrs) {
1075     size_t i;
1076     for(i = 0; i < ludp->lud_attrs_dups; i++) {
1077 #if defined(USE_WIN32_LDAP)
1078       curlx_unicodefree(ludp->lud_attrs[i]);
1079 #else
1080       free(ludp->lud_attrs[i]);
1081 #endif
1082     }
1083     free(ludp->lud_attrs);
1084   }
1085 
1086   free(ludp);
1087 }
1088 #endif  /* !HAVE_LDAP_URL_PARSE */
1089 #endif  /* !CURL_DISABLE_LDAP && !USE_OPENLDAP */
1090