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"
37 #include "param/param.h"
41 create a new ldap_connection stucture. The event context is optional
43 struct ldap_connection *ldap4_new_connection(TALLOC_CTX *mem_ctx,
44 struct event_context *ev)
46 struct ldap_connection *conn;
48 conn = talloc_zero(mem_ctx, struct ldap_connection);
54 ev = event_context_init(conn);
61 conn->next_messageid = 1;
62 conn->event.event_ctx = ev;
64 /* set a reasonable request timeout */
67 /* explicitly avoid reconnections by default */
68 conn->reconnect.max_retries = 0;
74 the connection is dead
76 static void ldap_connection_dead(struct ldap_connection *conn)
78 struct ldap_request *req;
80 /* return an error for any pending request ... */
81 while (conn->pending) {
83 DLIST_REMOVE(req->conn->pending, req);
84 req->state = LDAP_REQUEST_DONE;
85 req->status = NT_STATUS_UNEXPECTED_NETWORK_ERROR;
91 talloc_free(conn->sock); /* this will also free event.fde */
92 talloc_free(conn->packet);
94 conn->event.fde = NULL;
98 static void ldap_reconnect(struct ldap_connection *conn);
103 static void ldap_error_handler(void *private_data, NTSTATUS status)
105 struct ldap_connection *conn = talloc_get_type(private_data,
106 struct ldap_connection);
107 ldap_connection_dead(conn);
109 /* but try to reconnect so that the ldb client can go on */
110 ldap_reconnect(conn);
115 match up with a pending message, adding to the replies list
117 static void ldap_match_message(struct ldap_connection *conn, struct ldap_message *msg)
119 struct ldap_request *req;
122 for (req=conn->pending; req; req=req->next) {
123 if (req->messageid == msg->messageid) break;
125 /* match a zero message id to the last request sent.
126 It seems that servers send 0 if unable to parse */
127 if (req == NULL && msg->messageid == 0) {
131 DEBUG(0,("ldap: no matching message id for %u\n",
137 /* Check for undecoded critical extensions */
138 for (i=0; msg->controls && msg->controls[i]; i++) {
139 if (!msg->controls_decoded[i] &&
140 msg->controls[i]->critical) {
141 req->status = NT_STATUS_LDAP(LDAP_UNAVAILABLE_CRITICAL_EXTENSION);
142 req->state = LDAP_REQUEST_DONE;
143 DLIST_REMOVE(conn->pending, req);
151 /* add to the list of replies received */
152 talloc_steal(req, msg);
153 req->replies = talloc_realloc(req, req->replies,
154 struct ldap_message *, req->num_replies+1);
155 if (req->replies == NULL) {
156 req->status = NT_STATUS_NO_MEMORY;
157 req->state = LDAP_REQUEST_DONE;
158 DLIST_REMOVE(conn->pending, req);
165 req->replies[req->num_replies] = talloc_steal(req->replies, msg);
168 if (msg->type != LDAP_TAG_SearchResultEntry &&
169 msg->type != LDAP_TAG_SearchResultReference) {
170 /* currently only search results expect multiple
172 req->state = LDAP_REQUEST_DONE;
173 DLIST_REMOVE(conn->pending, req);
183 decode/process LDAP data
185 static NTSTATUS ldap_recv_handler(void *private_data, DATA_BLOB blob)
188 struct ldap_connection *conn = talloc_get_type(private_data,
189 struct ldap_connection);
190 struct ldap_message *msg = talloc(conn, struct ldap_message);
191 struct asn1_data *asn1 = asn1_init(conn);
193 if (asn1 == NULL || msg == NULL) {
194 return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);
197 if (!asn1_load(asn1, blob)) {
200 return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);
203 status = ldap_decode(asn1, msg);
204 if (!NT_STATUS_IS_OK(status)) {
209 ldap_match_message(conn, msg);
211 data_blob_free(&blob);
216 /* Handle read events, from the GENSEC socket callback, or real events */
217 void ldap_read_io_handler(void *private_data, uint16_t flags)
219 struct ldap_connection *conn = talloc_get_type(private_data,
220 struct ldap_connection);
221 packet_recv(conn->packet);
225 handle ldap socket events
227 static void ldap_io_handler(struct event_context *ev, struct fd_event *fde,
228 uint16_t flags, void *private_data)
230 struct ldap_connection *conn = talloc_get_type(private_data,
231 struct ldap_connection);
232 if (flags & EVENT_FD_WRITE) {
233 packet_queue_run(conn->packet);
234 if (!tls_enabled(conn->sock)) return;
236 if (flags & EVENT_FD_READ) {
237 ldap_read_io_handler(private_data, flags);
244 static NTSTATUS ldap_parse_basic_url(TALLOC_CTX *mem_ctx, const char *url,
245 char **host, uint16_t *port, bool *ldaps)
253 SMB_ASSERT(sizeof(protocol)>10 && sizeof(tmp_host)>254);
255 ret = sscanf(url, "%10[^:]://%254[^:/]:%d", protocol, tmp_host, &tmp_port);
257 return NT_STATUS_INVALID_PARAMETER;
260 if (strequal(protocol, "ldap")) {
263 } else if (strequal(protocol, "ldaps")) {
267 DEBUG(0, ("unrecognised ldap protocol (%s)!\n", protocol));
268 return NT_STATUS_PROTOCOL_UNREACHABLE;
274 *host = talloc_strdup(mem_ctx, tmp_host);
275 NT_STATUS_HAVE_NO_MEMORY(*host);
281 connect to a ldap server
284 struct ldap_connect_state {
285 struct composite_context *ctx;
286 struct ldap_connection *conn;
289 static void ldap_connect_recv_unix_conn(struct composite_context *ctx);
290 static void ldap_connect_recv_tcp_conn(struct composite_context *ctx);
292 struct composite_context *ldap_connect_send(struct ldap_connection *conn,
295 struct composite_context *result, *ctx;
296 struct ldap_connect_state *state;
300 result = talloc_zero(NULL, struct composite_context);
301 if (result == NULL) goto failed;
302 result->state = COMPOSITE_STATE_IN_PROGRESS;
303 result->async.fn = NULL;
304 result->event_ctx = conn->event.event_ctx;
306 state = talloc(result, struct ldap_connect_state);
307 if (state == NULL) goto failed;
309 result->private_data = state;
313 if (conn->reconnect.url == NULL) {
314 conn->reconnect.url = talloc_strdup(conn, url);
315 if (conn->reconnect.url == NULL) goto failed;
319 SMB_ASSERT(sizeof(protocol)>10);
321 ret = sscanf(url, "%10[^:]://", protocol);
326 if (strequal(protocol, "ldapi")) {
327 struct socket_address *unix_addr;
330 NTSTATUS status = socket_create("unix", SOCKET_TYPE_STREAM, &conn->sock, 0);
331 if (!NT_STATUS_IS_OK(status)) {
334 talloc_steal(conn, conn->sock);
335 SMB_ASSERT(sizeof(protocol)>10);
336 SMB_ASSERT(sizeof(path)>1024);
338 /* The %c specifier doesn't null terminate :-( */
340 ret = sscanf(url, "%10[^:]://%1025c", protocol, path);
342 composite_error(state->ctx, NT_STATUS_INVALID_PARAMETER);
346 rfc1738_unescape(path);
348 unix_addr = socket_address_from_strings(conn, conn->sock->backend_name,
354 ctx = socket_connect_send(conn->sock, NULL, unix_addr,
355 0, lp_name_resolve_order(global_loadparm), conn->event.event_ctx);
356 ctx->async.fn = ldap_connect_recv_unix_conn;
357 ctx->async.private_data = state;
360 NTSTATUS status = ldap_parse_basic_url(conn, url, &conn->host,
361 &conn->port, &conn->ldaps);
362 if (!NT_STATUS_IS_OK(state->ctx->status)) {
363 composite_error(state->ctx, status);
367 ctx = socket_connect_multi_send(state, conn->host, 1, &conn->port,
368 lp_name_resolve_order(global_loadparm), conn->event.event_ctx);
369 if (ctx == NULL) goto failed;
371 ctx->async.fn = ldap_connect_recv_tcp_conn;
372 ctx->async.private_data = state;
380 static void ldap_connect_got_sock(struct composite_context *ctx,
381 struct ldap_connection *conn)
383 /* setup a handler for events on this socket */
384 conn->event.fde = event_add_fd(conn->event.event_ctx, conn->sock,
385 socket_get_fd(conn->sock),
386 EVENT_FD_READ | EVENT_FD_AUTOCLOSE, ldap_io_handler, conn);
387 if (conn->event.fde == NULL) {
388 composite_error(ctx, NT_STATUS_INTERNAL_ERROR);
392 socket_set_flags(conn->sock, SOCKET_FLAG_NOCLOSE);
394 talloc_steal(conn, conn->sock);
396 struct socket_context *tls_socket;
397 char *cafile = private_path(conn->sock, global_loadparm, lp_tls_cafile(global_loadparm));
399 if (!cafile || !*cafile) {
400 talloc_free(conn->sock);
404 tls_socket = tls_init_client(conn->sock, conn->event.fde, cafile);
407 if (tls_socket == NULL) {
408 talloc_free(conn->sock);
411 talloc_unlink(conn, conn->sock);
412 conn->sock = tls_socket;
413 talloc_steal(conn, conn->sock);
416 conn->packet = packet_init(conn);
417 if (conn->packet == NULL) {
418 talloc_free(conn->sock);
422 packet_set_private(conn->packet, conn);
423 packet_set_socket(conn->packet, conn->sock);
424 packet_set_callback(conn->packet, ldap_recv_handler);
425 packet_set_full_request(conn->packet, ldap_full_packet);
426 packet_set_error_handler(conn->packet, ldap_error_handler);
427 packet_set_event_context(conn->packet, conn->event.event_ctx);
428 packet_set_fde(conn->packet, conn->event.fde);
429 packet_set_serialise(conn->packet);
434 static void ldap_connect_recv_tcp_conn(struct composite_context *ctx)
436 struct ldap_connect_state *state =
437 talloc_get_type(ctx->async.private_data,
438 struct ldap_connect_state);
439 struct ldap_connection *conn = state->conn;
441 NTSTATUS status = socket_connect_multi_recv(ctx, state, &conn->sock,
443 if (!NT_STATUS_IS_OK(status)) {
444 composite_error(state->ctx, status);
448 ldap_connect_got_sock(state->ctx, conn);
451 static void ldap_connect_recv_unix_conn(struct composite_context *ctx)
453 struct ldap_connect_state *state =
454 talloc_get_type(ctx->async.private_data,
455 struct ldap_connect_state);
456 struct ldap_connection *conn = state->conn;
458 NTSTATUS status = socket_connect_recv(ctx);
460 if (!NT_STATUS_IS_OK(state->ctx->status)) {
461 composite_error(state->ctx, status);
465 ldap_connect_got_sock(state->ctx, conn);
468 _PUBLIC_ NTSTATUS ldap_connect_recv(struct composite_context *ctx)
470 NTSTATUS status = composite_wait(ctx);
475 NTSTATUS ldap_connect(struct ldap_connection *conn, const char *url)
477 struct composite_context *ctx = ldap_connect_send(conn, url);
478 return ldap_connect_recv(ctx);
481 /* set reconnect parameters */
483 void ldap_set_reconn_params(struct ldap_connection *conn, int max_retries)
486 conn->reconnect.max_retries = max_retries;
487 conn->reconnect.retries = 0;
488 conn->reconnect.previous = time(NULL);
492 /* Actually this function is NOT ASYNC safe, FIXME? */
493 static void ldap_reconnect(struct ldap_connection *conn)
496 time_t now = time(NULL);
498 /* do we have set up reconnect ? */
499 if (conn->reconnect.max_retries == 0) return;
501 /* is the retry time expired ? */
502 if (now > conn->reconnect.previous + 30) {
503 conn->reconnect.retries = 0;
504 conn->reconnect.previous = now;
507 /* are we reconnectind too often and too fast? */
508 if (conn->reconnect.retries > conn->reconnect.max_retries) return;
510 /* keep track of the number of reconnections */
511 conn->reconnect.retries++;
514 status = ldap_connect(conn, conn->reconnect.url);
515 if ( ! NT_STATUS_IS_OK(status)) {
520 status = ldap_rebind(conn);
521 if ( ! NT_STATUS_IS_OK(status)) {
522 ldap_connection_dead(conn);
526 /* destroy an open ldap request */
527 static int ldap_request_destructor(struct ldap_request *req)
529 if (req->state == LDAP_REQUEST_PENDING) {
530 DLIST_REMOVE(req->conn->pending, req);
536 called on timeout of a ldap request
538 static void ldap_request_timeout(struct event_context *ev, struct timed_event *te,
539 struct timeval t, void *private_data)
541 struct ldap_request *req = talloc_get_type(private_data, struct ldap_request);
542 req->status = NT_STATUS_IO_TIMEOUT;
543 if (req->state == LDAP_REQUEST_PENDING) {
544 DLIST_REMOVE(req->conn->pending, req);
546 req->state = LDAP_REQUEST_DONE;
554 called on completion of a one-way ldap request
556 static void ldap_request_complete(struct event_context *ev, struct timed_event *te,
557 struct timeval t, void *private_data)
559 struct ldap_request *req = talloc_get_type(private_data, struct ldap_request);
566 send a ldap message - async interface
568 struct ldap_request *ldap_request_send(struct ldap_connection *conn,
569 struct ldap_message *msg)
571 struct ldap_request *req;
572 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
574 req = talloc_zero(conn, struct ldap_request);
575 if (req == NULL) return NULL;
577 if (conn->sock == NULL) {
578 status = NT_STATUS_INVALID_CONNECTION;
582 req->state = LDAP_REQUEST_SEND;
584 req->messageid = conn->next_messageid++;
585 if (conn->next_messageid == 0) {
586 conn->next_messageid = 1;
588 req->type = msg->type;
589 if (req->messageid == -1) {
593 talloc_set_destructor(req, ldap_request_destructor);
595 msg->messageid = req->messageid;
597 if (!ldap_encode(msg, &req->data, req)) {
598 status = NT_STATUS_INTERNAL_ERROR;
602 status = packet_send(conn->packet, req->data);
603 if (!NT_STATUS_IS_OK(status)) {
607 /* some requests don't expect a reply, so don't add those to the
609 if (req->type == LDAP_TAG_AbandonRequest ||
610 req->type == LDAP_TAG_UnbindRequest) {
611 req->status = NT_STATUS_OK;
612 req->state = LDAP_REQUEST_DONE;
613 /* we can't call the async callback now, as it isn't setup, so
614 call it as next event */
615 event_add_timed(conn->event.event_ctx, req, timeval_zero(),
616 ldap_request_complete, req);
620 req->state = LDAP_REQUEST_PENDING;
621 DLIST_ADD(conn->pending, req);
623 /* put a timeout on the request */
624 req->time_event = event_add_timed(conn->event.event_ctx, req,
625 timeval_current_ofs(conn->timeout, 0),
626 ldap_request_timeout, req);
631 req->status = status;
632 req->state = LDAP_REQUEST_ERROR;
633 event_add_timed(conn->event.event_ctx, req, timeval_zero(),
634 ldap_request_complete, req);
641 wait for a request to complete
642 note that this does not destroy the request
644 NTSTATUS ldap_request_wait(struct ldap_request *req)
646 while (req->state < LDAP_REQUEST_DONE) {
647 if (event_loop_once(req->conn->event.event_ctx) != 0) {
648 req->status = NT_STATUS_UNEXPECTED_NETWORK_ERROR;
657 a mapping of ldap response code to strings
659 static const struct {
660 enum ldap_result_code code;
662 } ldap_code_map[] = {
663 #define _LDAP_MAP_CODE(c) { c, #c }
664 _LDAP_MAP_CODE(LDAP_SUCCESS),
665 _LDAP_MAP_CODE(LDAP_OPERATIONS_ERROR),
666 _LDAP_MAP_CODE(LDAP_PROTOCOL_ERROR),
667 _LDAP_MAP_CODE(LDAP_TIME_LIMIT_EXCEEDED),
668 _LDAP_MAP_CODE(LDAP_SIZE_LIMIT_EXCEEDED),
669 _LDAP_MAP_CODE(LDAP_COMPARE_FALSE),
670 _LDAP_MAP_CODE(LDAP_COMPARE_TRUE),
671 _LDAP_MAP_CODE(LDAP_AUTH_METHOD_NOT_SUPPORTED),
672 _LDAP_MAP_CODE(LDAP_STRONG_AUTH_REQUIRED),
673 _LDAP_MAP_CODE(LDAP_REFERRAL),
674 _LDAP_MAP_CODE(LDAP_ADMIN_LIMIT_EXCEEDED),
675 _LDAP_MAP_CODE(LDAP_UNAVAILABLE_CRITICAL_EXTENSION),
676 _LDAP_MAP_CODE(LDAP_CONFIDENTIALITY_REQUIRED),
677 _LDAP_MAP_CODE(LDAP_SASL_BIND_IN_PROGRESS),
678 _LDAP_MAP_CODE(LDAP_NO_SUCH_ATTRIBUTE),
679 _LDAP_MAP_CODE(LDAP_UNDEFINED_ATTRIBUTE_TYPE),
680 _LDAP_MAP_CODE(LDAP_INAPPROPRIATE_MATCHING),
681 _LDAP_MAP_CODE(LDAP_CONSTRAINT_VIOLATION),
682 _LDAP_MAP_CODE(LDAP_ATTRIBUTE_OR_VALUE_EXISTS),
683 _LDAP_MAP_CODE(LDAP_INVALID_ATTRIBUTE_SYNTAX),
684 _LDAP_MAP_CODE(LDAP_NO_SUCH_OBJECT),
685 _LDAP_MAP_CODE(LDAP_ALIAS_PROBLEM),
686 _LDAP_MAP_CODE(LDAP_INVALID_DN_SYNTAX),
687 _LDAP_MAP_CODE(LDAP_ALIAS_DEREFERENCING_PROBLEM),
688 _LDAP_MAP_CODE(LDAP_INAPPROPRIATE_AUTHENTICATION),
689 _LDAP_MAP_CODE(LDAP_INVALID_CREDENTIALS),
690 _LDAP_MAP_CODE(LDAP_INSUFFICIENT_ACCESS_RIGHTS),
691 _LDAP_MAP_CODE(LDAP_BUSY),
692 _LDAP_MAP_CODE(LDAP_UNAVAILABLE),
693 _LDAP_MAP_CODE(LDAP_UNWILLING_TO_PERFORM),
694 _LDAP_MAP_CODE(LDAP_LOOP_DETECT),
695 _LDAP_MAP_CODE(LDAP_NAMING_VIOLATION),
696 _LDAP_MAP_CODE(LDAP_OBJECT_CLASS_VIOLATION),
697 _LDAP_MAP_CODE(LDAP_NOT_ALLOWED_ON_NON_LEAF),
698 _LDAP_MAP_CODE(LDAP_NOT_ALLOWED_ON_RDN),
699 _LDAP_MAP_CODE(LDAP_ENTRY_ALREADY_EXISTS),
700 _LDAP_MAP_CODE(LDAP_OBJECT_CLASS_MODS_PROHIBITED),
701 _LDAP_MAP_CODE(LDAP_AFFECTS_MULTIPLE_DSAS),
702 _LDAP_MAP_CODE(LDAP_OTHER)
706 used to setup the status code from a ldap response
708 NTSTATUS ldap_check_response(struct ldap_connection *conn, struct ldap_Result *r)
711 const char *codename = "unknown";
713 if (r->resultcode == LDAP_SUCCESS) {
717 if (conn->last_error) {
718 talloc_free(conn->last_error);
721 for (i=0;i<ARRAY_SIZE(ldap_code_map);i++) {
722 if (r->resultcode == ldap_code_map[i].code) {
723 codename = ldap_code_map[i].str;
728 conn->last_error = talloc_asprintf(conn, "LDAP error %u %s - %s <%s> <%s>",
731 r->dn?r->dn:"(NULL)",
732 r->errormessage?r->errormessage:"",
733 r->referral?r->referral:"");
735 return NT_STATUS_LDAP(r->resultcode);
739 return error string representing the last error
741 const char *ldap_errstr(struct ldap_connection *conn,
745 if (NT_STATUS_IS_LDAP(status) && conn->last_error != NULL) {
746 return talloc_strdup(mem_ctx, conn->last_error);
748 return talloc_asprintf(mem_ctx, "LDAP client internal error: %s", nt_errstr(status));
753 return the Nth result message, waiting if necessary
755 NTSTATUS ldap_result_n(struct ldap_request *req, int n, struct ldap_message **msg)
759 NT_STATUS_HAVE_NO_MEMORY(req);
761 while (req->state < LDAP_REQUEST_DONE && n >= req->num_replies) {
762 if (event_loop_once(req->conn->event.event_ctx) != 0) {
763 return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
767 if (n < req->num_replies) {
768 *msg = req->replies[n];
772 if (!NT_STATUS_IS_OK(req->status)) {
776 return NT_STATUS_NO_MORE_ENTRIES;
781 return a single result message, checking if it is of the expected LDAP type
783 NTSTATUS ldap_result_one(struct ldap_request *req, struct ldap_message **msg, int type)
786 status = ldap_result_n(req, 0, msg);
787 if (!NT_STATUS_IS_OK(status)) {
790 if ((*msg)->type != type) {
792 return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
798 a simple ldap transaction, for single result requests that only need a status code
799 this relies on single valued requests having the response type == request type + 1
801 NTSTATUS ldap_transaction(struct ldap_connection *conn, struct ldap_message *msg)
803 struct ldap_request *req = ldap_request_send(conn, msg);
804 struct ldap_message *res;
806 status = ldap_result_n(req, 0, &res);
807 if (!NT_STATUS_IS_OK(status)) {
811 if (res->type != msg->type + 1) {
813 return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);
815 status = ldap_check_response(conn, &res->r.GeneralResult);