Coverage Report

Created: 2026-12-01 06:26

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/curl/lib/openldap.c
Line
Count
Source
1
/***************************************************************************
2
 *                      _   _ ____  _
3
 *  Project         ___| | | |  _ \| |
4
 *                 / __| | | | |_) | |
5
 *                | (__| |_| |  _ <| |___
6
 *                 \___|\___/|_| \_\_____|
7
 *
8
 * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
9
 * Copyright (C) Howard Chu, <hyc@openldap.org>
10
 *
11
 * This software is licensed as described in the file COPYING, which
12
 * you should have received as part of this distribution. The terms
13
 * are also available at https://curl.se/docs/copyright.html.
14
 *
15
 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
16
 * copies of the Software, and permit persons to whom the Software is
17
 * furnished to do so, under the terms of the COPYING file.
18
 *
19
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
20
 * KIND, either express or implied.
21
 *
22
 * SPDX-License-Identifier: curl
23
 *
24
 ***************************************************************************/
25
#include "curl_setup.h"
26
27
#if !defined(CURL_DISABLE_LDAP) && defined(USE_OPENLDAP)
28
29
/*
30
 * Notice that USE_OPENLDAP is only a source code selection switch. When
31
 * libcurl is built with USE_OPENLDAP defined the libcurl source code that
32
 * gets compiled is the code from openldap.c, otherwise the code that gets
33
 * compiled is the code from ldap.c.
34
 *
35
 * When USE_OPENLDAP is defined a recent version of the OpenLDAP library
36
 * might be required for compilation and runtime. In order to use ancient
37
 * OpenLDAP library versions, USE_OPENLDAP shall not be defined.
38
 */
39
40
#include <ldap.h>
41
42
#include "urldata.h"
43
#include "url.h"
44
#include "sendf.h"
45
#include "curl_trc.h"
46
#include "vtls/vtls.h"
47
#include "transfer.h"
48
#include "curl_ldap.h"
49
#include "curlx/base64.h"
50
#include "cfilters.h"
51
#include "connect.h"
52
#include "curl_sasl.h"
53
#include "strcase.h"
54
#include "bufref.h"
55
56
/*
57
 * Uncommenting this will enable the built-in debug logging of the openldap
58
 * library. The debug log level can be set using the CURL_OPENLDAP_TRACE
59
 * environment variable. The debug output is written to stderr.
60
 *
61
 * The library supports the following debug flags:
62
 * LDAP_DEBUG_NONE         0x0000
63
 * LDAP_DEBUG_TRACE        0x0001
64
 * LDAP_DEBUG_CONSTRUCT    0x0002
65
 * LDAP_DEBUG_DESTROY      0x0004
66
 * LDAP_DEBUG_PARAMETER    0x0008
67
 * LDAP_DEBUG_ANY          0xffff
68
 *
69
 * For example, use CURL_OPENLDAP_TRACE=0 for no debug,
70
 * CURL_OPENLDAP_TRACE=2 for LDAP_DEBUG_CONSTRUCT messages only,
71
 * CURL_OPENLDAP_TRACE=65535 for all debug message levels.
72
 */
73
/* #define CURL_OPENLDAP_DEBUG */
74
75
/* Machine states. */
76
typedef enum {
77
  OLDAP_STOP,           /* Do nothing state, stops the state machine */
78
  OLDAP_SSL,            /* Performing SSL handshake. */
79
  OLDAP_STARTTLS,       /* STARTTLS request sent. */
80
  OLDAP_TLS,            /* Performing TLS handshake. */
81
  OLDAP_MECHS,          /* Get SASL authentication mechanisms. */
82
  OLDAP_SASL,           /* SASL binding reply. */
83
  OLDAP_BIND,           /* Simple bind reply. */
84
  OLDAP_BINDV2,         /* Simple bind reply in protocol version 2. */
85
  OLDAP_LAST            /* Never used */
86
} ldapstate;
87
88
#ifndef _LDAP_PVT_H
89
extern int ldap_pvt_url_scheme2proto(const char *);
90
extern int ldap_init_fd(ber_socket_t fd, int proto, const char *url,
91
                        LDAP **ld);
92
#endif
93
94
static Curl_recv oldap_recv;
95
96
struct ldapconninfo {
97
  struct SASL sasl;          /* SASL-related parameters */
98
  LDAP *ld;                  /* Openldap connection handle. */
99
  Curl_recv *recv;           /* For stacking SSL handler */
100
  Curl_send *send;
101
  struct berval *servercred; /* SASL data from server. */
102
  ldapstate state;           /* Current machine state. */
103
  curl_socket_t dupfd;       /* duplicated socket */
104
  int proto;                 /* LDAP_PROTO_TCP/LDAP_PROTO_UDP/LDAP_PROTO_IPC */
105
  int msgid;                 /* Current message id. */
106
  bool send_blocked;         /* last TLS send returned CURLE_AGAIN */
107
};
108
109
struct ldapreqinfo {
110
  int msgid;
111
  int nument;
112
};
113
114
/* meta key for storing ldapconninfo at easy handle */
115
0
#define CURL_META_LDAP_EASY   "meta:proto:ldap:easy"
116
/* meta key for storing ldapconninfo at connection */
117
0
#define CURL_META_LDAP_CONN   "meta:proto:ldap:conn"
118
119
/*
120
 * oldap_state()
121
 *
122
 * This is the ONLY way to change LDAP state!
123
 */
124
static void oldap_state(struct Curl_easy *data, struct ldapconninfo *li,
125
                        ldapstate newstate)
126
0
{
127
0
#if defined(DEBUGBUILD) && defined(CURLVERBOSE)
128
  /* for debug purposes */
129
0
  static const char * const names[] = {
130
0
    "STOP",
131
0
    "SSL",
132
0
    "STARTTLS",
133
0
    "TLS",
134
0
    "MECHS",
135
0
    "SASL",
136
0
    "BIND",
137
0
    "BINDV2",
138
    /* LAST */
139
0
  };
140
141
0
  if(li->state != newstate)
142
0
    infof(data, "LDAP %p state change from %s to %s",
143
0
          (void *)li, names[li->state], names[newstate]);
144
#else
145
  (void)data;
146
#endif
147
0
  li->state = newstate;
148
0
}
149
150
/*
151
 * Non-blocking ldap_result() for a single response to 'msgid'.
152
 *
153
 * OpenLDAP keeps every unsolicited notification (message id 0, RFC 4511
154
 * section 4.4) it reads off the socket queued until the application asks
155
 * for it. We never do, so a server could otherwise make that queue grow
156
 * without bound. Discard them as they arrive.
157
 */
158
static int oldap_result(struct ldapconninfo *li, int msgid, LDAPMessage **msg)
159
0
{
160
0
  struct timeval tv = { 0, 0 };
161
0
  int rc = ldap_result(li->ld, msgid, LDAP_MSG_ONE, &tv, msg);
162
0
  ldap_msgdelete(li->ld, LDAP_RES_UNSOLICITED);
163
0
  return rc;
164
0
}
165
166
/* Map some particular LDAP error codes to CURLcode values. */
167
static CURLcode oldap_map_error(int rc, CURLcode result)
168
0
{
169
0
  switch(rc) {
170
0
  case LDAP_NO_MEMORY:
171
0
    return CURLE_OUT_OF_MEMORY;
172
0
  case LDAP_INVALID_CREDENTIALS:
173
0
    return CURLE_LOGIN_DENIED;
174
0
  case LDAP_PROTOCOL_ERROR:
175
0
    return CURLE_UNSUPPORTED_PROTOCOL;
176
0
  case LDAP_INSUFFICIENT_ACCESS:
177
0
    return CURLE_REMOTE_ACCESS_DENIED;
178
0
  }
179
0
  return result;
180
0
}
181
182
static CURLcode oldap_url_parse(struct Curl_easy *data, LDAPURLDesc **ludp)
183
0
{
184
0
  CURLcode result = CURLE_OK;
185
0
  int rc;
186
0
  static const char * const url_errs[] = {
187
0
    "success",
188
0
    "out of memory",
189
0
    "bad parameter",
190
0
    "unrecognized scheme",
191
0
    "unbalanced delimiter",
192
0
    "bad URL",
193
0
    "bad host or port",
194
0
    "bad or missing attributes",
195
0
    "bad or missing scope",
196
0
    "bad or missing filter",
197
0
    "bad or missing extensions"
198
0
  };
199
200
0
  *ludp = NULL;
201
  /* `ldap_url_parse() seems to be terrible with urls
202
   * that have user/pass/options in it. So when we have options or
203
   * creds from the url, fail without calling the function.
204
   * Yes, this is super-weird code and I do not like it. */
205
0
  if((data->state.creds && (data->state.creds->source == CREDS_URL)) ||
206
0
     data->state.up.options)
207
0
    rc = LDAP_URL_ERR_BADURL;
208
0
  else
209
0
    rc = ldap_url_parse(Curl_bufref_ptr(&data->state.url), ludp);
210
211
0
  if(rc != LDAP_URL_SUCCESS) {
212
0
    const char *msg = "url parsing problem";
213
214
0
    result = rc == LDAP_URL_ERR_MEM ? CURLE_OUT_OF_MEMORY :
215
0
      CURLE_URL_MALFORMAT;
216
0
    rc -= LDAP_URL_SUCCESS;
217
0
    if((size_t)rc < CURL_ARRAYSIZE(url_errs))
218
0
      msg = url_errs[rc];
219
0
    failf(data, "LDAP local: %s", msg);
220
0
  }
221
0
  return result;
222
0
}
223
224
/* Parse the login options. */
225
static CURLcode oldap_parse_login_options(struct connectdata *conn)
226
0
{
227
0
  CURLcode result = CURLE_OK;
228
0
  struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN);
229
0
  const char *ptr = conn->options;
230
231
0
  DEBUGASSERT(li);
232
0
  if(!li)
233
0
    return CURLE_FAILED_INIT;
234
235
0
  while(!result && ptr && *ptr) {
236
0
    const char *key = ptr;
237
0
    const char *value;
238
239
0
    while(*ptr && *ptr != '=')
240
0
      ptr++;
241
242
0
    value = ptr + 1;
243
244
0
    while(*ptr && *ptr != ';')
245
0
      ptr++;
246
247
0
    if(checkprefix("AUTH=", key))
248
0
      result = Curl_sasl_parse_url_auth_option(&li->sasl, value, ptr - value);
249
0
    else
250
0
      result = CURLE_SETOPT_OPTION_SYNTAX;
251
252
0
    if(*ptr == ';')
253
0
      ptr++;
254
0
  }
255
256
0
  return result == CURLE_URL_MALFORMAT ? CURLE_SETOPT_OPTION_SYNTAX : result;
257
0
}
258
259
static CURLcode oldap_setup_connection(struct Curl_easy *data,
260
                                       struct connectdata *conn)
261
0
{
262
0
  CURLcode result;
263
0
  LDAPURLDesc *lud;
264
0
  (void)conn;
265
266
  /* Early URL syntax check. */
267
0
  result = oldap_url_parse(data, &lud);
268
0
  ldap_free_urldesc(lud);
269
270
0
  return result;
271
0
}
272
273
/*
274
 * Get the SASL authentication challenge from the server credential buffer.
275
 */
276
static CURLcode oldap_get_message(struct Curl_easy *data, struct bufref *out)
277
0
{
278
0
  struct ldapconninfo *li =
279
0
    Curl_conn_meta_get(data->conn, CURL_META_LDAP_CONN);
280
0
  struct berval *servercred = li ? li->servercred : NULL;
281
0
  DEBUGASSERT(li);
282
0
  if(!li)
283
0
    return CURLE_FAILED_INIT;
284
285
0
  if(!servercred || !servercred->bv_val)
286
0
    return CURLE_WEIRD_SERVER_REPLY;
287
0
  Curl_bufref_set(out, servercred->bv_val, servercred->bv_len, NULL);
288
0
  return CURLE_OK;
289
0
}
290
291
/*
292
 * Sends an initial SASL bind request to the server.
293
 */
294
static CURLcode oldap_perform_auth(struct Curl_easy *data, const char *mech,
295
                                   const struct bufref *initresp)
296
0
{
297
0
  struct connectdata *conn = data->conn;
298
0
  struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN);
299
0
  struct berval cred;
300
0
  struct berval *pcred = &cred;
301
0
  int rc;
302
303
0
  DEBUGASSERT(li);
304
0
  if(!li)
305
0
    return CURLE_FAILED_INIT;
306
0
  cred.bv_val = (char *)CURL_UNCONST(Curl_bufref_ptr(initresp));
307
0
  cred.bv_len = Curl_bufref_len(initresp);
308
0
  if(!cred.bv_val)
309
0
    pcred = NULL;
310
0
  rc = ldap_sasl_bind(li->ld, NULL, mech, pcred, NULL, NULL, &li->msgid);
311
0
  if(rc != LDAP_SUCCESS)
312
0
    return oldap_map_error(rc, CURLE_LDAP_CANNOT_BIND);
313
0
  return CURLE_OK;
314
0
}
315
316
/*
317
 * Sends SASL continuation.
318
 */
319
static CURLcode oldap_continue_auth(struct Curl_easy *data, const char *mech,
320
                                    const struct bufref *resp)
321
0
{
322
0
  struct connectdata *conn = data->conn;
323
0
  struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN);
324
0
  struct berval cred;
325
0
  struct berval *pcred = &cred;
326
0
  int rc;
327
328
0
  if(!li)
329
0
    return CURLE_FAILED_INIT;
330
0
  cred.bv_val = (char *)CURL_UNCONST(Curl_bufref_ptr(resp));
331
0
  cred.bv_len = Curl_bufref_len(resp);
332
0
  if(!cred.bv_val)
333
0
    pcred = NULL;
334
0
  rc = ldap_sasl_bind(li->ld, NULL, mech, pcred, NULL, NULL, &li->msgid);
335
0
  if(rc != LDAP_SUCCESS)
336
0
    return oldap_map_error(rc, CURLE_LDAP_CANNOT_BIND);
337
0
  return CURLE_OK;
338
0
}
339
340
/*
341
 * Sends SASL bind cancellation.
342
 */
343
static CURLcode oldap_cancel_auth(struct Curl_easy *data, const char *mech)
344
0
{
345
0
  struct ldapconninfo *li =
346
0
    Curl_conn_meta_get(data->conn, CURL_META_LDAP_CONN);
347
0
  int rc;
348
349
0
  (void)mech;
350
0
  if(!li)
351
0
    return CURLE_FAILED_INIT;
352
0
  rc = ldap_sasl_bind(li->ld, NULL, LDAP_SASL_NULL, NULL, NULL, NULL,
353
0
                      &li->msgid);
354
0
  if(rc != LDAP_SUCCESS)
355
0
    return oldap_map_error(rc, CURLE_LDAP_CANNOT_BIND);
356
0
  return CURLE_OK;
357
0
}
358
359
/* Starts LDAP simple bind. */
360
static CURLcode oldap_perform_bind(struct Curl_easy *data, ldapstate newstate)
361
0
{
362
0
  struct connectdata *conn = data->conn;
363
0
  struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN);
364
0
  const char *binddn = NULL;
365
0
  struct berval passwd;
366
0
  int rc;
367
368
0
  if(!li)
369
0
    return CURLE_FAILED_INIT;
370
0
  passwd.bv_val = NULL;
371
0
  passwd.bv_len = 0;
372
373
0
  if(conn->creds) {
374
0
    binddn = Curl_creds_user(conn->creds);
375
0
    passwd.bv_val = CURL_UNCONST(Curl_creds_passwd(conn->creds));
376
0
    passwd.bv_len = strlen(passwd.bv_val);
377
0
  }
378
379
0
  rc = ldap_sasl_bind(li->ld, binddn, LDAP_SASL_SIMPLE, &passwd,
380
0
                      NULL, NULL, &li->msgid);
381
0
  if(rc != LDAP_SUCCESS)
382
0
    return oldap_map_error(rc,
383
0
                           data->state.creds ?
384
0
                           CURLE_LOGIN_DENIED : CURLE_LDAP_CANNOT_BIND);
385
0
  oldap_state(data, li, newstate);
386
0
  return CURLE_OK;
387
0
}
388
389
/* Query the supported SASL authentication mechanisms. */
390
static CURLcode oldap_perform_mechs(struct Curl_easy *data)
391
0
{
392
0
  struct ldapconninfo *li =
393
0
    Curl_conn_meta_get(data->conn, CURL_META_LDAP_CONN);
394
0
  int rc;
395
0
  static const char * const supportedSASLMechanisms[] = {
396
0
    "supportedSASLMechanisms",
397
0
    NULL
398
0
  };
399
400
0
  if(!li)
401
0
    return CURLE_FAILED_INIT;
402
  /* Casting away the const for the 3rd parameter that the LDAP API expects as
403
     a non-const char ** is potentially unsafe but we believe the lack of
404
     const in the API was an oversight and that no LDAP implementation
405
     actually modifies the input. */
406
0
  rc = ldap_search_ext(li->ld, "", LDAP_SCOPE_BASE, "(objectclass=*)",
407
0
                       (char **)CURL_UNCONST(supportedSASLMechanisms), 0,
408
0
                       NULL, NULL, NULL, 0, &li->msgid);
409
0
  if(rc != LDAP_SUCCESS)
410
0
    return oldap_map_error(rc, CURLE_LOGIN_DENIED);
411
0
  oldap_state(data, li, OLDAP_MECHS);
412
0
  return CURLE_OK;
413
0
}
414
415
/* Starts SASL bind. */
416
static CURLcode oldap_perform_sasl(struct Curl_easy *data)
417
0
{
418
0
  struct ldapconninfo *li =
419
0
    Curl_conn_meta_get(data->conn, CURL_META_LDAP_CONN);
420
0
  saslprogress progress = SASL_IDLE;
421
0
  CURLcode result;
422
423
0
  if(!li)
424
0
    return CURLE_FAILED_INIT;
425
0
  result = Curl_sasl_start(&li->sasl, data, TRUE, &progress);
426
427
0
  oldap_state(data, li, OLDAP_SASL);
428
0
  if(!result && progress != SASL_INPROGRESS)
429
0
    result = Curl_sasl_is_blocked(&li->sasl, data);
430
0
  return result;
431
0
}
432
433
#ifdef USE_SSL
434
static int ldapsb_tls_setup(Sockbuf_IO_Desc *sbiod, void *arg)
435
0
{
436
0
  sbiod->sbiod_pvt = arg;
437
0
  return 0;
438
0
}
439
440
static int ldapsb_tls_remove(Sockbuf_IO_Desc *sbiod)
441
0
{
442
0
  sbiod->sbiod_pvt = NULL;
443
0
  return 0;
444
0
}
445
446
/* if there is a duplicated socket to close, close it */
447
static int ldapsb_tls_close(Sockbuf_IO_Desc *sbiod)
448
0
{
449
0
  struct Curl_easy *data = sbiod->sbiod_pvt;
450
0
  if(data) {
451
0
    struct connectdata *conn = data->conn;
452
0
    if(conn) {
453
0
      struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN);
454
0
      if(li && (li->dupfd != CURL_SOCKET_BAD)) {
455
0
        sclose(li->dupfd);
456
0
        li->dupfd = CURL_SOCKET_BAD;
457
0
      }
458
0
    }
459
0
  }
460
461
0
  return 0;
462
0
}
463
464
static int ldapsb_tls_ctrl(Sockbuf_IO_Desc *sbiod, int opt, void *arg)
465
0
{
466
0
  (void)arg;
467
0
  if(opt == LBER_SB_OPT_DATA_READY) {
468
0
    struct Curl_easy *data = sbiod->sbiod_pvt;
469
0
    return Curl_conn_data_pending(data);
470
0
  }
471
0
  return 0;
472
0
}
473
474
static ber_slen_t ldapsb_tls_read(Sockbuf_IO_Desc *sbiod, void *buf,
475
                                  ber_len_t len)
476
0
{
477
0
  struct Curl_easy *data = sbiod->sbiod_pvt;
478
0
  ber_slen_t ret = 0;
479
0
  if(data) {
480
0
    struct connectdata *conn = data->conn;
481
0
    if(conn) {
482
0
      struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN);
483
0
      CURLcode result = CURLE_RECV_ERROR;
484
0
      size_t nread;
485
486
0
      if(!li) {
487
0
        SET_SOCKERRNO(SOCKEINVAL);
488
0
        return -1;
489
0
      }
490
0
      result = li->recv(data, buf, len, &nread);
491
0
      if(result == CURLE_AGAIN) {
492
0
        SET_SOCKERRNO(SOCKEWOULDBLOCK);
493
0
      }
494
0
      ret = result ? -1 : (ber_slen_t)nread;
495
0
    }
496
0
  }
497
0
  return ret;
498
0
}
499
500
static ber_slen_t ldapsb_tls_write(Sockbuf_IO_Desc *sbiod, void *buf,
501
                                   ber_len_t len)
502
0
{
503
0
  struct Curl_easy *data = sbiod->sbiod_pvt;
504
0
  ber_slen_t ret = 0;
505
0
  if(data) {
506
0
    struct connectdata *conn = data->conn;
507
0
    if(conn) {
508
0
      struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN);
509
0
      CURLcode result = CURLE_SEND_ERROR;
510
0
      size_t nwritten;
511
512
0
      if(!li || !li->send) {
513
0
        SET_SOCKERRNO(SOCKEINVAL);
514
0
        return -1;
515
0
      }
516
0
      result = li->send(data, buf, len, FALSE, &nwritten);
517
0
      li->send_blocked = (result == CURLE_AGAIN);
518
0
      if(result == CURLE_AGAIN) {
519
0
        SET_SOCKERRNO(SOCKEWOULDBLOCK);
520
0
      }
521
0
      ret = result ? -1 : (ber_slen_t)nwritten;
522
0
    }
523
0
  }
524
0
  return ret;
525
0
}
526
527
static Sockbuf_IO ldapsb_tls = {
528
  ldapsb_tls_setup,
529
  ldapsb_tls_remove,
530
  ldapsb_tls_ctrl,
531
  ldapsb_tls_read,
532
  ldapsb_tls_write,
533
  ldapsb_tls_close
534
};
535
536
static bool ssl_installed(struct connectdata *conn)
537
0
{
538
0
  struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN);
539
0
  return li && li->recv;
540
0
}
541
542
static CURLcode oldap_ssl_connect(struct Curl_easy *data, ldapstate newstate)
543
0
{
544
0
  struct connectdata *conn = data->conn;
545
0
  struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN);
546
0
  bool ssldone = FALSE;
547
0
  CURLcode result;
548
549
0
  if(!li)
550
0
    return CURLE_FAILED_INIT;
551
0
  result = Curl_conn_connect(data, FALSE, &ssldone);
552
0
  if(result)
553
0
    return result;
554
0
  oldap_state(data, li, newstate);
555
556
0
  if(ssldone) {
557
0
    Sockbuf *sb;
558
559
0
    if(data->set.connect_only)
560
0
      return CURLE_BAD_FUNCTION_ARGUMENT;
561
562
    /* Install the libcurl SSL handlers into the sockbuf. */
563
0
    if((ldap_get_option(li->ld, LDAP_OPT_SOCKBUF, &sb) != LDAP_OPT_SUCCESS) ||
564
0
       ber_sockbuf_add_io(sb, &ldapsb_tls, LBER_SBIOD_LEVEL_TRANSPORT, data))
565
0
      return CURLE_FAILED_INIT;
566
0
    li->recv = conn->do_recv;
567
0
    li->send = conn->do_send;
568
0
  }
569
570
0
  return result;
571
0
}
572
573
/* Send the STARTTLS request */
574
static CURLcode oldap_perform_starttls(struct Curl_easy *data)
575
0
{
576
0
  struct ldapconninfo *li =
577
0
    Curl_conn_meta_get(data->conn, CURL_META_LDAP_CONN);
578
0
  int rc;
579
580
0
  if(!li)
581
0
    return CURLE_FAILED_INIT;
582
0
  rc = ldap_start_tls(li->ld, NULL, NULL, &li->msgid);
583
0
  if(rc != LDAP_SUCCESS)
584
0
    return oldap_map_error(rc, CURLE_USE_SSL_FAILED);
585
0
  oldap_state(data, li, OLDAP_STARTTLS);
586
0
  return CURLE_OK;
587
0
}
588
#endif
589
590
static void oldap_easy_dtor(const void *key, size_t klen, void *entry)
591
0
{
592
0
  struct ldapreqinfo *lr = entry;
593
0
  (void)key;
594
0
  (void)klen;
595
0
  curlx_free(lr);
596
0
}
597
598
static void oldap_conn_dtor(const void *key, size_t klen, void *entry)
599
0
{
600
0
  struct ldapconninfo *li = entry;
601
0
  (void)key;
602
0
  (void)klen;
603
0
  if(li->ld) {
604
0
    ldap_unbind_ext(li->ld, NULL, NULL);
605
0
    li->ld = NULL;
606
0
  }
607
0
  curlx_free(li);
608
0
}
609
610
/* SASL parameters for the ldap protocol */
611
static const struct SASLproto saslldap = {
612
  "ldap",                     /* The service name */
613
  oldap_perform_auth,         /* Send authentication command */
614
  oldap_continue_auth,        /* Send authentication continuation */
615
  oldap_cancel_auth,          /* Send authentication cancellation */
616
  oldap_get_message,          /* Get SASL response message */
617
  0,                          /* Maximum initial response length (no max) */
618
  LDAP_SASL_BIND_IN_PROGRESS, /* Code received when continuation is expected */
619
  LDAP_SUCCESS,               /* Code to receive upon authentication success */
620
  SASL_AUTH_NONE,             /* Default mechanisms */
621
  0                           /* Configuration flags */
622
};
623
624
static CURLcode oldap_connect(struct Curl_easy *data, bool *done)
625
0
{
626
0
  struct connectdata *conn = data->conn;
627
0
  struct ldapconninfo *li;
628
0
  static const int version = LDAP_VERSION3;
629
0
  char *hosturl = NULL;
630
0
  CURLcode result;
631
0
  int rc;
632
#ifdef CURL_OPENLDAP_DEBUG
633
  static int do_trace = -1;
634
#endif
635
636
0
  (void)done;
637
638
0
  li = curlx_calloc(1, sizeof(struct ldapconninfo));
639
0
  if(!li) {
640
0
    result = CURLE_OUT_OF_MEMORY;
641
0
    goto out;
642
0
  }
643
0
  li->dupfd = CURL_SOCKET_BAD;
644
645
0
  result = Curl_conn_meta_set(conn, CURL_META_LDAP_CONN, li, oldap_conn_dtor);
646
0
  if(result)
647
0
    goto out;
648
649
0
  li->proto = ldap_pvt_url_scheme2proto(data->state.origin->scheme->name);
650
651
  /* Initialize the SASL storage */
652
0
  Curl_sasl_init(&li->sasl, data, &saslldap);
653
654
0
  result = oldap_parse_login_options(conn);
655
0
  if(result)
656
0
    goto out;
657
658
0
  hosturl = curl_maprintf("%s://%s:%u",
659
0
                          conn->scheme->name,
660
0
                          conn->origin->ipv6 ?
661
0
                          conn->origin->user_hostname :
662
0
                          conn->origin->hostname,
663
0
                          conn->origin->port);
664
0
  if(!hosturl) {
665
0
    result = CURLE_OUT_OF_MEMORY;
666
0
    goto out;
667
0
  }
668
669
0
  {
670
#ifdef _WIN32
671
    SOCKET dupfd = INVALID_SOCKET;
672
    WSAPROTOCOL_INFO pi;
673
    if(WSADuplicateSocket(conn->chain.sock,
674
                          GetCurrentProcessId(), &pi))
675
      ; /* error */
676
    else
677
      dupfd = CURL_SOCKET(pi.iAddressFamily, pi.iSocketType, pi.iProtocol);
678
#else
679
0
#ifdef F_DUPFD_CLOEXEC
680
0
    int dupfd = fcntl(conn->chain.sock, F_DUPFD_CLOEXEC, 0);
681
#else
682
    int dupfd = dup(conn->chain.sock);
683
#ifdef HAVE_FCNTL
684
    if((dupfd != CURL_SOCKET_BAD) &&
685
       (fcntl(dupfd, F_SETFD, FD_CLOEXEC) < 0)) {
686
      sclose(dupfd);
687
      dupfd = CURL_SOCKET_BAD;
688
    }
689
#endif /* HAVE_FCNTL */
690
#endif /* F_DUPFD_CLOEXEC */
691
0
#endif /* _WIN32 */
692
693
0
    if(dupfd == CURL_SOCKET_BAD) {
694
0
      result = CURLE_COULDNT_CONNECT;
695
0
      goto out;
696
0
    }
697
0
    rc = ldap_init_fd((ber_socket_t)dupfd, li->proto, hosturl, &li->ld);
698
0
    if(rc)
699
0
      sclose(dupfd);
700
0
    else
701
      /* store the socket, as when this is used by TLS we close this ourselves
702
         and at this point the code does not yet know if this will use TLS or
703
         not */
704
0
      li->dupfd = dupfd;
705
0
  }
706
0
  if(rc) {
707
0
    failf(data, "LDAP local: Cannot connect to %s, %s",
708
0
          hosturl, ldap_err2string(rc));
709
0
    result = CURLE_COULDNT_CONNECT;
710
0
    goto out;
711
0
  }
712
713
#ifdef CURL_OPENLDAP_DEBUG
714
  if(do_trace < 0) {
715
    const char *env = getenv("CURL_OPENLDAP_TRACE");
716
    curl_off_t e = 0;
717
    if(!curlx_str_number(&env, &e, INT_MAX))
718
      do_trace = e > 0;
719
  }
720
  if(do_trace)
721
    ldap_set_option(li->ld, LDAP_OPT_DEBUG_LEVEL, &do_trace);
722
#endif
723
724
  /* Try version 3 first. */
725
0
  ldap_set_option(li->ld, LDAP_OPT_PROTOCOL_VERSION, &version);
726
727
  /* Do not chase referrals. */
728
0
  ldap_set_option(li->ld, LDAP_OPT_REFERRALS, LDAP_OPT_OFF);
729
730
0
  {
731
0
    ber_len_t max = 256 * 1024;
732
0
    Sockbuf *sb;
733
0
    if((ldap_get_option(li->ld, LDAP_OPT_SOCKBUF, &sb) != LDAP_OPT_SUCCESS) ||
734
       /* Set the maximum allowed size of an incoming message, which to
735
          OpenLDAP means that it will malloc() memory up to this size. If not
736
          set, there is no limit and we instead risk a malloc() failure. */
737
0
       !ber_sockbuf_ctrl(sb, LBER_SB_OPT_SET_MAX_INCOMING, &max)) {
738
0
      result = CURLE_FAILED_INIT;
739
0
      goto out;
740
0
    }
741
0
  }
742
743
0
#ifdef USE_SSL
744
0
  if(Curl_conn_is_ssl(conn)) {
745
0
    result = oldap_ssl_connect(data, OLDAP_SSL);
746
0
    goto out;
747
0
  }
748
749
0
  if(data->set.use_ssl) {
750
0
    result = oldap_perform_starttls(data);
751
0
    if(!result || data->set.use_ssl != CURLUSESSL_TRY)
752
0
      goto out;
753
0
  }
754
0
#endif
755
756
0
  if(li->sasl.prefmech != SASL_AUTH_NONE) {
757
0
    result = oldap_perform_mechs(data);
758
0
    goto out;
759
0
  }
760
761
  /* Force bind even if anonymous bind is not needed in protocol version 3
762
     to detect missing version 3 support. */
763
0
  result = oldap_perform_bind(data, OLDAP_BIND);
764
765
0
out:
766
0
  curlx_free(hosturl);
767
0
  return result;
768
0
}
769
770
/* Handle the supported SASL mechanisms query response */
771
static CURLcode oldap_state_mechs_resp(struct Curl_easy *data,
772
                                       LDAPMessage *msg, int code)
773
0
{
774
0
  struct connectdata *conn;
775
0
  struct ldapconninfo *li;
776
0
  int rc;
777
0
  BerElement *ber = NULL;
778
0
  CURLcode result = CURLE_OK;
779
0
  struct berval bv, *bvals;
780
781
0
  if(!data)
782
0
    return CURLE_FAILED_INIT;
783
784
0
  conn = data->conn;
785
0
  li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN);
786
787
0
  if(!li)
788
0
    return CURLE_FAILED_INIT;
789
0
  switch(ldap_msgtype(msg)) {
790
0
  case LDAP_RES_SEARCH_ENTRY:
791
    /* Got a list of supported SASL mechanisms. */
792
0
    if(code != LDAP_SUCCESS && code != LDAP_NO_RESULTS_RETURNED)
793
0
      return CURLE_LOGIN_DENIED;
794
795
0
    rc = ldap_get_dn_ber(li->ld, msg, &ber, &bv);
796
0
    if(rc < 0)
797
0
      return oldap_map_error(rc, CURLE_BAD_CONTENT_ENCODING);
798
0
    for(rc = ldap_get_attribute_ber(li->ld, msg, ber, &bv, &bvals);
799
0
        rc == LDAP_SUCCESS;
800
0
        rc = ldap_get_attribute_ber(li->ld, msg, ber, &bv, &bvals)) {
801
0
      int i;
802
803
0
      if(!bv.bv_val)
804
0
        break;
805
806
0
      if(bvals) {
807
0
        for(i = 0; bvals[i].bv_val; i++) {
808
0
          size_t llen;
809
0
          unsigned short mech =
810
0
            Curl_sasl_decode_mech((const char *)bvals[i].bv_val,
811
0
                                  bvals[i].bv_len, &llen);
812
0
          if(bvals[i].bv_len == llen)
813
0
            li->sasl.authmechs |= mech;
814
0
        }
815
0
        ber_memfree(bvals);
816
0
      }
817
0
    }
818
0
    ber_free(ber, 0);
819
0
    break;
820
821
0
  case LDAP_RES_SEARCH_RESULT:
822
0
    switch(code) {
823
0
    case LDAP_SIZELIMIT_EXCEEDED:
824
0
      infof(data, "Too many authentication mechanisms");
825
0
      FALLTHROUGH();
826
0
    case LDAP_SUCCESS:
827
0
    case LDAP_NO_RESULTS_RETURNED:
828
0
      if(Curl_sasl_can_authenticate(&li->sasl, data))
829
0
        result = oldap_perform_sasl(data);
830
0
      else
831
0
        result = CURLE_LOGIN_DENIED;
832
0
      break;
833
0
    default:
834
0
      result = oldap_map_error(code, CURLE_LOGIN_DENIED);
835
0
      break;
836
0
    }
837
0
    break;
838
0
  default:
839
0
    break;
840
0
  }
841
0
  return result;
842
0
}
843
844
/* Handle a SASL bind response. */
845
static CURLcode oldap_state_sasl_resp(struct Curl_easy *data,
846
                                      LDAPMessage *msg, int code)
847
0
{
848
0
  struct connectdata *conn = data->conn;
849
0
  struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN);
850
0
  CURLcode result = CURLE_OK;
851
0
  saslprogress progress;
852
0
  int rc;
853
854
0
  if(!li)
855
0
    return CURLE_FAILED_INIT;
856
0
  li->servercred = NULL;
857
0
  rc = ldap_parse_sasl_bind_result(li->ld, msg, &li->servercred, 0);
858
0
  if(rc != LDAP_SUCCESS) {
859
0
    failf(data, "LDAP local: sasl ldap_parse_result %s", ldap_err2string(rc));
860
0
    result = oldap_map_error(rc, CURLE_LOGIN_DENIED);
861
0
  }
862
0
  else {
863
0
    result = Curl_sasl_continue(&li->sasl, data, code, &progress);
864
0
    if(!result) {
865
0
      switch(progress) {
866
0
      case SASL_DONE:
867
0
        oldap_state(data, li, OLDAP_STOP);   /* Authenticated */
868
0
        break;
869
0
      case SASL_IDLE:            /* No mechanism left after cancellation */
870
0
        failf(data, "Authentication cancelled");
871
0
        result = CURLE_LOGIN_DENIED;
872
0
        break;
873
0
      default:
874
0
        break;
875
0
      }
876
0
    }
877
0
  }
878
879
0
  if(li->servercred)
880
0
    ber_bvfree(li->servercred);
881
0
  return result;
882
0
}
883
884
/* Handle a simple bind response. */
885
static CURLcode oldap_state_bind_resp(struct Curl_easy *data, LDAPMessage *msg,
886
                                      int code)
887
0
{
888
0
  struct connectdata *conn = data->conn;
889
0
  struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN);
890
0
  CURLcode result = CURLE_OK;
891
0
  struct berval *bv = NULL;
892
0
  int rc;
893
894
0
  if(!li)
895
0
    return CURLE_FAILED_INIT;
896
897
0
  if(code != LDAP_SUCCESS)
898
0
    return oldap_map_error(code, CURLE_LDAP_CANNOT_BIND);
899
900
0
  rc = ldap_parse_sasl_bind_result(li->ld, msg, &bv, 0);
901
0
  if(rc != LDAP_SUCCESS) {
902
0
    failf(data, "LDAP local: bind ldap_parse_sasl_bind_result %s",
903
0
          ldap_err2string(rc));
904
0
    result = oldap_map_error(rc, CURLE_LDAP_CANNOT_BIND);
905
0
  }
906
0
  else
907
0
    oldap_state(data, li, OLDAP_STOP);
908
909
0
  if(bv)
910
0
    ber_bvfree(bv);
911
0
  return result;
912
0
}
913
914
static CURLcode oldap_connecting(struct Curl_easy *data, bool *done)
915
0
{
916
0
  CURLcode result = CURLE_OK;
917
0
  struct connectdata *conn = data->conn;
918
0
  struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN);
919
0
  LDAPMessage *msg = NULL;
920
0
  int code = LDAP_SUCCESS;
921
0
  int rc;
922
923
0
  if(!li)
924
0
    return CURLE_FAILED_INIT;
925
926
0
  if(li->state != OLDAP_SSL && li->state != OLDAP_TLS) {
927
    /* Get response to last command. */
928
0
    rc = oldap_result(li, li->msgid, &msg);
929
0
    switch(rc) {
930
0
    case 0:                               /* Timed out. */
931
0
      return CURLE_OK;
932
0
    case LDAP_RES_SEARCH_ENTRY:
933
0
    case LDAP_RES_SEARCH_REFERENCE:
934
0
      break;
935
0
    default:
936
0
      li->msgid = 0;                      /* Nothing to abandon upon error. */
937
0
      if(rc < 0) {
938
0
        failf(data, "LDAP local: connecting ldap_result %s",
939
0
              ldap_err2string(rc));
940
0
        return oldap_map_error(rc, CURLE_COULDNT_CONNECT);
941
0
      }
942
0
      break;
943
0
    }
944
945
    /* Get error code from message. */
946
0
    rc = ldap_parse_result(li->ld, msg, &code, NULL, NULL, NULL, NULL, 0);
947
0
    if(rc)
948
0
      code = rc;
949
0
    else {
950
      /* store the latest code for later retrieval */
951
0
      data->info.httpcode = code;
952
0
    }
953
954
    /* If protocol version 3 is not supported, fallback to version 2. */
955
0
    if(code == LDAP_PROTOCOL_ERROR && li->state != OLDAP_BINDV2 &&
956
0
#ifdef USE_SSL
957
0
       (ssl_installed(conn) || data->set.use_ssl <= CURLUSESSL_TRY) &&
958
0
#endif
959
0
       li->sasl.prefmech == SASL_AUTH_NONE) {
960
0
      static const int version = LDAP_VERSION2;
961
962
0
      ldap_set_option(li->ld, LDAP_OPT_PROTOCOL_VERSION, &version);
963
0
      ldap_msgfree(msg);
964
0
      return oldap_perform_bind(data, OLDAP_BINDV2);
965
0
    }
966
0
  }
967
968
  /* Handle response message according to current state. */
969
0
  switch(li->state) {
970
971
0
#ifdef USE_SSL
972
0
  case OLDAP_SSL:
973
0
    result = oldap_ssl_connect(data, OLDAP_SSL);
974
0
    if(!result && ssl_installed(conn)) {
975
0
      if(li->sasl.prefmech != SASL_AUTH_NONE)
976
0
        result = oldap_perform_mechs(data);
977
0
      else
978
0
        result = oldap_perform_bind(data, OLDAP_BIND);
979
0
    }
980
0
    break;
981
0
  case OLDAP_STARTTLS:
982
0
    if(code != LDAP_SUCCESS) {
983
0
      if(data->set.use_ssl != CURLUSESSL_TRY)
984
0
        result = oldap_map_error(code, CURLE_USE_SSL_FAILED);
985
0
      else if(li->sasl.prefmech != SASL_AUTH_NONE)
986
0
        result = oldap_perform_mechs(data);
987
0
      else
988
0
        result = oldap_perform_bind(data, OLDAP_BIND);
989
0
      break;
990
0
    }
991
0
    result = Curl_ssl_cfilter_add(
992
0
      data, Curl_conn_get_origin(conn), &conn->chain);
993
0
    if(result)
994
0
      break;
995
0
    FALLTHROUGH();
996
0
  case OLDAP_TLS:
997
0
    result = oldap_ssl_connect(data, OLDAP_TLS);
998
0
    if(result)
999
0
      result = oldap_map_error(code, CURLE_USE_SSL_FAILED);
1000
0
    else if(ssl_installed(conn)) {
1001
0
      if(li->sasl.prefmech != SASL_AUTH_NONE)
1002
0
        result = oldap_perform_mechs(data);
1003
0
      else if(data->state.creds)
1004
0
        result = oldap_perform_bind(data, OLDAP_BIND);
1005
0
      else {
1006
        /* Version 3 supported: no bind required */
1007
0
        oldap_state(data, li, OLDAP_STOP);
1008
0
        result = CURLE_OK;
1009
0
      }
1010
0
    }
1011
0
    break;
1012
0
#endif
1013
1014
0
  case OLDAP_MECHS:
1015
0
    result = oldap_state_mechs_resp(data, msg, code);
1016
0
    break;
1017
0
  case OLDAP_SASL:
1018
0
    result = oldap_state_sasl_resp(data, msg, code);
1019
0
    break;
1020
0
  case OLDAP_BIND:
1021
0
  case OLDAP_BINDV2:
1022
0
    result = oldap_state_bind_resp(data, msg, code);
1023
0
    break;
1024
0
  default:
1025
    /* internal error */
1026
0
    result = CURLE_COULDNT_CONNECT;
1027
0
    break;
1028
0
  }
1029
1030
0
  ldap_msgfree(msg);
1031
1032
0
  *done = li->state == OLDAP_STOP;
1033
0
  if(*done)
1034
0
    conn->do_recv = oldap_recv;
1035
1036
0
  if(result && li->msgid) {
1037
0
    ldap_abandon_ext(li->ld, li->msgid, NULL, NULL);
1038
0
    li->msgid = 0;
1039
0
  }
1040
0
  return result;
1041
0
}
1042
1043
static CURLcode oldap_disconnect(struct Curl_easy *data,
1044
                                 struct connectdata *conn,
1045
                                 bool dead_connection)
1046
0
{
1047
0
  struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN);
1048
0
  (void)dead_connection;
1049
#ifndef USE_SSL
1050
  (void)data;
1051
#endif
1052
1053
0
  if(li && li->ld) {
1054
0
#ifdef USE_SSL
1055
0
    if(ssl_installed(conn)) {
1056
0
      Sockbuf *sb;
1057
      /* a blocked TLS send must be retried as-is, do not send the unbind */
1058
0
      if(li->send_blocked)
1059
0
        li->send = NULL;
1060
0
      if(ldap_get_option(li->ld, LDAP_OPT_SOCKBUF, &sb) != LDAP_OPT_SUCCESS ||
1061
0
         ber_sockbuf_add_io(sb, &ldapsb_tls, LBER_SBIOD_LEVEL_TRANSPORT, data))
1062
0
        return CURLE_FAILED_INIT;
1063
0
    }
1064
0
#endif
1065
0
    ldap_unbind_ext(li->ld, NULL, NULL);
1066
0
    li->ld = NULL;
1067
0
  }
1068
0
  return CURLE_OK;
1069
0
}
1070
1071
static CURLcode oldap_do(struct Curl_easy *data, bool *done)
1072
0
{
1073
0
  struct connectdata *conn = data->conn;
1074
0
  struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN);
1075
0
  struct ldapreqinfo *lr;
1076
0
  CURLcode result;
1077
0
  int rc;
1078
0
  LDAPURLDesc *lud;
1079
0
  int msgid;
1080
1081
0
  if(!li)
1082
0
    return CURLE_FAILED_INIT;
1083
1084
0
  infof(data, "LDAP local: %s", Curl_bufref_ptr(&data->state.url));
1085
1086
0
  result = oldap_url_parse(data, &lud);
1087
0
  if(result)
1088
0
    goto out;
1089
1090
0
#ifdef USE_SSL
1091
0
  if(ssl_installed(conn)) {
1092
0
    Sockbuf *sb;
1093
    /* re-install the libcurl SSL handlers into the sockbuf. */
1094
0
    if((ldap_get_option(li->ld, LDAP_OPT_SOCKBUF, &sb) != LDAP_OPT_SUCCESS) ||
1095
0
       ber_sockbuf_add_io(sb, &ldapsb_tls, LBER_SBIOD_LEVEL_TRANSPORT, data)) {
1096
0
      ldap_free_urldesc(lud);
1097
0
      return CURLE_FAILED_INIT;
1098
0
    }
1099
0
  }
1100
0
#endif
1101
1102
0
  rc = ldap_search_ext(li->ld, lud->lud_dn, lud->lud_scope,
1103
0
                       lud->lud_filter, lud->lud_attrs, 0,
1104
0
                       NULL, NULL, NULL, 0, &msgid);
1105
0
  ldap_free_urldesc(lud);
1106
0
  if(rc != LDAP_SUCCESS) {
1107
0
    failf(data, "LDAP local: ldap_search_ext %s", ldap_err2string(rc));
1108
0
    result = CURLE_LDAP_SEARCH_FAILED;
1109
0
    goto out;
1110
0
  }
1111
1112
0
  lr = curlx_calloc(1, sizeof(struct ldapreqinfo));
1113
0
  if(!lr ||
1114
0
     Curl_meta_set(data, CURL_META_LDAP_EASY, lr, oldap_easy_dtor)) {
1115
0
    ldap_abandon_ext(li->ld, msgid, NULL, NULL);
1116
0
    result = CURLE_OUT_OF_MEMORY;
1117
0
    goto out;
1118
0
  }
1119
1120
0
  lr->msgid = msgid;
1121
0
  Curl_xfer_setup_recv(data, -1);
1122
0
  *done = TRUE;
1123
1124
0
out:
1125
0
  return result;
1126
0
}
1127
1128
static CURLcode oldap_done(struct Curl_easy *data, CURLcode res,
1129
                           bool premature)
1130
0
{
1131
0
  struct connectdata *conn = data->conn;
1132
0
  struct ldapreqinfo *lr = Curl_meta_get(data, CURL_META_LDAP_EASY);
1133
1134
0
  (void)res;
1135
0
  (void)premature;
1136
1137
0
  if(lr) {
1138
    /* if there was a search in progress, abandon it */
1139
0
    if(lr->msgid) {
1140
0
      struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN);
1141
0
      if(li && li->ld) {
1142
0
        ldap_abandon_ext(li->ld, lr->msgid, NULL, NULL);
1143
0
      }
1144
0
      lr->msgid = 0;
1145
0
    }
1146
0
    Curl_meta_remove(data, CURL_META_LDAP_EASY);
1147
0
  }
1148
1149
0
  return CURLE_OK;
1150
0
}
1151
1152
static CURLcode client_write(struct Curl_easy *data,
1153
                             const char *prefix, size_t plen,
1154
                             const char *value, size_t len,
1155
                             const char *suffix, size_t slen)
1156
0
{
1157
0
  CURLcode result = CURLE_OK;
1158
1159
0
  if(prefix) {
1160
    /* If we have a zero-length value and the prefix ends with a space
1161
       separator, drop the latter. */
1162
0
    if(!len && plen && prefix[plen - 1] == ' ')
1163
0
      plen--;
1164
0
    result = Curl_client_write(data, CLIENTWRITE_BODY, prefix, plen);
1165
0
  }
1166
0
  if(!result && value) {
1167
0
    result = Curl_client_write(data, CLIENTWRITE_BODY, value, len);
1168
0
  }
1169
0
  if(!result && suffix) {
1170
0
    result = Curl_client_write(data, CLIENTWRITE_BODY, suffix, slen);
1171
0
  }
1172
0
  return result;
1173
0
}
1174
1175
/* RFC 2849: a string that is not a SAFE-STRING (leading ':' or '<', leading or
1176
   trailing space, or any non-printable byte such as CR/LF) cannot go into LDIF
1177
   as-is. DNs and values get base64-encoded instead; an attribute type has no
1178
   base64 form in LDIF and is rejected by the caller. */
1179
static bool oldap_str_needs_base64(const char *s, size_t len)
1180
0
{
1181
0
  size_t i;
1182
0
  if(!len)
1183
0
    return FALSE;
1184
0
  if((s[0] == ':') || (s[0] == '<') || ISBLANK(s[0]) || ISBLANK(s[len - 1]))
1185
0
    return TRUE;
1186
0
  for(i = 0; i < len; i++)
1187
0
    if(!ISPRINT(s[i]))
1188
0
      return TRUE;
1189
0
  return FALSE;
1190
0
}
1191
1192
static CURLcode oldap_recv(struct Curl_easy *data,
1193
                           char *buf, size_t len, size_t *pnread)
1194
0
{
1195
0
  struct connectdata *conn = data->conn;
1196
0
  struct ldapconninfo *li = Curl_conn_meta_get(conn, CURL_META_LDAP_CONN);
1197
0
  struct ldapreqinfo *lr = Curl_meta_get(data, CURL_META_LDAP_EASY);
1198
0
  int rc;
1199
0
  LDAPMessage *msg = NULL;
1200
0
  BerElement *ber = NULL;
1201
0
  struct berval bv, *bvals;
1202
0
  CURLcode result = CURLE_AGAIN;
1203
0
  int code;
1204
0
  char *info = NULL;
1205
1206
0
  (void)len;
1207
0
  (void)buf;
1208
0
  *pnread = 0;
1209
0
  if(!li || !lr)
1210
0
    return CURLE_FAILED_INIT;
1211
1212
0
  rc = oldap_result(li, lr->msgid, &msg);
1213
0
  if(rc < 0) {
1214
0
    failf(data, "LDAP local: search ldap_result %s", ldap_err2string(rc));
1215
0
    result = CURLE_RECV_ERROR;
1216
0
  }
1217
1218
  /* error or timed out */
1219
0
  if(!msg)
1220
0
    return result;
1221
1222
0
  result = CURLE_OK;
1223
1224
0
  switch(ldap_msgtype(msg)) {
1225
0
  case LDAP_RES_SEARCH_RESULT:
1226
0
    lr->msgid = 0;
1227
0
    rc = ldap_parse_result(li->ld, msg, &code, NULL, &info, NULL, NULL, 0);
1228
0
    if(rc) {
1229
0
      failf(data, "LDAP local: search ldap_parse_result %s",
1230
0
            ldap_err2string(rc));
1231
0
      result = CURLE_LDAP_SEARCH_FAILED;
1232
0
      break;
1233
0
    }
1234
1235
    /* store the latest code for later retrieval */
1236
0
    data->info.httpcode = code;
1237
1238
0
    switch(code) {
1239
0
    case LDAP_SIZELIMIT_EXCEEDED:
1240
0
      infof(data, "There are more than %d entries", lr->nument);
1241
0
      FALLTHROUGH();
1242
0
    case LDAP_SUCCESS:
1243
0
      data->req.size = data->req.bytecount;
1244
0
      break;
1245
0
    default:
1246
0
      failf(data, "LDAP remote: search failed %s %s", ldap_err2string(code),
1247
0
            info ? info : "");
1248
0
      result = CURLE_LDAP_SEARCH_FAILED;
1249
0
      break;
1250
0
    }
1251
0
    if(info)
1252
0
      ldap_memfree(info);
1253
0
    break;
1254
0
  case LDAP_RES_SEARCH_ENTRY:
1255
0
    lr->nument++;
1256
0
    rc = ldap_get_dn_ber(li->ld, msg, &ber, &bv);
1257
0
    if(rc < 0) {
1258
0
      result = CURLE_RECV_ERROR;
1259
0
      break;
1260
0
    }
1261
1262
0
    if(oldap_str_needs_base64(bv.bv_val, bv.bv_len)) {
1263
0
      char *dn_b64 = NULL;
1264
0
      size_t dn_b64_sz = 0;
1265
1266
      /* A DN with e.g. CR/LF would inject LDIF lines, so base64-encode it. */
1267
0
      result = curlx_base64_encode((uint8_t *)bv.bv_val, bv.bv_len,
1268
0
                                   &dn_b64, &dn_b64_sz);
1269
0
      if(!result)
1270
0
        result = client_write(data, STRCONST("DN:: "), dn_b64, dn_b64_sz,
1271
0
                              STRCONST("\n"));
1272
0
      curlx_free(dn_b64);
1273
0
    }
1274
0
    else
1275
0
      result = client_write(data, STRCONST("DN: "), bv.bv_val, bv.bv_len,
1276
0
                            STRCONST("\n"));
1277
0
    if(result)
1278
0
      break;
1279
1280
0
    for(rc = ldap_get_attribute_ber(li->ld, msg, ber, &bv, &bvals);
1281
0
        rc == LDAP_SUCCESS;
1282
0
        rc = ldap_get_attribute_ber(li->ld, msg, ber, &bv, &bvals)) {
1283
0
      int i;
1284
0
      bool binary;
1285
1286
0
      if(!bv.bv_val)
1287
0
        break;
1288
1289
      /* An attribute type has no base64 form in LDIF, so a type carrying
1290
         control bytes (CR/LF etc.) would let a hostile server inject lines.
1291
         A conformant type name never contains them, so reject it. */
1292
0
      if(oldap_str_needs_base64(bv.bv_val, bv.bv_len)) {
1293
0
        failf(data, "LDAP local: attribute type contains illegal bytes");
1294
0
        if(bvals)
1295
0
          ber_memfree(bvals);
1296
0
        result = CURLE_WEIRD_SERVER_REPLY;
1297
0
        break;
1298
0
      }
1299
1300
0
      if(!bvals) {
1301
0
        result = client_write(data, STRCONST("\t"), bv.bv_val, bv.bv_len,
1302
0
                              STRCONST(":\n"));
1303
0
        if(result)
1304
0
          break;
1305
0
        continue;
1306
0
      }
1307
1308
0
      binary = bv.bv_len > 7 &&
1309
0
        curl_strnequal(bv.bv_val + bv.bv_len - 7, ";binary", 7);
1310
1311
0
      for(i = 0; bvals[i].bv_val; i++) {
1312
0
        bool binval = FALSE;
1313
1314
0
        result = client_write(data, STRCONST("\t"), bv.bv_val, bv.bv_len,
1315
0
                              STRCONST(":"));
1316
0
        if(result)
1317
0
          break;
1318
1319
0
        if(!binary)
1320
0
          binval = oldap_str_needs_base64(bvals[i].bv_val, bvals[i].bv_len);
1321
0
        if(binary || binval) {
1322
0
          char *val_b64 = NULL;
1323
0
          size_t val_b64_sz = 0;
1324
1325
          /* Binary value, encode to base64. */
1326
0
          if(bvals[i].bv_len)
1327
0
            result = curlx_base64_encode((uint8_t *)bvals[i].bv_val,
1328
0
                                         bvals[i].bv_len,
1329
0
                                         &val_b64, &val_b64_sz);
1330
0
          if(!result)
1331
0
            result = client_write(data, STRCONST(": "), val_b64, val_b64_sz,
1332
0
                                  STRCONST("\n"));
1333
0
          curlx_free(val_b64);
1334
0
        }
1335
0
        else
1336
0
          result = client_write(data, STRCONST(" "),
1337
0
                                bvals[i].bv_val, bvals[i].bv_len,
1338
0
                                STRCONST("\n"));
1339
0
        if(result)
1340
0
          break;
1341
0
      }
1342
1343
0
      ber_memfree(bvals);
1344
0
      bvals = NULL;
1345
0
      if(!result)
1346
0
        result = client_write(data, STRCONST("\n"), NULL, 0, NULL, 0);
1347
0
      if(result)
1348
0
        break;
1349
0
    }
1350
1351
0
    if(!result)
1352
0
      result = client_write(data, STRCONST("\n"), NULL, 0, NULL, 0);
1353
0
    if(!result)
1354
0
      result = CURLE_AGAIN;
1355
0
    break;
1356
0
  }
1357
1358
0
  ber_free(ber, 0);
1359
0
  ldap_msgfree(msg);
1360
0
  return result;
1361
0
}
1362
1363
void Curl_ldap_version(char *buf, size_t bufsz)
1364
0
{
1365
0
  LDAPAPIInfo api;
1366
0
  api.ldapai_info_version = LDAP_API_INFO_VERSION;
1367
1368
0
  if(ldap_get_option(NULL, LDAP_OPT_API_INFO, &api) == LDAP_OPT_SUCCESS) {
1369
0
    unsigned int patch = (unsigned int)(api.ldapai_vendor_version % 100);
1370
0
    unsigned int major = (unsigned int)(api.ldapai_vendor_version / 10000);
1371
0
    unsigned int minor =
1372
0
      (((unsigned int)api.ldapai_vendor_version - (major * 10000))
1373
0
       - patch) / 100;
1374
0
    curl_msnprintf(buf, bufsz, "%s/%u.%u.%u",
1375
0
                   api.ldapai_vendor_name, major, minor, patch);
1376
0
    ldap_memfree(api.ldapai_vendor_name);
1377
0
    ber_memvfree((void **)api.ldapai_extensions);
1378
0
  }
1379
0
  else
1380
0
    curl_msnprintf(buf, bufsz, "OpenLDAP");
1381
0
}
1382
1383
/*
1384
 * LDAP protocol handler.
1385
 */
1386
const struct Curl_protocol Curl_protocol_ldap = {
1387
  oldap_setup_connection,               /* setup_connection */
1388
  ZERO_NULL,                            /* setup_filters */
1389
  oldap_do,                             /* do_it */
1390
  oldap_done,                           /* done */
1391
  ZERO_NULL,                            /* do_more */
1392
  oldap_connect,                        /* connect_it */
1393
  oldap_connecting,                     /* connecting */
1394
  ZERO_NULL,                            /* doing */
1395
  ZERO_NULL,                            /* proto_pollset */
1396
  ZERO_NULL,                            /* doing_pollset */
1397
  ZERO_NULL,                            /* domore_pollset */
1398
  ZERO_NULL,                            /* perform_pollset */
1399
  oldap_disconnect,                     /* disconnect */
1400
  ZERO_NULL,                            /* write_resp */
1401
  ZERO_NULL,                            /* write_resp_hd */
1402
  ZERO_NULL,                            /* connection_is_dead */
1403
  ZERO_NULL,                            /* attach connection */
1404
  ZERO_NULL,                            /* follow */
1405
};
1406
1407
#endif /* !CURL_DISABLE_LDAP && USE_OPENLDAP */
1408
1409
/* The LDAP scheme structs are in ldap.c */