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.
27 #include "system/network.h"
28 #include "system/filesys.h"
29 #include "auth/auth.h"
31 #include "dlinklist.h"
32 #include "libcli/ldap/ldap.h"
36 /****************************************************************************
38 ****************************************************************************/
39 static BOOL timeout_until(struct timeval *timeout,
40 const struct timeval *endtime)
46 if ((now.tv_sec > endtime->tv_sec) ||
47 ((now.tv_sec == endtime->tv_sec) &&
48 (now.tv_usec > endtime->tv_usec)))
51 timeout->tv_sec = endtime->tv_sec - now.tv_sec;
52 timeout->tv_usec = endtime->tv_usec - now.tv_usec;
57 /****************************************************************************
58 Read data from the client, reading exactly N bytes, with timeout.
59 ****************************************************************************/
60 static ssize_t read_data_until(int fd,char *buffer,size_t N,
61 const struct timeval *endtime)
68 if (endtime != NULL) {
70 struct timeval timeout;
76 if (!timeout_until(&timeout, endtime))
79 res = sys_select(fd+1, &r_fds, NULL, NULL, &timeout);
84 ret = sys_read(fd,buffer + total,N - total);
87 DEBUG(10,("read_data: read of %d returned 0. Error = %s\n", (int)(N - total), strerror(errno) ));
92 DEBUG(0,("read_data: read failure for %d. Error = %s\n", (int)(N - total), strerror(errno) ));
97 return (ssize_t)total;
101 /****************************************************************************
102 Write data to a fd with timeout.
103 ****************************************************************************/
104 static ssize_t write_data_until(int fd,char *buffer,size_t N,
105 const struct timeval *endtime)
112 if (endtime != NULL) {
114 struct timeval timeout;
120 if (!timeout_until(&timeout, endtime))
123 res = sys_select(fd+1, NULL, &w_fds, NULL, &timeout);
128 ret = sys_write(fd,buffer + total,N - total);
131 DEBUG(0,("write_data: write failure. Error = %s\n", strerror(errno) ));
139 return (ssize_t)total;
144 static BOOL read_one_uint8(int sock, uint8_t *result, struct asn1_data *data,
145 const struct timeval *endtime)
147 if (read_data_until(sock, result, 1, endtime) != 1)
150 return asn1_write(data, result, 1);
153 /* Read a complete ASN sequence (ie LDAP result) from a socket */
154 static BOOL asn1_read_sequence_until(int sock, struct asn1_data *data,
155 const struct timeval *endtime)
163 if (!read_one_uint8(sock, &b, data, endtime))
167 data->has_error = True;
171 if (!read_one_uint8(sock, &b, data, endtime))
176 if (!read_one_uint8(sock, &b, data, endtime))
180 if (!read_one_uint8(sock, &b, data, endtime))
189 buf = talloc_size(NULL, len);
193 if (read_data_until(sock, buf, len, endtime) != len)
196 if (!asn1_write(data, buf, len))
208 /****************************************************************************
209 create an outgoing socket. timeout is in milliseconds.
210 **************************************************************************/
211 static int open_socket_out(int type, struct ipv4_addr *addr, int port, int timeout)
213 struct sockaddr_in sock_out;
215 int connect_loop = 250; /* 250 milliseconds */
216 int loops = (timeout) / connect_loop;
218 /* create a socket to write to */
219 res = socket(PF_INET, type, 0);
221 { DEBUG(0,("socket error\n")); return -1; }
223 if (type != SOCK_STREAM) return(res);
225 memset((char *)&sock_out,'\0',sizeof(sock_out));
226 putip((char *)&sock_out.sin_addr,(char *)addr);
228 sock_out.sin_port = htons( port );
229 sock_out.sin_family = PF_INET;
231 /* set it non-blocking */
232 set_blocking(res,False);
234 DEBUG(3,("Connecting to %s at port %d\n", sys_inet_ntoa(*addr),port));
236 /* and connect it to the destination */
238 ret = connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out));
240 /* Some systems return EAGAIN when they mean EINPROGRESS */
241 if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
242 errno == EAGAIN) && loops--) {
243 msleep(connect_loop);
247 if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
249 DEBUG(1,("timeout connecting to %s:%d\n", sys_inet_ntoa(*addr),port));
255 if (ret < 0 && errno == EISCONN) {
262 DEBUG(2,("error connecting to %s:%d (%s)\n",
263 sys_inet_ntoa(*addr),port,strerror(errno)));
268 /* set it blocking again */
269 set_blocking(res,True);
275 static struct ldap_message *new_ldap_search_message(struct ldap_connection *conn,
277 enum ldap_scope scope,
280 const char **attributes)
282 struct ldap_message *res;
284 res = new_ldap_message(conn);
289 res->type = LDAP_TAG_SearchRequest;
290 res->r.SearchRequest.basedn = base;
291 res->r.SearchRequest.scope = scope;
292 res->r.SearchRequest.deref = LDAP_DEREFERENCE_NEVER;
293 res->r.SearchRequest.timelimit = 0;
294 res->r.SearchRequest.sizelimit = 0;
295 res->r.SearchRequest.attributesonly = False;
296 res->r.SearchRequest.filter = filter;
297 res->r.SearchRequest.num_attributes = num_attributes;
298 res->r.SearchRequest.attributes = attributes;
304 static struct ldap_message *new_ldap_simple_bind_msg(struct ldap_connection *conn, const char *dn, const char *pw)
306 struct ldap_message *res;
308 res = new_ldap_message(conn);
313 res->type = LDAP_TAG_BindRequest;
314 res->r.BindRequest.version = 3;
315 res->r.BindRequest.dn = talloc_strdup(res->mem_ctx, dn);
316 res->r.BindRequest.mechanism = LDAP_AUTH_MECH_SIMPLE;
317 res->r.BindRequest.creds.password = talloc_strdup(res->mem_ctx, pw);
322 static struct ldap_message *new_ldap_sasl_bind_msg(struct ldap_connection *conn, const char *sasl_mechanism, DATA_BLOB *secblob)
324 struct ldap_message *res;
326 res = new_ldap_message(conn);
331 res->type = LDAP_TAG_BindRequest;
332 res->r.BindRequest.version = 3;
333 res->r.BindRequest.dn = "";
334 res->r.BindRequest.mechanism = LDAP_AUTH_MECH_SASL;
335 res->r.BindRequest.creds.SASL.mechanism = talloc_strdup(res->mem_ctx, sasl_mechanism);
336 res->r.BindRequest.creds.SASL.secblob = *secblob;
341 static struct ldap_connection *new_ldap_connection(TALLOC_CTX *mem_ctx)
343 struct ldap_connection *result;
345 result = talloc(mem_ctx, struct ldap_connection);
351 result->mem_ctx = result;
352 result->next_msgid = 1;
353 result->outstanding = NULL;
354 result->searchid = 0;
355 result->search_entries = NULL;
356 result->auth_dn = NULL;
357 result->simple_pw = NULL;
358 result->gensec = NULL;
363 struct ldap_connection *ldap_connect(TALLOC_CTX *mem_ctx, const char *url)
367 struct ldap_connection *conn;
370 conn = new_ldap_connection(mem_ctx);
375 ret = ldap_parse_basic_url(conn->mem_ctx, url, &conn->host,
376 &conn->port, &conn->ldaps);
382 hp = sys_gethostbyname(conn->host);
383 if (!hp || !hp->h_addr) {
388 putip((char *)&ip, (char *)hp->h_addr);
390 conn->sock = open_socket_out(SOCK_STREAM, &ip, conn->port, LDAP_CONNECTION_TIMEOUT);
391 if (conn->sock < 0) {
399 struct ldap_message *new_ldap_message(TALLOC_CTX *mem_ctx)
401 struct ldap_message *result;
403 result = talloc(mem_ctx, struct ldap_message);
409 result->mem_ctx = result;
414 BOOL ldap_send_msg(struct ldap_connection *conn, struct ldap_message *msg,
415 const struct timeval *endtime)
419 struct ldap_queue_entry *entry;
421 msg->messageid = conn->next_msgid++;
423 if (!ldap_encode(msg, &request))
426 result = (write_data_until(conn->sock, request.data, request.length,
427 endtime) == request.length);
429 data_blob_free(&request);
434 /* abandon and unbind don't expect results */
436 if ((msg->type == LDAP_TAG_AbandonRequest) ||
437 (msg->type == LDAP_TAG_UnbindRequest))
440 entry = malloc_p(struct ldap_queue_entry);
445 entry->msgid = msg->messageid;
447 DLIST_ADD(conn->outstanding, entry);
452 BOOL ldap_receive_msg(struct ldap_connection *conn, struct ldap_message *msg,
453 const struct timeval *endtime)
455 struct asn1_data data;
458 if (!asn1_read_sequence_until(conn->sock, &data, endtime))
461 result = ldap_decode(&data, msg);
467 static struct ldap_message *recv_from_queue(struct ldap_connection *conn,
470 struct ldap_queue_entry *e;
472 for (e = conn->outstanding; e != NULL; e = e->next) {
474 if (e->msgid == msgid) {
475 struct ldap_message *result = e->msg;
476 DLIST_REMOVE(conn->outstanding, e);
485 static void add_search_entry(struct ldap_connection *conn,
486 struct ldap_message *msg)
488 struct ldap_queue_entry *e = malloc_p(struct ldap_queue_entry);
494 DLIST_ADD_END(conn->search_entries, e, struct ldap_queue_entry *);
498 static void fill_outstanding_request(struct ldap_connection *conn,
499 struct ldap_message *msg)
501 struct ldap_queue_entry *e;
503 for (e = conn->outstanding; e != NULL; e = e->next) {
504 if (e->msgid == msg->messageid) {
510 /* This reply has not been expected, destroy the incoming msg */
515 struct ldap_message *ldap_receive(struct ldap_connection *conn, int msgid,
516 const struct timeval *endtime)
518 struct ldap_message *result = recv_from_queue(conn, msgid);
524 struct asn1_data data;
527 result = new_ldap_message(conn);
529 if (!asn1_read_sequence_until(conn->sock, &data, endtime))
532 res = ldap_decode(&data, result);
538 if (result->messageid == msgid)
541 if (result->type == LDAP_TAG_SearchResultEntry) {
542 add_search_entry(conn, result);
544 fill_outstanding_request(conn, result);
551 struct ldap_message *ldap_transaction(struct ldap_connection *conn,
552 struct ldap_message *request)
554 if (!ldap_send_msg(conn, request, NULL))
557 return ldap_receive(conn, request->messageid, NULL);
560 int ldap_bind_simple(struct ldap_connection *conn, const char *userdn, const char *password)
562 struct ldap_message *response;
563 struct ldap_message *msg;
565 int result = LDAP_OTHER;
583 if (conn->simple_pw) {
584 pw = conn->simple_pw;
590 msg = new_ldap_simple_bind_msg(conn, dn, pw);
594 response = ldap_transaction(conn, msg);
600 result = response->r.BindResponse.response.resultcode;
603 talloc_free(response);
608 int ldap_bind_sasl(struct ldap_connection *conn, const char *username, const char *domain, const char *password)
611 TALLOC_CTX *mem_ctx = NULL;
612 struct ldap_message *response;
613 struct ldap_message *msg;
614 DATA_BLOB input = data_blob(NULL, 0);
615 DATA_BLOB output = data_blob(NULL, 0);
616 int result = LDAP_OTHER;
621 status = gensec_client_start(conn, &conn->gensec);
622 if (!NT_STATUS_IS_OK(status)) {
623 DEBUG(0, ("Failed to start GENSEC engine (%s)\n", nt_errstr(status)));
627 gensec_want_feature(conn->gensec, GENSEC_FEATURE_SIGN | GENSEC_FEATURE_SEAL);
629 status = gensec_set_domain(conn->gensec, domain);
630 if (!NT_STATUS_IS_OK(status)) {
631 DEBUG(1, ("Failed to start set GENSEC client domain to %s: %s\n",
632 domain, nt_errstr(status)));
636 status = gensec_set_username(conn->gensec, username);
637 if (!NT_STATUS_IS_OK(status)) {
638 DEBUG(1, ("Failed to start set GENSEC client username to %s: %s\n",
639 username, nt_errstr(status)));
643 status = gensec_set_password(conn->gensec, password);
644 if (!NT_STATUS_IS_OK(status)) {
645 DEBUG(1, ("Failed to start set GENSEC client password: %s\n",
650 status = gensec_set_target_hostname(conn->gensec, conn->host);
651 if (!NT_STATUS_IS_OK(status)) {
652 DEBUG(1, ("Failed to start set GENSEC target hostname: %s\n",
657 status = gensec_set_target_service(conn->gensec, "ldap");
658 if (!NT_STATUS_IS_OK(status)) {
659 DEBUG(1, ("Failed to start set GENSEC target service: %s\n",
664 status = gensec_start_mech_by_sasl_name(conn->gensec, "GSS-SPNEGO");
665 if (!NT_STATUS_IS_OK(status)) {
666 DEBUG(1, ("Failed to start set GENSEC client SPNEGO mechanism: %s\n",
671 mem_ctx = talloc_init("ldap_bind_sasl");
675 status = gensec_update(conn->gensec, mem_ctx,
680 if (NT_STATUS_IS_OK(status) && output.length == 0) {
683 if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED) && !NT_STATUS_IS_OK(status)) {
687 msg = new_ldap_sasl_bind_msg(conn, "GSS-SPNEGO", &output);
691 response = ldap_transaction(conn, msg);
698 result = response->r.BindResponse.response.resultcode;
700 if (result != LDAP_SUCCESS && result != LDAP_SASL_BIND_IN_PROGRESS) {
704 if (!NT_STATUS_IS_OK(status)) {
705 status = gensec_update(conn->gensec, mem_ctx,
706 response->r.BindResponse.SASL.secblob,
712 talloc_free(response);
717 talloc_free(mem_ctx);
722 struct ldap_connection *ldap_setup_connection(TALLOC_CTX *mem_ctx, const char *url,
723 const char *userdn, const char *password)
725 struct ldap_connection *conn;
728 conn =ldap_connect(mem_ctx, url);
733 result = ldap_bind_simple(conn, userdn, password);
734 if (result != LDAP_SUCCESS) {
742 struct ldap_connection *ldap_setup_connection_with_sasl(TALLOC_CTX *mem_ctx, const char *url,
743 const char *username, const char *domain, const char *password)
745 struct ldap_connection *conn;
748 conn =ldap_connect(mem_ctx, url);
753 result = ldap_bind_sasl(conn, username, domain, password);
754 if (result != LDAP_SUCCESS) {
762 BOOL ldap_abandon_message(struct ldap_connection *conn, int msgid,
763 const struct timeval *endtime)
765 struct ldap_message *msg = new_ldap_message(conn);
771 msg->type = LDAP_TAG_AbandonRequest;
772 msg->r.AbandonRequest.messageid = msgid;
774 result = ldap_send_msg(conn, msg, endtime);
779 BOOL ldap_setsearchent(struct ldap_connection *conn, struct ldap_message *msg,
780 const struct timeval *endtime)
782 if ((conn->searchid != 0) &&
783 (!ldap_abandon_message(conn, conn->searchid, endtime)))
786 conn->searchid = conn->next_msgid;
787 return ldap_send_msg(conn, msg, endtime);
790 struct ldap_message *ldap_getsearchent(struct ldap_connection *conn,
791 const struct timeval *endtime)
793 struct ldap_message *result;
795 if (conn->search_entries != NULL) {
796 struct ldap_queue_entry *e = conn->search_entries;
799 DLIST_REMOVE(conn->search_entries, e);
804 result = ldap_receive(conn, conn->searchid, endtime);
809 if (result->type == LDAP_TAG_SearchResultEntry)
812 if (result->type == LDAP_TAG_SearchResultDone) {
813 /* TODO: Handle Paged Results */
818 /* TODO: Handle Search References here */
822 void ldap_endsearchent(struct ldap_connection *conn,
823 const struct timeval *endtime)
825 struct ldap_queue_entry *e;
827 e = conn->search_entries;
830 struct ldap_queue_entry *next = e->next;
831 DLIST_REMOVE(conn->search_entries, e);
837 struct ldap_message *ldap_searchone(struct ldap_connection *conn,
838 struct ldap_message *msg,
839 const struct timeval *endtime)
841 struct ldap_message *res1, *res2 = NULL;
842 if (!ldap_setsearchent(conn, msg, endtime))
845 res1 = ldap_getsearchent(conn, endtime);
848 res2 = ldap_getsearchent(conn, endtime);
850 ldap_endsearchent(conn, endtime);
856 /* More than one entry */
865 BOOL ldap_find_single_value(struct ldap_message *msg, const char *attr,
869 struct ldap_SearchResEntry *r = &msg->r.SearchResultEntry;
871 if (msg->type != LDAP_TAG_SearchResultEntry)
874 for (i=0; i<r->num_attributes; i++) {
875 if (strequal(attr, r->attributes[i].name)) {
876 if (r->attributes[i].num_values != 1)
879 *value = r->attributes[i].values[0];
886 BOOL ldap_find_single_string(struct ldap_message *msg, const char *attr,
887 TALLOC_CTX *mem_ctx, char **value)
891 if (!ldap_find_single_value(msg, attr, &blob))
894 *value = talloc_size(mem_ctx, blob.length+1);
899 memcpy(*value, blob.data, blob.length);
900 (*value)[blob.length] = '\0';
904 BOOL ldap_find_single_int(struct ldap_message *msg, const char *attr,
912 if (!ldap_find_single_value(msg, attr, &blob))
915 val = malloc(blob.length+1);
919 memcpy(val, blob.data, blob.length);
920 val[blob.length] = '\0';
925 *value = strtol(val, NULL, 10);
935 int ldap_error(struct ldap_connection *conn)
940 NTSTATUS ldap2nterror(int ldaperror)