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;
120 for (req=conn->pending; req; req=req->next) {
121 if (req->messageid == msg->messageid) break;
123 /* match a zero message id to the last request sent.
124 It seems that servers send 0 if unable to parse */
125 if (req == NULL && msg->messageid == 0) {
129 DEBUG(0,("ldap: no matching message id for %u\n",
135 /* add to the list of replies received */
136 talloc_steal(req, msg);
137 req->replies = talloc_realloc(req, req->replies,
138 struct ldap_message *, req->num_replies+1);
139 if (req->replies == NULL) {
140 req->status = NT_STATUS_NO_MEMORY;
141 req->state = LDAP_REQUEST_DONE;
142 DLIST_REMOVE(conn->pending, req);
149 req->replies[req->num_replies] = talloc_steal(req->replies, msg);
152 if (msg->type != LDAP_TAG_SearchResultEntry &&
153 msg->type != LDAP_TAG_SearchResultReference) {
154 /* currently only search results expect multiple
156 req->state = LDAP_REQUEST_DONE;
157 DLIST_REMOVE(conn->pending, req);
167 decode/process LDAP data
169 static NTSTATUS ldap_recv_handler(void *private_data, DATA_BLOB blob)
172 struct ldap_connection *conn = talloc_get_type(private_data,
173 struct ldap_connection);
174 struct ldap_message *msg = talloc(conn, struct ldap_message);
175 struct asn1_data *asn1 = asn1_init(conn);
177 if (asn1 == NULL || msg == NULL) {
178 return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);
181 if (!asn1_load(asn1, blob)) {
184 return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);
187 status = ldap_decode(asn1, msg);
188 if (!NT_STATUS_IS_OK(status)) {
193 ldap_match_message(conn, msg);
195 data_blob_free(&blob);
200 /* Handle read events, from the GENSEC socket callback, or real events */
201 void ldap_read_io_handler(void *private_data, uint16_t flags)
203 struct ldap_connection *conn = talloc_get_type(private_data,
204 struct ldap_connection);
205 packet_recv(conn->packet);
209 handle ldap socket events
211 static void ldap_io_handler(struct event_context *ev, struct fd_event *fde,
212 uint16_t flags, void *private_data)
214 struct ldap_connection *conn = talloc_get_type(private_data,
215 struct ldap_connection);
216 if (flags & EVENT_FD_WRITE) {
217 packet_queue_run(conn->packet);
218 if (!tls_enabled(conn->sock)) return;
220 if (flags & EVENT_FD_READ) {
221 ldap_read_io_handler(private_data, flags);
228 static NTSTATUS ldap_parse_basic_url(TALLOC_CTX *mem_ctx, const char *url,
229 char **host, uint16_t *port, bool *ldaps)
237 SMB_ASSERT(sizeof(protocol)>10 && sizeof(tmp_host)>254);
239 ret = sscanf(url, "%10[^:]://%254[^:/]:%d", protocol, tmp_host, &tmp_port);
241 return NT_STATUS_INVALID_PARAMETER;
244 if (strequal(protocol, "ldap")) {
247 } else if (strequal(protocol, "ldaps")) {
251 DEBUG(0, ("unrecognised ldap protocol (%s)!\n", protocol));
252 return NT_STATUS_PROTOCOL_UNREACHABLE;
258 *host = talloc_strdup(mem_ctx, tmp_host);
259 NT_STATUS_HAVE_NO_MEMORY(*host);
265 connect to a ldap server
268 struct ldap_connect_state {
269 struct composite_context *ctx;
270 struct ldap_connection *conn;
273 static void ldap_connect_recv_unix_conn(struct composite_context *ctx);
274 static void ldap_connect_recv_tcp_conn(struct composite_context *ctx);
276 struct composite_context *ldap_connect_send(struct ldap_connection *conn,
279 struct composite_context *result, *ctx;
280 struct ldap_connect_state *state;
284 result = talloc_zero(NULL, struct composite_context);
285 if (result == NULL) goto failed;
286 result->state = COMPOSITE_STATE_IN_PROGRESS;
287 result->async.fn = NULL;
288 result->event_ctx = conn->event.event_ctx;
290 state = talloc(result, struct ldap_connect_state);
291 if (state == NULL) goto failed;
293 result->private_data = state;
297 if (conn->reconnect.url == NULL) {
298 conn->reconnect.url = talloc_strdup(conn, url);
299 if (conn->reconnect.url == NULL) goto failed;
303 SMB_ASSERT(sizeof(protocol)>10);
305 ret = sscanf(url, "%10[^:]://", protocol);
310 if (strequal(protocol, "ldapi")) {
311 struct socket_address *unix_addr;
314 NTSTATUS status = socket_create("unix", SOCKET_TYPE_STREAM, &conn->sock, 0);
315 if (!NT_STATUS_IS_OK(status)) {
318 talloc_steal(conn, conn->sock);
319 SMB_ASSERT(sizeof(protocol)>10);
320 SMB_ASSERT(sizeof(path)>1024);
322 /* The %c specifier doesn't null terminate :-( */
324 ret = sscanf(url, "%10[^:]://%1025c", protocol, path);
326 composite_error(state->ctx, NT_STATUS_INVALID_PARAMETER);
330 rfc1738_unescape(path);
332 unix_addr = socket_address_from_strings(conn, conn->sock->backend_name,
338 ctx = socket_connect_send(conn->sock, NULL, unix_addr,
339 0, conn->event.event_ctx);
340 ctx->async.fn = ldap_connect_recv_unix_conn;
341 ctx->async.private_data = state;
344 NTSTATUS status = ldap_parse_basic_url(conn, url, &conn->host,
345 &conn->port, &conn->ldaps);
346 if (!NT_STATUS_IS_OK(state->ctx->status)) {
347 composite_error(state->ctx, status);
351 ctx = socket_connect_multi_send(state, conn->host, 1, &conn->port,
352 conn->event.event_ctx);
353 if (ctx == NULL) goto failed;
355 ctx->async.fn = ldap_connect_recv_tcp_conn;
356 ctx->async.private_data = state;
364 static void ldap_connect_got_sock(struct composite_context *ctx, struct ldap_connection *conn)
366 /* setup a handler for events on this socket */
367 conn->event.fde = event_add_fd(conn->event.event_ctx, conn->sock,
368 socket_get_fd(conn->sock),
369 EVENT_FD_READ | EVENT_FD_AUTOCLOSE, ldap_io_handler, conn);
370 if (conn->event.fde == NULL) {
371 composite_error(ctx, NT_STATUS_INTERNAL_ERROR);
375 socket_set_flags(conn->sock, SOCKET_FLAG_NOCLOSE);
377 talloc_steal(conn, conn->sock);
379 struct socket_context *tls_socket = tls_init_client(conn->sock, conn->event.fde);
380 if (tls_socket == NULL) {
381 talloc_free(conn->sock);
384 talloc_unlink(conn, conn->sock);
385 conn->sock = tls_socket;
386 talloc_steal(conn, conn->sock);
389 conn->packet = packet_init(conn);
390 if (conn->packet == NULL) {
391 talloc_free(conn->sock);
395 packet_set_private(conn->packet, conn);
396 packet_set_socket(conn->packet, conn->sock);
397 packet_set_callback(conn->packet, ldap_recv_handler);
398 packet_set_full_request(conn->packet, ldap_full_packet);
399 packet_set_error_handler(conn->packet, ldap_error_handler);
400 packet_set_event_context(conn->packet, conn->event.event_ctx);
401 packet_set_fde(conn->packet, conn->event.fde);
402 packet_set_serialise(conn->packet);
407 static void ldap_connect_recv_tcp_conn(struct composite_context *ctx)
409 struct ldap_connect_state *state =
410 talloc_get_type(ctx->async.private_data,
411 struct ldap_connect_state);
412 struct ldap_connection *conn = state->conn;
414 NTSTATUS status = socket_connect_multi_recv(ctx, state, &conn->sock,
416 if (!NT_STATUS_IS_OK(status)) {
417 composite_error(state->ctx, status);
421 ldap_connect_got_sock(state->ctx, conn);
424 static void ldap_connect_recv_unix_conn(struct composite_context *ctx)
426 struct ldap_connect_state *state =
427 talloc_get_type(ctx->async.private_data,
428 struct ldap_connect_state);
429 struct ldap_connection *conn = state->conn;
431 NTSTATUS status = socket_connect_recv(ctx);
433 if (!NT_STATUS_IS_OK(state->ctx->status)) {
434 composite_error(state->ctx, status);
438 ldap_connect_got_sock(state->ctx, conn);
441 _PUBLIC_ NTSTATUS ldap_connect_recv(struct composite_context *ctx)
443 NTSTATUS status = composite_wait(ctx);
448 NTSTATUS ldap_connect(struct ldap_connection *conn, const char *url)
450 struct composite_context *ctx = ldap_connect_send(conn, url);
451 return ldap_connect_recv(ctx);
454 /* set reconnect parameters */
456 void ldap_set_reconn_params(struct ldap_connection *conn, int max_retries)
459 conn->reconnect.max_retries = max_retries;
460 conn->reconnect.retries = 0;
461 conn->reconnect.previous = time(NULL);
465 /* Actually this function is NOT ASYNC safe, FIXME? */
466 static void ldap_reconnect(struct ldap_connection *conn)
469 time_t now = time(NULL);
471 /* do we have set up reconnect ? */
472 if (conn->reconnect.max_retries == 0) return;
474 /* is the retry time expired ? */
475 if (now > conn->reconnect.previous + 30) {
476 conn->reconnect.retries = 0;
477 conn->reconnect.previous = now;
480 /* are we reconnectind too often and too fast? */
481 if (conn->reconnect.retries > conn->reconnect.max_retries) return;
483 /* keep track of the number of reconnections */
484 conn->reconnect.retries++;
487 status = ldap_connect(conn, conn->reconnect.url);
488 if ( ! NT_STATUS_IS_OK(status)) {
493 status = ldap_rebind(conn);
494 if ( ! NT_STATUS_IS_OK(status)) {
495 ldap_connection_dead(conn);
499 /* destroy an open ldap request */
500 static int ldap_request_destructor(struct ldap_request *req)
502 if (req->state == LDAP_REQUEST_PENDING) {
503 DLIST_REMOVE(req->conn->pending, req);
509 called on timeout of a ldap request
511 static void ldap_request_timeout(struct event_context *ev, struct timed_event *te,
512 struct timeval t, void *private_data)
514 struct ldap_request *req = talloc_get_type(private_data, struct ldap_request);
515 req->status = NT_STATUS_IO_TIMEOUT;
516 if (req->state == LDAP_REQUEST_PENDING) {
517 DLIST_REMOVE(req->conn->pending, req);
519 req->state = LDAP_REQUEST_DONE;
527 called on completion of a one-way ldap request
529 static void ldap_request_complete(struct event_context *ev, struct timed_event *te,
530 struct timeval t, void *private_data)
532 struct ldap_request *req = talloc_get_type(private_data, struct ldap_request);
539 send a ldap message - async interface
541 struct ldap_request *ldap_request_send(struct ldap_connection *conn,
542 struct ldap_message *msg)
544 struct ldap_request *req;
545 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
547 req = talloc_zero(conn, struct ldap_request);
548 if (req == NULL) return NULL;
550 if (conn->sock == NULL) {
551 status = NT_STATUS_INVALID_CONNECTION;
555 req->state = LDAP_REQUEST_SEND;
557 req->messageid = conn->next_messageid++;
558 if (conn->next_messageid == 0) {
559 conn->next_messageid = 1;
561 req->type = msg->type;
562 if (req->messageid == -1) {
566 talloc_set_destructor(req, ldap_request_destructor);
568 msg->messageid = req->messageid;
570 if (!ldap_encode(msg, &req->data, req)) {
571 status = NT_STATUS_INTERNAL_ERROR;
575 status = packet_send(conn->packet, req->data);
576 if (!NT_STATUS_IS_OK(status)) {
580 /* some requests don't expect a reply, so don't add those to the
582 if (req->type == LDAP_TAG_AbandonRequest ||
583 req->type == LDAP_TAG_UnbindRequest) {
584 req->status = NT_STATUS_OK;
585 req->state = LDAP_REQUEST_DONE;
586 /* we can't call the async callback now, as it isn't setup, so
587 call it as next event */
588 event_add_timed(conn->event.event_ctx, req, timeval_zero(),
589 ldap_request_complete, req);
593 req->state = LDAP_REQUEST_PENDING;
594 DLIST_ADD(conn->pending, req);
596 /* put a timeout on the request */
597 req->time_event = event_add_timed(conn->event.event_ctx, req,
598 timeval_current_ofs(conn->timeout, 0),
599 ldap_request_timeout, req);
604 req->status = status;
605 req->state = LDAP_REQUEST_ERROR;
606 event_add_timed(conn->event.event_ctx, req, timeval_zero(),
607 ldap_request_complete, req);
614 wait for a request to complete
615 note that this does not destroy the request
617 NTSTATUS ldap_request_wait(struct ldap_request *req)
619 while (req->state < LDAP_REQUEST_DONE) {
620 if (event_loop_once(req->conn->event.event_ctx) != 0) {
621 req->status = NT_STATUS_UNEXPECTED_NETWORK_ERROR;
630 a mapping of ldap response code to strings
632 static const struct {
633 enum ldap_result_code code;
635 } ldap_code_map[] = {
636 #define _LDAP_MAP_CODE(c) { c, #c }
637 _LDAP_MAP_CODE(LDAP_SUCCESS),
638 _LDAP_MAP_CODE(LDAP_OPERATIONS_ERROR),
639 _LDAP_MAP_CODE(LDAP_PROTOCOL_ERROR),
640 _LDAP_MAP_CODE(LDAP_TIME_LIMIT_EXCEEDED),
641 _LDAP_MAP_CODE(LDAP_SIZE_LIMIT_EXCEEDED),
642 _LDAP_MAP_CODE(LDAP_COMPARE_FALSE),
643 _LDAP_MAP_CODE(LDAP_COMPARE_TRUE),
644 _LDAP_MAP_CODE(LDAP_AUTH_METHOD_NOT_SUPPORTED),
645 _LDAP_MAP_CODE(LDAP_STRONG_AUTH_REQUIRED),
646 _LDAP_MAP_CODE(LDAP_REFERRAL),
647 _LDAP_MAP_CODE(LDAP_ADMIN_LIMIT_EXCEEDED),
648 _LDAP_MAP_CODE(LDAP_UNAVAILABLE_CRITICAL_EXTENSION),
649 _LDAP_MAP_CODE(LDAP_CONFIDENTIALITY_REQUIRED),
650 _LDAP_MAP_CODE(LDAP_SASL_BIND_IN_PROGRESS),
651 _LDAP_MAP_CODE(LDAP_NO_SUCH_ATTRIBUTE),
652 _LDAP_MAP_CODE(LDAP_UNDEFINED_ATTRIBUTE_TYPE),
653 _LDAP_MAP_CODE(LDAP_INAPPROPRIATE_MATCHING),
654 _LDAP_MAP_CODE(LDAP_CONSTRAINT_VIOLATION),
655 _LDAP_MAP_CODE(LDAP_ATTRIBUTE_OR_VALUE_EXISTS),
656 _LDAP_MAP_CODE(LDAP_INVALID_ATTRIBUTE_SYNTAX),
657 _LDAP_MAP_CODE(LDAP_NO_SUCH_OBJECT),
658 _LDAP_MAP_CODE(LDAP_ALIAS_PROBLEM),
659 _LDAP_MAP_CODE(LDAP_INVALID_DN_SYNTAX),
660 _LDAP_MAP_CODE(LDAP_ALIAS_DEREFERENCING_PROBLEM),
661 _LDAP_MAP_CODE(LDAP_INAPPROPRIATE_AUTHENTICATION),
662 _LDAP_MAP_CODE(LDAP_INVALID_CREDENTIALS),
663 _LDAP_MAP_CODE(LDAP_INSUFFICIENT_ACCESS_RIGHTS),
664 _LDAP_MAP_CODE(LDAP_BUSY),
665 _LDAP_MAP_CODE(LDAP_UNAVAILABLE),
666 _LDAP_MAP_CODE(LDAP_UNWILLING_TO_PERFORM),
667 _LDAP_MAP_CODE(LDAP_LOOP_DETECT),
668 _LDAP_MAP_CODE(LDAP_NAMING_VIOLATION),
669 _LDAP_MAP_CODE(LDAP_OBJECT_CLASS_VIOLATION),
670 _LDAP_MAP_CODE(LDAP_NOT_ALLOWED_ON_NON_LEAF),
671 _LDAP_MAP_CODE(LDAP_NOT_ALLOWED_ON_RDN),
672 _LDAP_MAP_CODE(LDAP_ENTRY_ALREADY_EXISTS),
673 _LDAP_MAP_CODE(LDAP_OBJECT_CLASS_MODS_PROHIBITED),
674 _LDAP_MAP_CODE(LDAP_AFFECTS_MULTIPLE_DSAS),
675 _LDAP_MAP_CODE(LDAP_OTHER)
679 used to setup the status code from a ldap response
681 NTSTATUS ldap_check_response(struct ldap_connection *conn, struct ldap_Result *r)
684 const char *codename = "unknown";
686 if (r->resultcode == LDAP_SUCCESS) {
690 if (conn->last_error) {
691 talloc_free(conn->last_error);
694 for (i=0;i<ARRAY_SIZE(ldap_code_map);i++) {
695 if (r->resultcode == ldap_code_map[i].code) {
696 codename = ldap_code_map[i].str;
701 conn->last_error = talloc_asprintf(conn, "LDAP error %u %s - %s <%s> <%s>",
704 r->dn?r->dn:"(NULL)",
705 r->errormessage?r->errormessage:"",
706 r->referral?r->referral:"");
708 return NT_STATUS_LDAP(r->resultcode);
712 return error string representing the last error
714 const char *ldap_errstr(struct ldap_connection *conn,
718 if (NT_STATUS_IS_LDAP(status) && conn->last_error != NULL) {
719 return talloc_strdup(mem_ctx, conn->last_error);
721 return talloc_asprintf(mem_ctx, "LDAP client internal error: %s", nt_errstr(status));
726 return the Nth result message, waiting if necessary
728 NTSTATUS ldap_result_n(struct ldap_request *req, int n, struct ldap_message **msg)
732 NT_STATUS_HAVE_NO_MEMORY(req);
734 while (req->state < LDAP_REQUEST_DONE && n >= req->num_replies) {
735 if (event_loop_once(req->conn->event.event_ctx) != 0) {
736 return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
740 if (n < req->num_replies) {
741 *msg = req->replies[n];
745 if (!NT_STATUS_IS_OK(req->status)) {
749 return NT_STATUS_NO_MORE_ENTRIES;
754 return a single result message, checking if it is of the expected LDAP type
756 NTSTATUS ldap_result_one(struct ldap_request *req, struct ldap_message **msg, int type)
759 status = ldap_result_n(req, 0, msg);
760 if (!NT_STATUS_IS_OK(status)) {
763 if ((*msg)->type != type) {
765 return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
771 a simple ldap transaction, for single result requests that only need a status code
772 this relies on single valued requests having the response type == request type + 1
774 NTSTATUS ldap_transaction(struct ldap_connection *conn, struct ldap_message *msg)
776 struct ldap_request *req = ldap_request_send(conn, msg);
777 struct ldap_message *res;
779 status = ldap_result_n(req, 0, &res);
780 if (!NT_STATUS_IS_OK(status)) {
784 if (res->type != msg->type + 1) {
786 return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);
788 status = ldap_check_response(conn, &res->r.GeneralResult);