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 3 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, see <http://www.gnu.org/licenses/>.
26 #include "libcli/util/asn_1.h"
27 #include "lib/util/dlinklist.h"
28 #include "lib/events/events.h"
29 #include "lib/socket/socket.h"
30 #include "libcli/ldap/ldap.h"
31 #include "libcli/ldap/ldap_client.h"
32 #include "libcli/composite/composite.h"
33 #include "lib/stream/packet.h"
34 #include "lib/tls/tls.h"
35 #include "auth/gensec/gensec.h"
36 #include "system/time.h"
40 create a new ldap_connection stucture. The event context is optional
42 struct ldap_connection *ldap4_new_connection(TALLOC_CTX *mem_ctx,
43 struct event_context *ev)
45 struct ldap_connection *conn;
47 conn = talloc_zero(mem_ctx, struct ldap_connection);
53 ev = event_context_init(conn);
60 conn->next_messageid = 1;
61 conn->event.event_ctx = ev;
63 /* set a reasonable request timeout */
66 /* explicitly avoid reconnections by default */
67 conn->reconnect.max_retries = 0;
73 the connection is dead
75 static void ldap_connection_dead(struct ldap_connection *conn)
77 struct ldap_request *req;
79 /* return an error for any pending request ... */
80 while (conn->pending) {
82 DLIST_REMOVE(req->conn->pending, req);
83 req->state = LDAP_REQUEST_DONE;
84 req->status = NT_STATUS_UNEXPECTED_NETWORK_ERROR;
90 talloc_free(conn->sock); /* this will also free event.fde */
91 talloc_free(conn->packet);
93 conn->event.fde = NULL;
97 static void ldap_reconnect(struct ldap_connection *conn);
102 static void ldap_error_handler(void *private_data, NTSTATUS status)
104 struct ldap_connection *conn = talloc_get_type(private_data,
105 struct ldap_connection);
106 ldap_connection_dead(conn);
108 /* but try to reconnect so that the ldb client can go on */
109 ldap_reconnect(conn);
114 match up with a pending message, adding to the replies list
116 static void ldap_match_message(struct ldap_connection *conn, struct ldap_message *msg)
118 struct ldap_request *req;
121 for (req=conn->pending; req; req=req->next) {
122 if (req->messageid == msg->messageid) break;
124 /* match a zero message id to the last request sent.
125 It seems that servers send 0 if unable to parse */
126 if (req == NULL && msg->messageid == 0) {
130 DEBUG(0,("ldap: no matching message id for %u\n",
136 /* Check for undecoded critical extensions */
137 for (i=0; msg->controls && msg->controls[i]; i++) {
138 if (!msg->controls_decoded[i] &&
139 msg->controls[i]->critical) {
140 req->status = NT_STATUS_LDAP(LDAP_UNAVAILABLE_CRITICAL_EXTENSION);
141 req->state = LDAP_REQUEST_DONE;
142 DLIST_REMOVE(conn->pending, req);
150 /* add to the list of replies received */
151 talloc_steal(req, msg);
152 req->replies = talloc_realloc(req, req->replies,
153 struct ldap_message *, req->num_replies+1);
154 if (req->replies == NULL) {
155 req->status = NT_STATUS_NO_MEMORY;
156 req->state = LDAP_REQUEST_DONE;
157 DLIST_REMOVE(conn->pending, req);
164 req->replies[req->num_replies] = talloc_steal(req->replies, msg);
167 if (msg->type != LDAP_TAG_SearchResultEntry &&
168 msg->type != LDAP_TAG_SearchResultReference) {
169 /* currently only search results expect multiple
171 req->state = LDAP_REQUEST_DONE;
172 DLIST_REMOVE(conn->pending, req);
182 decode/process LDAP data
184 static NTSTATUS ldap_recv_handler(void *private_data, DATA_BLOB blob)
187 struct ldap_connection *conn = talloc_get_type(private_data,
188 struct ldap_connection);
189 struct ldap_message *msg = talloc(conn, struct ldap_message);
190 struct asn1_data *asn1 = asn1_init(conn);
192 if (asn1 == NULL || msg == NULL) {
193 return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);
196 if (!asn1_load(asn1, blob)) {
199 return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);
202 status = ldap_decode(asn1, msg);
203 if (!NT_STATUS_IS_OK(status)) {
208 ldap_match_message(conn, msg);
210 data_blob_free(&blob);
215 /* Handle read events, from the GENSEC socket callback, or real events */
216 void ldap_read_io_handler(void *private_data, uint16_t flags)
218 struct ldap_connection *conn = talloc_get_type(private_data,
219 struct ldap_connection);
220 packet_recv(conn->packet);
224 handle ldap socket events
226 static void ldap_io_handler(struct event_context *ev, struct fd_event *fde,
227 uint16_t flags, void *private_data)
229 struct ldap_connection *conn = talloc_get_type(private_data,
230 struct ldap_connection);
231 if (flags & EVENT_FD_WRITE) {
232 packet_queue_run(conn->packet);
233 if (!tls_enabled(conn->sock)) return;
235 if (flags & EVENT_FD_READ) {
236 ldap_read_io_handler(private_data, flags);
243 static NTSTATUS ldap_parse_basic_url(TALLOC_CTX *mem_ctx, const char *url,
244 char **host, uint16_t *port, bool *ldaps)
252 SMB_ASSERT(sizeof(protocol)>10 && sizeof(tmp_host)>254);
254 ret = sscanf(url, "%10[^:]://%254[^:/]:%d", protocol, tmp_host, &tmp_port);
256 return NT_STATUS_INVALID_PARAMETER;
259 if (strequal(protocol, "ldap")) {
262 } else if (strequal(protocol, "ldaps")) {
266 DEBUG(0, ("unrecognised ldap protocol (%s)!\n", protocol));
267 return NT_STATUS_PROTOCOL_UNREACHABLE;
273 *host = talloc_strdup(mem_ctx, tmp_host);
274 NT_STATUS_HAVE_NO_MEMORY(*host);
280 connect to a ldap server
283 struct ldap_connect_state {
284 struct composite_context *ctx;
285 struct ldap_connection *conn;
288 static void ldap_connect_recv_unix_conn(struct composite_context *ctx);
289 static void ldap_connect_recv_tcp_conn(struct composite_context *ctx);
291 struct composite_context *ldap_connect_send(struct ldap_connection *conn,
294 struct composite_context *result, *ctx;
295 struct ldap_connect_state *state;
299 result = talloc_zero(NULL, struct composite_context);
300 if (result == NULL) goto failed;
301 result->state = COMPOSITE_STATE_IN_PROGRESS;
302 result->async.fn = NULL;
303 result->event_ctx = conn->event.event_ctx;
305 state = talloc(result, struct ldap_connect_state);
306 if (state == NULL) goto failed;
308 result->private_data = state;
312 if (conn->reconnect.url == NULL) {
313 conn->reconnect.url = talloc_strdup(conn, url);
314 if (conn->reconnect.url == NULL) goto failed;
318 SMB_ASSERT(sizeof(protocol)>10);
320 ret = sscanf(url, "%10[^:]://", protocol);
325 if (strequal(protocol, "ldapi")) {
326 struct socket_address *unix_addr;
329 NTSTATUS status = socket_create("unix", SOCKET_TYPE_STREAM, &conn->sock, 0);
330 if (!NT_STATUS_IS_OK(status)) {
333 talloc_steal(conn, conn->sock);
334 SMB_ASSERT(sizeof(protocol)>10);
335 SMB_ASSERT(sizeof(path)>1024);
337 /* The %c specifier doesn't null terminate :-( */
339 ret = sscanf(url, "%10[^:]://%1025c", protocol, path);
341 composite_error(state->ctx, NT_STATUS_INVALID_PARAMETER);
345 rfc1738_unescape(path);
347 unix_addr = socket_address_from_strings(conn, conn->sock->backend_name,
353 ctx = socket_connect_send(conn->sock, NULL, unix_addr,
354 0, conn->event.event_ctx);
355 ctx->async.fn = ldap_connect_recv_unix_conn;
356 ctx->async.private_data = state;
359 NTSTATUS status = ldap_parse_basic_url(conn, url, &conn->host,
360 &conn->port, &conn->ldaps);
361 if (!NT_STATUS_IS_OK(state->ctx->status)) {
362 composite_error(state->ctx, status);
366 ctx = socket_connect_multi_send(state, conn->host, 1, &conn->port,
367 conn->event.event_ctx);
368 if (ctx == NULL) goto failed;
370 ctx->async.fn = ldap_connect_recv_tcp_conn;
371 ctx->async.private_data = state;
379 static void ldap_connect_got_sock(struct composite_context *ctx, struct ldap_connection *conn)
381 /* setup a handler for events on this socket */
382 conn->event.fde = event_add_fd(conn->event.event_ctx, conn->sock,
383 socket_get_fd(conn->sock),
384 EVENT_FD_READ | EVENT_FD_AUTOCLOSE, ldap_io_handler, conn);
385 if (conn->event.fde == NULL) {
386 composite_error(ctx, NT_STATUS_INTERNAL_ERROR);
390 socket_set_flags(conn->sock, SOCKET_FLAG_NOCLOSE);
392 talloc_steal(conn, conn->sock);
394 struct socket_context *tls_socket = tls_init_client(conn->sock, conn->event.fde);
395 if (tls_socket == NULL) {
396 talloc_free(conn->sock);
399 talloc_unlink(conn, conn->sock);
400 conn->sock = tls_socket;
401 talloc_steal(conn, conn->sock);
404 conn->packet = packet_init(conn);
405 if (conn->packet == NULL) {
406 talloc_free(conn->sock);
410 packet_set_private(conn->packet, conn);
411 packet_set_socket(conn->packet, conn->sock);
412 packet_set_callback(conn->packet, ldap_recv_handler);
413 packet_set_full_request(conn->packet, ldap_full_packet);
414 packet_set_error_handler(conn->packet, ldap_error_handler);
415 packet_set_event_context(conn->packet, conn->event.event_ctx);
416 packet_set_fde(conn->packet, conn->event.fde);
417 packet_set_serialise(conn->packet);
422 static void ldap_connect_recv_tcp_conn(struct composite_context *ctx)
424 struct ldap_connect_state *state =
425 talloc_get_type(ctx->async.private_data,
426 struct ldap_connect_state);
427 struct ldap_connection *conn = state->conn;
429 NTSTATUS status = socket_connect_multi_recv(ctx, state, &conn->sock,
431 if (!NT_STATUS_IS_OK(status)) {
432 composite_error(state->ctx, status);
436 ldap_connect_got_sock(state->ctx, conn);
439 static void ldap_connect_recv_unix_conn(struct composite_context *ctx)
441 struct ldap_connect_state *state =
442 talloc_get_type(ctx->async.private_data,
443 struct ldap_connect_state);
444 struct ldap_connection *conn = state->conn;
446 NTSTATUS status = socket_connect_recv(ctx);
448 if (!NT_STATUS_IS_OK(state->ctx->status)) {
449 composite_error(state->ctx, status);
453 ldap_connect_got_sock(state->ctx, conn);
456 _PUBLIC_ NTSTATUS ldap_connect_recv(struct composite_context *ctx)
458 NTSTATUS status = composite_wait(ctx);
463 NTSTATUS ldap_connect(struct ldap_connection *conn, const char *url)
465 struct composite_context *ctx = ldap_connect_send(conn, url);
466 return ldap_connect_recv(ctx);
469 /* set reconnect parameters */
471 void ldap_set_reconn_params(struct ldap_connection *conn, int max_retries)
474 conn->reconnect.max_retries = max_retries;
475 conn->reconnect.retries = 0;
476 conn->reconnect.previous = time(NULL);
480 /* Actually this function is NOT ASYNC safe, FIXME? */
481 static void ldap_reconnect(struct ldap_connection *conn)
484 time_t now = time(NULL);
486 /* do we have set up reconnect ? */
487 if (conn->reconnect.max_retries == 0) return;
489 /* is the retry time expired ? */
490 if (now > conn->reconnect.previous + 30) {
491 conn->reconnect.retries = 0;
492 conn->reconnect.previous = now;
495 /* are we reconnectind too often and too fast? */
496 if (conn->reconnect.retries > conn->reconnect.max_retries) return;
498 /* keep track of the number of reconnections */
499 conn->reconnect.retries++;
502 status = ldap_connect(conn, conn->reconnect.url);
503 if ( ! NT_STATUS_IS_OK(status)) {
508 status = ldap_rebind(conn);
509 if ( ! NT_STATUS_IS_OK(status)) {
510 ldap_connection_dead(conn);
514 /* destroy an open ldap request */
515 static int ldap_request_destructor(struct ldap_request *req)
517 if (req->state == LDAP_REQUEST_PENDING) {
518 DLIST_REMOVE(req->conn->pending, req);
524 called on timeout of a ldap request
526 static void ldap_request_timeout(struct event_context *ev, struct timed_event *te,
527 struct timeval t, void *private_data)
529 struct ldap_request *req = talloc_get_type(private_data, struct ldap_request);
530 req->status = NT_STATUS_IO_TIMEOUT;
531 if (req->state == LDAP_REQUEST_PENDING) {
532 DLIST_REMOVE(req->conn->pending, req);
534 req->state = LDAP_REQUEST_DONE;
542 called on completion of a one-way ldap request
544 static void ldap_request_complete(struct event_context *ev, struct timed_event *te,
545 struct timeval t, void *private_data)
547 struct ldap_request *req = talloc_get_type(private_data, struct ldap_request);
554 send a ldap message - async interface
556 struct ldap_request *ldap_request_send(struct ldap_connection *conn,
557 struct ldap_message *msg)
559 struct ldap_request *req;
560 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
562 req = talloc_zero(conn, struct ldap_request);
563 if (req == NULL) return NULL;
565 if (conn->sock == NULL) {
566 status = NT_STATUS_INVALID_CONNECTION;
570 req->state = LDAP_REQUEST_SEND;
572 req->messageid = conn->next_messageid++;
573 if (conn->next_messageid == 0) {
574 conn->next_messageid = 1;
576 req->type = msg->type;
577 if (req->messageid == -1) {
581 talloc_set_destructor(req, ldap_request_destructor);
583 msg->messageid = req->messageid;
585 if (!ldap_encode(msg, &req->data, req)) {
586 status = NT_STATUS_INTERNAL_ERROR;
590 status = packet_send(conn->packet, req->data);
591 if (!NT_STATUS_IS_OK(status)) {
595 /* some requests don't expect a reply, so don't add those to the
597 if (req->type == LDAP_TAG_AbandonRequest ||
598 req->type == LDAP_TAG_UnbindRequest) {
599 req->status = NT_STATUS_OK;
600 req->state = LDAP_REQUEST_DONE;
601 /* we can't call the async callback now, as it isn't setup, so
602 call it as next event */
603 event_add_timed(conn->event.event_ctx, req, timeval_zero(),
604 ldap_request_complete, req);
608 req->state = LDAP_REQUEST_PENDING;
609 DLIST_ADD(conn->pending, req);
611 /* put a timeout on the request */
612 req->time_event = event_add_timed(conn->event.event_ctx, req,
613 timeval_current_ofs(conn->timeout, 0),
614 ldap_request_timeout, req);
619 req->status = status;
620 req->state = LDAP_REQUEST_ERROR;
621 event_add_timed(conn->event.event_ctx, req, timeval_zero(),
622 ldap_request_complete, req);
629 wait for a request to complete
630 note that this does not destroy the request
632 NTSTATUS ldap_request_wait(struct ldap_request *req)
634 while (req->state < LDAP_REQUEST_DONE) {
635 if (event_loop_once(req->conn->event.event_ctx) != 0) {
636 req->status = NT_STATUS_UNEXPECTED_NETWORK_ERROR;
645 a mapping of ldap response code to strings
647 static const struct {
648 enum ldap_result_code code;
650 } ldap_code_map[] = {
651 #define _LDAP_MAP_CODE(c) { c, #c }
652 _LDAP_MAP_CODE(LDAP_SUCCESS),
653 _LDAP_MAP_CODE(LDAP_OPERATIONS_ERROR),
654 _LDAP_MAP_CODE(LDAP_PROTOCOL_ERROR),
655 _LDAP_MAP_CODE(LDAP_TIME_LIMIT_EXCEEDED),
656 _LDAP_MAP_CODE(LDAP_SIZE_LIMIT_EXCEEDED),
657 _LDAP_MAP_CODE(LDAP_COMPARE_FALSE),
658 _LDAP_MAP_CODE(LDAP_COMPARE_TRUE),
659 _LDAP_MAP_CODE(LDAP_AUTH_METHOD_NOT_SUPPORTED),
660 _LDAP_MAP_CODE(LDAP_STRONG_AUTH_REQUIRED),
661 _LDAP_MAP_CODE(LDAP_REFERRAL),
662 _LDAP_MAP_CODE(LDAP_ADMIN_LIMIT_EXCEEDED),
663 _LDAP_MAP_CODE(LDAP_UNAVAILABLE_CRITICAL_EXTENSION),
664 _LDAP_MAP_CODE(LDAP_CONFIDENTIALITY_REQUIRED),
665 _LDAP_MAP_CODE(LDAP_SASL_BIND_IN_PROGRESS),
666 _LDAP_MAP_CODE(LDAP_NO_SUCH_ATTRIBUTE),
667 _LDAP_MAP_CODE(LDAP_UNDEFINED_ATTRIBUTE_TYPE),
668 _LDAP_MAP_CODE(LDAP_INAPPROPRIATE_MATCHING),
669 _LDAP_MAP_CODE(LDAP_CONSTRAINT_VIOLATION),
670 _LDAP_MAP_CODE(LDAP_ATTRIBUTE_OR_VALUE_EXISTS),
671 _LDAP_MAP_CODE(LDAP_INVALID_ATTRIBUTE_SYNTAX),
672 _LDAP_MAP_CODE(LDAP_NO_SUCH_OBJECT),
673 _LDAP_MAP_CODE(LDAP_ALIAS_PROBLEM),
674 _LDAP_MAP_CODE(LDAP_INVALID_DN_SYNTAX),
675 _LDAP_MAP_CODE(LDAP_ALIAS_DEREFERENCING_PROBLEM),
676 _LDAP_MAP_CODE(LDAP_INAPPROPRIATE_AUTHENTICATION),
677 _LDAP_MAP_CODE(LDAP_INVALID_CREDENTIALS),
678 _LDAP_MAP_CODE(LDAP_INSUFFICIENT_ACCESS_RIGHTS),
679 _LDAP_MAP_CODE(LDAP_BUSY),
680 _LDAP_MAP_CODE(LDAP_UNAVAILABLE),
681 _LDAP_MAP_CODE(LDAP_UNWILLING_TO_PERFORM),
682 _LDAP_MAP_CODE(LDAP_LOOP_DETECT),
683 _LDAP_MAP_CODE(LDAP_NAMING_VIOLATION),
684 _LDAP_MAP_CODE(LDAP_OBJECT_CLASS_VIOLATION),
685 _LDAP_MAP_CODE(LDAP_NOT_ALLOWED_ON_NON_LEAF),
686 _LDAP_MAP_CODE(LDAP_NOT_ALLOWED_ON_RDN),
687 _LDAP_MAP_CODE(LDAP_ENTRY_ALREADY_EXISTS),
688 _LDAP_MAP_CODE(LDAP_OBJECT_CLASS_MODS_PROHIBITED),
689 _LDAP_MAP_CODE(LDAP_AFFECTS_MULTIPLE_DSAS),
690 _LDAP_MAP_CODE(LDAP_OTHER)
694 used to setup the status code from a ldap response
696 NTSTATUS ldap_check_response(struct ldap_connection *conn, struct ldap_Result *r)
699 const char *codename = "unknown";
701 if (r->resultcode == LDAP_SUCCESS) {
705 if (conn->last_error) {
706 talloc_free(conn->last_error);
709 for (i=0;i<ARRAY_SIZE(ldap_code_map);i++) {
710 if (r->resultcode == ldap_code_map[i].code) {
711 codename = ldap_code_map[i].str;
716 conn->last_error = talloc_asprintf(conn, "LDAP error %u %s - %s <%s> <%s>",
719 r->dn?r->dn:"(NULL)",
720 r->errormessage?r->errormessage:"",
721 r->referral?r->referral:"");
723 return NT_STATUS_LDAP(r->resultcode);
727 return error string representing the last error
729 const char *ldap_errstr(struct ldap_connection *conn,
733 if (NT_STATUS_IS_LDAP(status) && conn->last_error != NULL) {
734 return talloc_strdup(mem_ctx, conn->last_error);
736 return talloc_asprintf(mem_ctx, "LDAP client internal error: %s", nt_errstr(status));
741 return the Nth result message, waiting if necessary
743 NTSTATUS ldap_result_n(struct ldap_request *req, int n, struct ldap_message **msg)
747 NT_STATUS_HAVE_NO_MEMORY(req);
749 while (req->state < LDAP_REQUEST_DONE && n >= req->num_replies) {
750 if (event_loop_once(req->conn->event.event_ctx) != 0) {
751 return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
755 if (n < req->num_replies) {
756 *msg = req->replies[n];
760 if (!NT_STATUS_IS_OK(req->status)) {
764 return NT_STATUS_NO_MORE_ENTRIES;
769 return a single result message, checking if it is of the expected LDAP type
771 NTSTATUS ldap_result_one(struct ldap_request *req, struct ldap_message **msg, int type)
774 status = ldap_result_n(req, 0, msg);
775 if (!NT_STATUS_IS_OK(status)) {
778 if ((*msg)->type != type) {
780 return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
786 a simple ldap transaction, for single result requests that only need a status code
787 this relies on single valued requests having the response type == request type + 1
789 NTSTATUS ldap_transaction(struct ldap_connection *conn, struct ldap_message *msg)
791 struct ldap_request *req = ldap_request_send(conn, msg);
792 struct ldap_message *res;
794 status = ldap_result_n(req, 0, &res);
795 if (!NT_STATUS_IS_OK(status)) {
799 if (res->type != msg->type + 1) {
801 return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);
803 status = ldap_check_response(conn, &res->r.GeneralResult);