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"
38 #include "libcli/resolve/resolve.h"
42 create a new ldap_connection stucture. The event context is optional
44 struct ldap_connection *ldap4_new_connection(TALLOC_CTX *mem_ctx,
45 struct loadparm_context *lp_ctx,
46 struct event_context *ev)
48 struct ldap_connection *conn;
50 conn = talloc_zero(mem_ctx, struct ldap_connection);
56 ev = event_context_init(conn);
63 conn->next_messageid = 1;
64 conn->event.event_ctx = ev;
66 conn->lp_ctx = lp_ctx;
68 /* set a reasonable request timeout */
71 /* explicitly avoid reconnections by default */
72 conn->reconnect.max_retries = 0;
78 the connection is dead
80 static void ldap_connection_dead(struct ldap_connection *conn)
82 struct ldap_request *req;
84 /* return an error for any pending request ... */
85 while (conn->pending) {
87 DLIST_REMOVE(req->conn->pending, req);
88 req->state = LDAP_REQUEST_DONE;
89 req->status = NT_STATUS_UNEXPECTED_NETWORK_ERROR;
95 talloc_free(conn->sock); /* this will also free event.fde */
96 talloc_free(conn->packet);
98 conn->event.fde = NULL;
102 static void ldap_reconnect(struct ldap_connection *conn);
107 static void ldap_error_handler(void *private_data, NTSTATUS status)
109 struct ldap_connection *conn = talloc_get_type(private_data,
110 struct ldap_connection);
111 ldap_connection_dead(conn);
113 /* but try to reconnect so that the ldb client can go on */
114 ldap_reconnect(conn);
119 match up with a pending message, adding to the replies list
121 static void ldap_match_message(struct ldap_connection *conn, struct ldap_message *msg)
123 struct ldap_request *req;
126 for (req=conn->pending; req; req=req->next) {
127 if (req->messageid == msg->messageid) break;
129 /* match a zero message id to the last request sent.
130 It seems that servers send 0 if unable to parse */
131 if (req == NULL && msg->messageid == 0) {
135 DEBUG(0,("ldap: no matching message id for %u\n",
141 /* Check for undecoded critical extensions */
142 for (i=0; msg->controls && msg->controls[i]; i++) {
143 if (!msg->controls_decoded[i] &&
144 msg->controls[i]->critical) {
145 req->status = NT_STATUS_LDAP(LDAP_UNAVAILABLE_CRITICAL_EXTENSION);
146 req->state = LDAP_REQUEST_DONE;
147 DLIST_REMOVE(conn->pending, req);
155 /* add to the list of replies received */
156 talloc_steal(req, msg);
157 req->replies = talloc_realloc(req, req->replies,
158 struct ldap_message *, req->num_replies+1);
159 if (req->replies == NULL) {
160 req->status = NT_STATUS_NO_MEMORY;
161 req->state = LDAP_REQUEST_DONE;
162 DLIST_REMOVE(conn->pending, req);
169 req->replies[req->num_replies] = talloc_steal(req->replies, msg);
172 if (msg->type != LDAP_TAG_SearchResultEntry &&
173 msg->type != LDAP_TAG_SearchResultReference) {
174 /* currently only search results expect multiple
176 req->state = LDAP_REQUEST_DONE;
177 DLIST_REMOVE(conn->pending, req);
187 decode/process LDAP data
189 static NTSTATUS ldap_recv_handler(void *private_data, DATA_BLOB blob)
192 struct ldap_connection *conn = talloc_get_type(private_data,
193 struct ldap_connection);
194 struct ldap_message *msg = talloc(conn, struct ldap_message);
195 struct asn1_data *asn1 = asn1_init(conn);
197 if (asn1 == NULL || msg == NULL) {
198 return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);
201 if (!asn1_load(asn1, blob)) {
204 return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);
207 status = ldap_decode(asn1, msg);
208 if (!NT_STATUS_IS_OK(status)) {
213 ldap_match_message(conn, msg);
215 data_blob_free(&blob);
220 /* Handle read events, from the GENSEC socket callback, or real events */
221 void ldap_read_io_handler(void *private_data, uint16_t flags)
223 struct ldap_connection *conn = talloc_get_type(private_data,
224 struct ldap_connection);
225 packet_recv(conn->packet);
229 handle ldap socket events
231 static void ldap_io_handler(struct event_context *ev, struct fd_event *fde,
232 uint16_t flags, void *private_data)
234 struct ldap_connection *conn = talloc_get_type(private_data,
235 struct ldap_connection);
236 if (flags & EVENT_FD_WRITE) {
237 packet_queue_run(conn->packet);
238 if (!tls_enabled(conn->sock)) return;
240 if (flags & EVENT_FD_READ) {
241 ldap_read_io_handler(private_data, flags);
248 static NTSTATUS ldap_parse_basic_url(TALLOC_CTX *mem_ctx, const char *url,
249 char **host, uint16_t *port, bool *ldaps)
257 SMB_ASSERT(sizeof(protocol)>10 && sizeof(tmp_host)>254);
259 ret = sscanf(url, "%10[^:]://%254[^:/]:%d", protocol, tmp_host, &tmp_port);
261 return NT_STATUS_INVALID_PARAMETER;
264 if (strequal(protocol, "ldap")) {
267 } else if (strequal(protocol, "ldaps")) {
271 DEBUG(0, ("unrecognised ldap protocol (%s)!\n", protocol));
272 return NT_STATUS_PROTOCOL_UNREACHABLE;
278 *host = talloc_strdup(mem_ctx, tmp_host);
279 NT_STATUS_HAVE_NO_MEMORY(*host);
285 connect to a ldap server
288 struct ldap_connect_state {
289 struct composite_context *ctx;
290 struct ldap_connection *conn;
293 static void ldap_connect_recv_unix_conn(struct composite_context *ctx);
294 static void ldap_connect_recv_tcp_conn(struct composite_context *ctx);
296 struct composite_context *ldap_connect_send(struct ldap_connection *conn,
299 struct composite_context *result, *ctx;
300 struct ldap_connect_state *state;
304 result = talloc_zero(NULL, struct composite_context);
305 if (result == NULL) goto failed;
306 result->state = COMPOSITE_STATE_IN_PROGRESS;
307 result->async.fn = NULL;
308 result->event_ctx = conn->event.event_ctx;
310 state = talloc(result, struct ldap_connect_state);
311 if (state == NULL) goto failed;
313 result->private_data = state;
317 if (conn->reconnect.url == NULL) {
318 conn->reconnect.url = talloc_strdup(conn, url);
319 if (conn->reconnect.url == NULL) goto failed;
323 SMB_ASSERT(sizeof(protocol)>10);
325 ret = sscanf(url, "%10[^:]://", protocol);
330 if (strequal(protocol, "ldapi")) {
331 struct socket_address *unix_addr;
334 NTSTATUS status = socket_create("unix", SOCKET_TYPE_STREAM, &conn->sock, 0);
335 if (!NT_STATUS_IS_OK(status)) {
338 talloc_steal(conn, conn->sock);
339 SMB_ASSERT(sizeof(protocol)>10);
340 SMB_ASSERT(sizeof(path)>1024);
342 /* The %c specifier doesn't null terminate :-( */
344 ret = sscanf(url, "%10[^:]://%1025c", protocol, path);
346 composite_error(state->ctx, NT_STATUS_INVALID_PARAMETER);
350 rfc1738_unescape(path);
352 unix_addr = socket_address_from_strings(conn, conn->sock->backend_name,
358 ctx = socket_connect_send(conn->sock, NULL, unix_addr,
359 0, lp_resolve_context(conn->lp_ctx), conn->event.event_ctx);
360 ctx->async.fn = ldap_connect_recv_unix_conn;
361 ctx->async.private_data = state;
364 NTSTATUS status = ldap_parse_basic_url(conn, url, &conn->host,
365 &conn->port, &conn->ldaps);
366 if (!NT_STATUS_IS_OK(state->ctx->status)) {
367 composite_error(state->ctx, status);
371 ctx = socket_connect_multi_send(state, conn->host, 1, &conn->port,
372 lp_resolve_context(conn->lp_ctx), conn->event.event_ctx);
373 if (ctx == NULL) goto failed;
375 ctx->async.fn = ldap_connect_recv_tcp_conn;
376 ctx->async.private_data = state;
384 static void ldap_connect_got_sock(struct composite_context *ctx,
385 struct ldap_connection *conn)
387 /* setup a handler for events on this socket */
388 conn->event.fde = event_add_fd(conn->event.event_ctx, conn->sock,
389 socket_get_fd(conn->sock),
390 EVENT_FD_READ | EVENT_FD_AUTOCLOSE, ldap_io_handler, conn);
391 if (conn->event.fde == NULL) {
392 composite_error(ctx, NT_STATUS_INTERNAL_ERROR);
396 socket_set_flags(conn->sock, SOCKET_FLAG_NOCLOSE);
398 talloc_steal(conn, conn->sock);
400 struct socket_context *tls_socket;
401 char *cafile = private_path(conn->sock, conn->lp_ctx, lp_tls_cafile(conn->lp_ctx));
403 if (!cafile || !*cafile) {
404 talloc_free(conn->sock);
408 tls_socket = tls_init_client(conn->sock, conn->event.fde, cafile);
411 if (tls_socket == NULL) {
412 talloc_free(conn->sock);
415 talloc_unlink(conn, conn->sock);
416 conn->sock = tls_socket;
417 talloc_steal(conn, conn->sock);
420 conn->packet = packet_init(conn);
421 if (conn->packet == NULL) {
422 talloc_free(conn->sock);
426 packet_set_private(conn->packet, conn);
427 packet_set_socket(conn->packet, conn->sock);
428 packet_set_callback(conn->packet, ldap_recv_handler);
429 packet_set_full_request(conn->packet, ldap_full_packet);
430 packet_set_error_handler(conn->packet, ldap_error_handler);
431 packet_set_event_context(conn->packet, conn->event.event_ctx);
432 packet_set_fde(conn->packet, conn->event.fde);
433 packet_set_serialise(conn->packet);
438 static void ldap_connect_recv_tcp_conn(struct composite_context *ctx)
440 struct ldap_connect_state *state =
441 talloc_get_type(ctx->async.private_data,
442 struct ldap_connect_state);
443 struct ldap_connection *conn = state->conn;
445 NTSTATUS status = socket_connect_multi_recv(ctx, state, &conn->sock,
447 if (!NT_STATUS_IS_OK(status)) {
448 composite_error(state->ctx, status);
452 ldap_connect_got_sock(state->ctx, conn);
455 static void ldap_connect_recv_unix_conn(struct composite_context *ctx)
457 struct ldap_connect_state *state =
458 talloc_get_type(ctx->async.private_data,
459 struct ldap_connect_state);
460 struct ldap_connection *conn = state->conn;
462 NTSTATUS status = socket_connect_recv(ctx);
464 if (!NT_STATUS_IS_OK(state->ctx->status)) {
465 composite_error(state->ctx, status);
469 ldap_connect_got_sock(state->ctx, conn);
472 _PUBLIC_ NTSTATUS ldap_connect_recv(struct composite_context *ctx)
474 NTSTATUS status = composite_wait(ctx);
479 NTSTATUS ldap_connect(struct ldap_connection *conn, const char *url)
481 struct composite_context *ctx = ldap_connect_send(conn, url);
482 return ldap_connect_recv(ctx);
485 /* set reconnect parameters */
487 void ldap_set_reconn_params(struct ldap_connection *conn, int max_retries)
490 conn->reconnect.max_retries = max_retries;
491 conn->reconnect.retries = 0;
492 conn->reconnect.previous = time(NULL);
496 /* Actually this function is NOT ASYNC safe, FIXME? */
497 static void ldap_reconnect(struct ldap_connection *conn)
500 time_t now = time(NULL);
502 /* do we have set up reconnect ? */
503 if (conn->reconnect.max_retries == 0) return;
505 /* is the retry time expired ? */
506 if (now > conn->reconnect.previous + 30) {
507 conn->reconnect.retries = 0;
508 conn->reconnect.previous = now;
511 /* are we reconnectind too often and too fast? */
512 if (conn->reconnect.retries > conn->reconnect.max_retries) return;
514 /* keep track of the number of reconnections */
515 conn->reconnect.retries++;
518 status = ldap_connect(conn, conn->reconnect.url);
519 if ( ! NT_STATUS_IS_OK(status)) {
524 status = ldap_rebind(conn);
525 if ( ! NT_STATUS_IS_OK(status)) {
526 ldap_connection_dead(conn);
530 /* destroy an open ldap request */
531 static int ldap_request_destructor(struct ldap_request *req)
533 if (req->state == LDAP_REQUEST_PENDING) {
534 DLIST_REMOVE(req->conn->pending, req);
540 called on timeout of a ldap request
542 static void ldap_request_timeout(struct event_context *ev, struct timed_event *te,
543 struct timeval t, void *private_data)
545 struct ldap_request *req = talloc_get_type(private_data, struct ldap_request);
546 req->status = NT_STATUS_IO_TIMEOUT;
547 if (req->state == LDAP_REQUEST_PENDING) {
548 DLIST_REMOVE(req->conn->pending, req);
550 req->state = LDAP_REQUEST_DONE;
558 called on completion of a one-way ldap request
560 static void ldap_request_complete(struct event_context *ev, struct timed_event *te,
561 struct timeval t, void *private_data)
563 struct ldap_request *req = talloc_get_type(private_data, struct ldap_request);
570 send a ldap message - async interface
572 struct ldap_request *ldap_request_send(struct ldap_connection *conn,
573 struct ldap_message *msg)
575 struct ldap_request *req;
576 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
578 req = talloc_zero(conn, struct ldap_request);
579 if (req == NULL) return NULL;
581 if (conn->sock == NULL) {
582 status = NT_STATUS_INVALID_CONNECTION;
586 req->state = LDAP_REQUEST_SEND;
588 req->messageid = conn->next_messageid++;
589 if (conn->next_messageid == 0) {
590 conn->next_messageid = 1;
592 req->type = msg->type;
593 if (req->messageid == -1) {
597 talloc_set_destructor(req, ldap_request_destructor);
599 msg->messageid = req->messageid;
601 if (!ldap_encode(msg, &req->data, req)) {
602 status = NT_STATUS_INTERNAL_ERROR;
606 status = packet_send(conn->packet, req->data);
607 if (!NT_STATUS_IS_OK(status)) {
611 /* some requests don't expect a reply, so don't add those to the
613 if (req->type == LDAP_TAG_AbandonRequest ||
614 req->type == LDAP_TAG_UnbindRequest) {
615 req->status = NT_STATUS_OK;
616 req->state = LDAP_REQUEST_DONE;
617 /* we can't call the async callback now, as it isn't setup, so
618 call it as next event */
619 event_add_timed(conn->event.event_ctx, req, timeval_zero(),
620 ldap_request_complete, req);
624 req->state = LDAP_REQUEST_PENDING;
625 DLIST_ADD(conn->pending, req);
627 /* put a timeout on the request */
628 req->time_event = event_add_timed(conn->event.event_ctx, req,
629 timeval_current_ofs(conn->timeout, 0),
630 ldap_request_timeout, req);
635 req->status = status;
636 req->state = LDAP_REQUEST_ERROR;
637 event_add_timed(conn->event.event_ctx, req, timeval_zero(),
638 ldap_request_complete, req);
645 wait for a request to complete
646 note that this does not destroy the request
648 NTSTATUS ldap_request_wait(struct ldap_request *req)
650 while (req->state < LDAP_REQUEST_DONE) {
651 if (event_loop_once(req->conn->event.event_ctx) != 0) {
652 req->status = NT_STATUS_UNEXPECTED_NETWORK_ERROR;
661 a mapping of ldap response code to strings
663 static const struct {
664 enum ldap_result_code code;
666 } ldap_code_map[] = {
667 #define _LDAP_MAP_CODE(c) { c, #c }
668 _LDAP_MAP_CODE(LDAP_SUCCESS),
669 _LDAP_MAP_CODE(LDAP_OPERATIONS_ERROR),
670 _LDAP_MAP_CODE(LDAP_PROTOCOL_ERROR),
671 _LDAP_MAP_CODE(LDAP_TIME_LIMIT_EXCEEDED),
672 _LDAP_MAP_CODE(LDAP_SIZE_LIMIT_EXCEEDED),
673 _LDAP_MAP_CODE(LDAP_COMPARE_FALSE),
674 _LDAP_MAP_CODE(LDAP_COMPARE_TRUE),
675 _LDAP_MAP_CODE(LDAP_AUTH_METHOD_NOT_SUPPORTED),
676 _LDAP_MAP_CODE(LDAP_STRONG_AUTH_REQUIRED),
677 _LDAP_MAP_CODE(LDAP_REFERRAL),
678 _LDAP_MAP_CODE(LDAP_ADMIN_LIMIT_EXCEEDED),
679 _LDAP_MAP_CODE(LDAP_UNAVAILABLE_CRITICAL_EXTENSION),
680 _LDAP_MAP_CODE(LDAP_CONFIDENTIALITY_REQUIRED),
681 _LDAP_MAP_CODE(LDAP_SASL_BIND_IN_PROGRESS),
682 _LDAP_MAP_CODE(LDAP_NO_SUCH_ATTRIBUTE),
683 _LDAP_MAP_CODE(LDAP_UNDEFINED_ATTRIBUTE_TYPE),
684 _LDAP_MAP_CODE(LDAP_INAPPROPRIATE_MATCHING),
685 _LDAP_MAP_CODE(LDAP_CONSTRAINT_VIOLATION),
686 _LDAP_MAP_CODE(LDAP_ATTRIBUTE_OR_VALUE_EXISTS),
687 _LDAP_MAP_CODE(LDAP_INVALID_ATTRIBUTE_SYNTAX),
688 _LDAP_MAP_CODE(LDAP_NO_SUCH_OBJECT),
689 _LDAP_MAP_CODE(LDAP_ALIAS_PROBLEM),
690 _LDAP_MAP_CODE(LDAP_INVALID_DN_SYNTAX),
691 _LDAP_MAP_CODE(LDAP_ALIAS_DEREFERENCING_PROBLEM),
692 _LDAP_MAP_CODE(LDAP_INAPPROPRIATE_AUTHENTICATION),
693 _LDAP_MAP_CODE(LDAP_INVALID_CREDENTIALS),
694 _LDAP_MAP_CODE(LDAP_INSUFFICIENT_ACCESS_RIGHTS),
695 _LDAP_MAP_CODE(LDAP_BUSY),
696 _LDAP_MAP_CODE(LDAP_UNAVAILABLE),
697 _LDAP_MAP_CODE(LDAP_UNWILLING_TO_PERFORM),
698 _LDAP_MAP_CODE(LDAP_LOOP_DETECT),
699 _LDAP_MAP_CODE(LDAP_NAMING_VIOLATION),
700 _LDAP_MAP_CODE(LDAP_OBJECT_CLASS_VIOLATION),
701 _LDAP_MAP_CODE(LDAP_NOT_ALLOWED_ON_NON_LEAF),
702 _LDAP_MAP_CODE(LDAP_NOT_ALLOWED_ON_RDN),
703 _LDAP_MAP_CODE(LDAP_ENTRY_ALREADY_EXISTS),
704 _LDAP_MAP_CODE(LDAP_OBJECT_CLASS_MODS_PROHIBITED),
705 _LDAP_MAP_CODE(LDAP_AFFECTS_MULTIPLE_DSAS),
706 _LDAP_MAP_CODE(LDAP_OTHER)
710 used to setup the status code from a ldap response
712 NTSTATUS ldap_check_response(struct ldap_connection *conn, struct ldap_Result *r)
715 const char *codename = "unknown";
717 if (r->resultcode == LDAP_SUCCESS) {
721 if (conn->last_error) {
722 talloc_free(conn->last_error);
725 for (i=0;i<ARRAY_SIZE(ldap_code_map);i++) {
726 if (r->resultcode == ldap_code_map[i].code) {
727 codename = ldap_code_map[i].str;
732 conn->last_error = talloc_asprintf(conn, "LDAP error %u %s - %s <%s> <%s>",
735 r->dn?r->dn:"(NULL)",
736 r->errormessage?r->errormessage:"",
737 r->referral?r->referral:"");
739 return NT_STATUS_LDAP(r->resultcode);
743 return error string representing the last error
745 const char *ldap_errstr(struct ldap_connection *conn,
749 if (NT_STATUS_IS_LDAP(status) && conn->last_error != NULL) {
750 return talloc_strdup(mem_ctx, conn->last_error);
752 return talloc_asprintf(mem_ctx, "LDAP client internal error: %s", nt_errstr(status));
757 return the Nth result message, waiting if necessary
759 NTSTATUS ldap_result_n(struct ldap_request *req, int n, struct ldap_message **msg)
763 NT_STATUS_HAVE_NO_MEMORY(req);
765 while (req->state < LDAP_REQUEST_DONE && n >= req->num_replies) {
766 if (event_loop_once(req->conn->event.event_ctx) != 0) {
767 return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
771 if (n < req->num_replies) {
772 *msg = req->replies[n];
776 if (!NT_STATUS_IS_OK(req->status)) {
780 return NT_STATUS_NO_MORE_ENTRIES;
785 return a single result message, checking if it is of the expected LDAP type
787 NTSTATUS ldap_result_one(struct ldap_request *req, struct ldap_message **msg, int type)
790 status = ldap_result_n(req, 0, msg);
791 if (!NT_STATUS_IS_OK(status)) {
794 if ((*msg)->type != type) {
796 return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
802 a simple ldap transaction, for single result requests that only need a status code
803 this relies on single valued requests having the response type == request type + 1
805 NTSTATUS ldap_transaction(struct ldap_connection *conn, struct ldap_message *msg)
807 struct ldap_request *req = ldap_request_send(conn, msg);
808 struct ldap_message *res;
810 status = ldap_result_n(req, 0, &res);
811 if (!NT_STATUS_IS_OK(status)) {
815 if (res->type != msg->type + 1) {
817 return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);
819 status = ldap_check_response(conn, &res->r.GeneralResult);