2 Unix SMB/CIFS mplementation.
3 LDAP protocol helper functions for SAMBA
5 Copyright (C) Andrew Tridgell 2004
6 Copyright (C) Volker Lendecke 2004
7 Copyright (C) Stefan Metzmacher 2004
8 Copyright (C) Simo Sorce 2004
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 2 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program; if not, write to the Free Software
22 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #include "dlinklist.h"
29 #include "lib/events/events.h"
30 #include "lib/socket/socket.h"
31 #include "lib/tls/tls.h"
32 #include "libcli/ldap/ldap.h"
33 #include "libcli/ldap/ldap_client.h"
34 #include "libcli/composite/composite.h"
38 create a new ldap_connection stucture. The event context is optional
40 struct ldap_connection *ldap_new_connection(TALLOC_CTX *mem_ctx,
41 struct event_context *ev)
43 struct ldap_connection *conn;
45 conn = talloc_zero(mem_ctx, struct ldap_connection);
51 ev = event_context_init(conn);
58 conn->next_messageid = 1;
59 conn->event.event_ctx = ev;
61 /* set a reasonable request timeout */
69 the connection is dead
71 static void ldap_connection_dead(struct ldap_connection *conn)
73 struct ldap_request *req;
75 while (conn->pending) {
77 DLIST_REMOVE(req->conn->pending, req);
78 req->state = LDAP_REQUEST_DONE;
79 req->status = NT_STATUS_UNEXPECTED_NETWORK_ERROR;
85 while (conn->send_queue) {
86 req = conn->send_queue;
87 DLIST_REMOVE(req->conn->send_queue, req);
88 req->state = LDAP_REQUEST_DONE;
89 req->status = NT_STATUS_UNEXPECTED_NETWORK_ERROR;
95 talloc_free(conn->tls);
101 match up with a pending message, adding to the replies list
103 static void ldap_match_message(struct ldap_connection *conn, struct ldap_message *msg)
105 struct ldap_request *req;
107 for (req=conn->pending; req; req=req->next) {
108 if (req->messageid == msg->messageid) break;
110 /* match a zero message id to the last request sent.
111 It seems that servers send 0 if unable to parse */
112 if (req == NULL && msg->messageid == 0) {
116 DEBUG(0,("ldap: no matching message id for %u\n",
122 /* add to the list of replies received */
123 talloc_steal(req, msg);
124 req->replies = talloc_realloc(req, req->replies,
125 struct ldap_message *, req->num_replies+1);
126 if (req->replies == NULL) {
127 req->status = NT_STATUS_NO_MEMORY;
128 req->state = LDAP_REQUEST_DONE;
129 DLIST_REMOVE(conn->pending, req);
136 req->replies[req->num_replies] = talloc_steal(req->replies, msg);
139 if (msg->type != LDAP_TAG_SearchResultEntry &&
140 msg->type != LDAP_TAG_SearchResultReference) {
141 /* currently only search results expect multiple
143 req->state = LDAP_REQUEST_DONE;
144 DLIST_REMOVE(conn->pending, req);
153 try and decode/process plain data
155 static void ldap_try_decode_plain(struct ldap_connection *conn)
157 struct asn1_data asn1;
159 if (!asn1_load(&asn1, conn->partial)) {
160 ldap_connection_dead(conn);
164 /* try and decode - this will fail if we don't have a full packet yet */
165 while (asn1.ofs < asn1.length) {
166 struct ldap_message *msg = talloc(conn, struct ldap_message);
167 off_t saved_ofs = asn1.ofs;
170 ldap_connection_dead(conn);
174 if (ldap_decode(&asn1, msg)) {
175 ldap_match_message(conn, msg);
177 asn1.ofs = saved_ofs;
183 /* keep any remaining data in conn->partial */
184 data_blob_free(&conn->partial);
185 if (asn1.ofs != asn1.length) {
186 conn->partial = data_blob_talloc(conn,
187 asn1.data + asn1.ofs,
188 asn1.length - asn1.ofs);
194 try and decode/process wrapped data
196 static void ldap_try_decode_wrapped(struct ldap_connection *conn)
200 /* keep decoding while we have a full wrapped packet */
201 while (conn->partial.length >= 4 &&
202 (len=RIVAL(conn->partial.data, 0)) <= conn->partial.length-4) {
203 DATA_BLOB wrapped, unwrapped;
204 struct asn1_data asn1;
205 struct ldap_message *msg = talloc(conn, struct ldap_message);
209 ldap_connection_dead(conn);
213 wrapped.data = conn->partial.data+4;
214 wrapped.length = len;
216 status = gensec_unwrap(conn->gensec, msg, &wrapped, &unwrapped);
217 if (!NT_STATUS_IS_OK(status)) {
218 ldap_connection_dead(conn);
222 if (!asn1_load(&asn1, unwrapped)) {
223 ldap_connection_dead(conn);
227 while (ldap_decode(&asn1, msg)) {
228 ldap_match_message(conn, msg);
229 msg = talloc(conn, struct ldap_message);
235 if (conn->partial.length == len + 4) {
236 data_blob_free(&conn->partial);
238 memmove(conn->partial.data, conn->partial.data+len+4,
239 conn->partial.length - (len+4));
240 conn->partial.length -= len + 4;
247 handle ldap recv events
249 static void ldap_recv_handler(struct ldap_connection *conn)
252 size_t npending=0, nread;
254 /* work out how much data is pending */
255 status = tls_socket_pending(conn->tls, &npending);
256 if (!NT_STATUS_IS_OK(status) || npending == 0) {
257 ldap_connection_dead(conn);
261 conn->partial.data = talloc_realloc_size(conn, conn->partial.data,
262 conn->partial.length + npending);
263 if (conn->partial.data == NULL) {
264 ldap_connection_dead(conn);
268 /* receive the pending data */
269 status = tls_socket_recv(conn->tls, conn->partial.data + conn->partial.length,
271 if (NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES)) {
274 if (!NT_STATUS_IS_OK(status)) {
275 ldap_connection_dead(conn);
278 conn->partial.length += nread;
280 /* see if we can decode what we have */
281 if (conn->enable_wrap) {
282 ldap_try_decode_wrapped(conn);
284 ldap_try_decode_plain(conn);
290 handle ldap send events
292 static void ldap_send_handler(struct ldap_connection *conn)
294 while (conn->send_queue) {
295 struct ldap_request *req = conn->send_queue;
299 status = tls_socket_send(conn->tls, &req->data, &nsent);
300 if (NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES)) {
303 if (!NT_STATUS_IS_OK(status)) {
304 ldap_connection_dead(conn);
308 req->data.data += nsent;
309 req->data.length -= nsent;
310 if (req->data.length == 0) {
311 req->state = LDAP_REQUEST_PENDING;
312 DLIST_REMOVE(conn->send_queue, req);
314 /* some types of requests don't expect a reply */
315 if (req->type == LDAP_TAG_AbandonRequest ||
316 req->type == LDAP_TAG_UnbindRequest) {
317 req->status = NT_STATUS_OK;
318 req->state = LDAP_REQUEST_DONE;
323 DLIST_ADD(conn->pending, req);
327 if (conn->send_queue == NULL) {
328 EVENT_FD_NOT_WRITEABLE(conn->event.fde);
334 handle ldap socket events
336 static void ldap_io_handler(struct event_context *ev, struct fd_event *fde,
337 uint16_t flags, void *private)
339 struct ldap_connection *conn = talloc_get_type(private, struct ldap_connection);
340 if (flags & EVENT_FD_WRITE) {
341 ldap_send_handler(conn);
342 if (conn->tls == NULL) return;
344 if (flags & EVENT_FD_READ) {
345 ldap_recv_handler(conn);
352 static NTSTATUS ldap_parse_basic_url(TALLOC_CTX *mem_ctx, const char *url,
353 char **host, uint16_t *port, BOOL *ldaps)
361 /* skip leading "URL:" (if any) */
362 if (strncasecmp(p, "URL:", 4) == 0) {
367 SMB_ASSERT(sizeof(protocol)>10 && sizeof(tmp_host)>254);
369 ret = sscanf(p, "%10[^:]://%254[^:/]:%d", protocol, tmp_host, &tmp_port);
371 return NT_STATUS_INVALID_PARAMETER;
374 if (strequal(protocol, "ldap")) {
377 } else if (strequal(protocol, "ldaps")) {
381 DEBUG(0, ("unrecognised ldap protocol (%s)!\n", protocol));
382 return NT_STATUS_PROTOCOL_UNREACHABLE;
388 *host = talloc_strdup(mem_ctx, tmp_host);
389 NT_STATUS_HAVE_NO_MEMORY(*host);
395 connect to a ldap server
398 struct ldap_connect_state {
399 struct composite_context *ctx;
400 struct ldap_connection *conn;
403 static void ldap_connect_recv_conn(struct composite_context *ctx);
405 struct composite_context *ldap_connect_send(struct ldap_connection *conn,
408 struct composite_context *result, *ctx;
409 struct ldap_connect_state *state;
411 result = talloc_zero(NULL, struct composite_context);
412 if (result == NULL) goto failed;
413 result->state = COMPOSITE_STATE_IN_PROGRESS;
414 result->async.fn = NULL;
415 result->event_ctx = conn->event.event_ctx;
417 state = talloc(result, struct ldap_connect_state);
418 if (state == NULL) goto failed;
420 result->private_data = state;
424 state->ctx->status = ldap_parse_basic_url(conn, url, &conn->host,
425 &conn->port, &conn->ldaps);
426 if (!NT_STATUS_IS_OK(state->ctx->status)) {
427 composite_trigger_error(state->ctx);
431 ctx = socket_connect_multi_send(state, conn->host, 1, &conn->port,
432 conn->event.event_ctx);
433 if (ctx == NULL) goto failed;
435 ctx->async.fn = ldap_connect_recv_conn;
436 ctx->async.private_data = state;
444 static void ldap_connect_recv_conn(struct composite_context *ctx)
446 struct ldap_connect_state *state =
447 talloc_get_type(ctx->async.private_data,
448 struct ldap_connect_state);
449 struct ldap_connection *conn = state->conn;
452 state->ctx->status = socket_connect_multi_recv(ctx, state, &conn->sock,
454 if (!composite_is_ok(state->ctx)) return;
456 /* setup a handler for events on this socket */
457 conn->event.fde = event_add_fd(conn->event.event_ctx, conn->sock,
458 socket_get_fd(conn->sock),
459 EVENT_FD_READ, ldap_io_handler, conn);
460 if (conn->event.fde == NULL) {
461 composite_error(state->ctx, NT_STATUS_INTERNAL_ERROR);
465 conn->tls = tls_init_client(conn->sock, conn->event.fde, conn->ldaps);
466 if (conn->tls == NULL) {
467 talloc_free(conn->sock);
470 talloc_steal(conn, conn->tls);
471 talloc_steal(conn->tls, conn->sock);
473 composite_done(state->ctx);
478 NTSTATUS ldap_connect_recv(struct composite_context *ctx)
480 NTSTATUS status = composite_wait(ctx);
485 NTSTATUS ldap_connect(struct ldap_connection *conn, const char *url)
487 struct composite_context *ctx = ldap_connect_send(conn, url);
488 return ldap_connect_recv(ctx);
491 /* destroy an open ldap request */
492 static int ldap_request_destructor(void *ptr)
494 struct ldap_request *req = talloc_get_type(ptr, struct ldap_request);
495 if (req->state == LDAP_REQUEST_SEND) {
496 DLIST_REMOVE(req->conn->send_queue, req);
498 if (req->state == LDAP_REQUEST_PENDING) {
499 DLIST_REMOVE(req->conn->pending, req);
505 called on timeout of a ldap request
507 static void ldap_request_timeout(struct event_context *ev, struct timed_event *te,
508 struct timeval t, void *private)
510 struct ldap_request *req = talloc_get_type(private, struct ldap_request);
511 req->status = NT_STATUS_IO_TIMEOUT;
512 if (req->state == LDAP_REQUEST_SEND) {
513 DLIST_REMOVE(req->conn->send_queue, req);
515 if (req->state == LDAP_REQUEST_PENDING) {
516 DLIST_REMOVE(req->conn->pending, req);
518 req->state = LDAP_REQUEST_DONE;
525 send a ldap message - async interface
527 struct ldap_request *ldap_request_send(struct ldap_connection *conn,
528 struct ldap_message *msg)
530 struct ldap_request *req;
532 if (conn->tls == NULL) {
536 req = talloc_zero(conn, struct ldap_request);
537 if (req == NULL) goto failed;
539 req->state = LDAP_REQUEST_SEND;
541 req->messageid = conn->next_messageid++;
542 if (conn->next_messageid == 0) {
543 conn->next_messageid = 1;
545 req->type = msg->type;
546 if (req->messageid == -1) {
550 talloc_set_destructor(req, ldap_request_destructor);
552 msg->messageid = req->messageid;
554 if (!ldap_encode(msg, &req->data, req)) {
558 /* possibly encrypt/sign the request */
559 if (conn->enable_wrap) {
563 status = gensec_wrap(conn->gensec, req, &req->data, &wrapped);
564 if (!NT_STATUS_IS_OK(status)) {
567 data_blob_free(&req->data);
568 req->data = data_blob_talloc(req, NULL, wrapped.length + 4);
569 if (req->data.data == NULL) {
572 RSIVAL(req->data.data, 0, wrapped.length);
573 memcpy(req->data.data+4, wrapped.data, wrapped.length);
574 data_blob_free(&wrapped);
578 if (conn->send_queue == NULL) {
579 EVENT_FD_WRITEABLE(conn->event.fde);
581 DLIST_ADD_END(conn->send_queue, req, struct ldap_request *);
583 /* put a timeout on the request */
584 event_add_timed(conn->event.event_ctx, req,
585 timeval_current_ofs(conn->timeout, 0),
586 ldap_request_timeout, req);
597 wait for a request to complete
598 note that this does not destroy the request
600 NTSTATUS ldap_request_wait(struct ldap_request *req)
602 while (req->state != LDAP_REQUEST_DONE) {
603 if (event_loop_once(req->conn->event.event_ctx) != 0) {
604 req->status = NT_STATUS_UNEXPECTED_NETWORK_ERROR;
613 a mapping of ldap response code to strings
615 static const struct {
616 enum ldap_result_code code;
618 } ldap_code_map[] = {
619 #define _LDAP_MAP_CODE(c) { c, #c }
620 _LDAP_MAP_CODE(LDAP_SUCCESS),
621 _LDAP_MAP_CODE(LDAP_OPERATIONS_ERROR),
622 _LDAP_MAP_CODE(LDAP_PROTOCOL_ERROR),
623 _LDAP_MAP_CODE(LDAP_TIME_LIMIT_EXCEEDED),
624 _LDAP_MAP_CODE(LDAP_SIZE_LIMIT_EXCEEDED),
625 _LDAP_MAP_CODE(LDAP_COMPARE_FALSE),
626 _LDAP_MAP_CODE(LDAP_COMPARE_TRUE),
627 _LDAP_MAP_CODE(LDAP_AUTH_METHOD_NOT_SUPPORTED),
628 _LDAP_MAP_CODE(LDAP_STRONG_AUTH_REQUIRED),
629 _LDAP_MAP_CODE(LDAP_REFERRAL),
630 _LDAP_MAP_CODE(LDAP_ADMIN_LIMIT_EXCEEDED),
631 _LDAP_MAP_CODE(LDAP_UNAVAILABLE_CRITICAL_EXTENSION),
632 _LDAP_MAP_CODE(LDAP_CONFIDENTIALITY_REQUIRED),
633 _LDAP_MAP_CODE(LDAP_SASL_BIND_IN_PROGRESS),
634 _LDAP_MAP_CODE(LDAP_NO_SUCH_ATTRIBUTE),
635 _LDAP_MAP_CODE(LDAP_UNDEFINED_ATTRIBUTE_TYPE),
636 _LDAP_MAP_CODE(LDAP_INAPPROPRIATE_MATCHING),
637 _LDAP_MAP_CODE(LDAP_CONSTRAINT_VIOLATION),
638 _LDAP_MAP_CODE(LDAP_ATTRIBUTE_OR_VALUE_EXISTS),
639 _LDAP_MAP_CODE(LDAP_INVALID_ATTRIBUTE_SYNTAX),
640 _LDAP_MAP_CODE(LDAP_NO_SUCH_OBJECT),
641 _LDAP_MAP_CODE(LDAP_ALIAS_PROBLEM),
642 _LDAP_MAP_CODE(LDAP_INVALID_DN_SYNTAX),
643 _LDAP_MAP_CODE(LDAP_ALIAS_DEREFERENCING_PROBLEM),
644 _LDAP_MAP_CODE(LDAP_INAPPROPRIATE_AUTHENTICATION),
645 _LDAP_MAP_CODE(LDAP_INVALID_CREDENTIALS),
646 _LDAP_MAP_CODE(LDAP_INSUFFICIENT_ACCESS_RIGHTs),
647 _LDAP_MAP_CODE(LDAP_BUSY),
648 _LDAP_MAP_CODE(LDAP_UNAVAILABLE),
649 _LDAP_MAP_CODE(LDAP_UNWILLING_TO_PERFORM),
650 _LDAP_MAP_CODE(LDAP_LOOP_DETECT),
651 _LDAP_MAP_CODE(LDAP_NAMING_VIOLATION),
652 _LDAP_MAP_CODE(LDAP_OBJECT_CLASS_VIOLATION),
653 _LDAP_MAP_CODE(LDAP_NOT_ALLOWED_ON_NON_LEAF),
654 _LDAP_MAP_CODE(LDAP_NOT_ALLOWED_ON_RDN),
655 _LDAP_MAP_CODE(LDAP_ENTRY_ALREADY_EXISTS),
656 _LDAP_MAP_CODE(LDAP_OBJECT_CLASS_MODS_PROHIBITED),
657 _LDAP_MAP_CODE(LDAP_AFFECTS_MULTIPLE_DSAS),
658 _LDAP_MAP_CODE(LDAP_OTHER)
662 used to setup the status code from a ldap response
664 NTSTATUS ldap_check_response(struct ldap_connection *conn, struct ldap_Result *r)
667 const char *codename = "unknown";
669 if (r->resultcode == LDAP_SUCCESS) {
673 if (conn->last_error) {
674 talloc_free(conn->last_error);
677 for (i=0;i<ARRAY_SIZE(ldap_code_map);i++) {
678 if (r->resultcode == ldap_code_map[i].code) {
679 codename = ldap_code_map[i].str;
684 conn->last_error = talloc_asprintf(conn, "LDAP error %u %s - %s <%s> <%s>",
687 r->dn?r->dn:"(NULL)",
688 r->errormessage?r->errormessage:"",
689 r->referral?r->referral:"");
691 return NT_STATUS_LDAP(r->resultcode);
695 return error string representing the last error
697 const char *ldap_errstr(struct ldap_connection *conn, NTSTATUS status)
699 if (NT_STATUS_IS_LDAP(status) && conn->last_error != NULL) {
700 return conn->last_error;
702 return nt_errstr(status);
707 return the Nth result message, waiting if necessary
709 NTSTATUS ldap_result_n(struct ldap_request *req, int n, struct ldap_message **msg)
713 NT_STATUS_HAVE_NO_MEMORY(req);
715 while (req->state != LDAP_REQUEST_DONE && n >= req->num_replies) {
716 if (event_loop_once(req->conn->event.event_ctx) != 0) {
717 return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
721 if (n < req->num_replies) {
722 *msg = req->replies[n];
726 if (!NT_STATUS_IS_OK(req->status)) {
730 return NT_STATUS_NO_MORE_ENTRIES;
735 return a single result message, checking if it is of the expected LDAP type
737 NTSTATUS ldap_result_one(struct ldap_request *req, struct ldap_message **msg, int type)
740 status = ldap_result_n(req, 0, msg);
741 if (!NT_STATUS_IS_OK(status)) {
744 if ((*msg)->type != type) {
746 return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
752 a simple ldap transaction, for single result requests that only need a status code
753 this relies on single valued requests having the response type == request type + 1
755 NTSTATUS ldap_transaction(struct ldap_connection *conn, struct ldap_message *msg)
757 struct ldap_request *req = ldap_request_send(conn, msg);
758 struct ldap_message *res;
760 status = ldap_result_n(req, 0, &res);
761 if (!NT_STATUS_IS_OK(status)) {
765 if (res->type != msg->type + 1) {
767 return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);
769 status = ldap_check_response(conn, &res->r.GeneralResult);