r4385: Set the correct target service.
[samba.git] / source4 / libcli / ldap / ldap_client.c
1 /* 
2    Unix SMB/CIFS mplementation.
3    LDAP protocol helper functions for SAMBA
4    
5    Copyright (C) Andrew Tridgell  2004
6    Copyright (C) Volker Lendecke 2004
7    Copyright (C) Stefan Metzmacher 2004
8    Copyright (C) Simo Sorce 2004
9     
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.
14    
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.
19    
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.
23    
24 */
25
26 #include "includes.h"
27 #include "system/network.h"
28 #include "auth/auth.h"
29 #include "asn_1.h"
30 #include "dlinklist.h"
31
32 #if 0
33 static struct ldap_message *new_ldap_search_message(struct ldap_connection *conn,
34                                              const char *base,
35                                              enum ldap_scope scope,
36                                              char *filter,
37                                              int num_attributes,
38                                              const char **attributes)
39 {
40         struct ldap_message *res;
41
42         res = new_ldap_message(conn);
43         if (!res) {
44                 return NULL;
45         }
46
47         res->type = LDAP_TAG_SearchRequest;
48         res->r.SearchRequest.basedn = base;
49         res->r.SearchRequest.scope = scope;
50         res->r.SearchRequest.deref = LDAP_DEREFERENCE_NEVER;
51         res->r.SearchRequest.timelimit = 0;
52         res->r.SearchRequest.sizelimit = 0;
53         res->r.SearchRequest.attributesonly = False;
54         res->r.SearchRequest.filter = filter;
55         res->r.SearchRequest.num_attributes = num_attributes;
56         res->r.SearchRequest.attributes = attributes;
57
58         return res;
59 }
60 #endif
61
62 static struct ldap_message *new_ldap_simple_bind_msg(struct ldap_connection *conn, const char *dn, const char *pw)
63 {
64         struct ldap_message *res;
65
66         res = new_ldap_message(conn);
67         if (!res) {
68                 return NULL;
69         }
70
71         res->type = LDAP_TAG_BindRequest;
72         res->r.BindRequest.version = 3;
73         res->r.BindRequest.dn = talloc_strdup(res->mem_ctx, dn);
74         res->r.BindRequest.mechanism = LDAP_AUTH_MECH_SIMPLE;
75         res->r.BindRequest.creds.password = talloc_strdup(res->mem_ctx, pw);
76
77         return res;
78 }
79
80 static struct ldap_message *new_ldap_sasl_bind_msg(struct ldap_connection *conn, const char *sasl_mechanism, DATA_BLOB *secblob)
81 {
82         struct ldap_message *res;
83
84         res = new_ldap_message(conn);
85         if (!res) {
86                 return NULL;
87         }
88
89         res->type = LDAP_TAG_BindRequest;
90         res->r.BindRequest.version = 3;
91         res->r.BindRequest.dn = "";
92         res->r.BindRequest.mechanism = LDAP_AUTH_MECH_SASL;
93         res->r.BindRequest.creds.SASL.mechanism = talloc_strdup(res->mem_ctx, sasl_mechanism);
94         res->r.BindRequest.creds.SASL.secblob = *secblob;
95
96         return res;
97 }
98
99 static struct ldap_connection *new_ldap_connection(TALLOC_CTX *mem_ctx)
100 {
101         struct ldap_connection *result;
102
103         result = talloc_p(mem_ctx, struct ldap_connection);
104
105         if (!result) {
106                 return NULL;
107         }
108
109         result->mem_ctx = result;
110         result->next_msgid = 1;
111         result->outstanding = NULL;
112         result->searchid = 0;
113         result->search_entries = NULL;
114         result->auth_dn = NULL;
115         result->simple_pw = NULL;
116         result->gensec = NULL;
117
118         return result;
119 }
120
121 struct ldap_connection *ldap_connect(TALLOC_CTX *mem_ctx, const char *url)
122 {
123         struct hostent *hp;
124         struct ipv4_addr ip;
125         struct ldap_connection *conn;
126         BOOL ret;
127
128         conn = new_ldap_connection(mem_ctx);
129         if (!conn) {
130                 return NULL;
131         }
132
133         ret = ldap_parse_basic_url(conn->mem_ctx, url, &conn->host,
134                                   &conn->port, &conn->ldaps);
135         if (!ret) {
136                 talloc_free(conn);
137                 return NULL;
138         }
139
140         hp = sys_gethostbyname(conn->host);
141         if (!hp || !hp->h_addr) {
142                 talloc_free(conn);
143                 return NULL;
144         }
145
146         putip((char *)&ip, (char *)hp->h_addr);
147
148         conn->sock = open_socket_out(SOCK_STREAM, &ip, conn->port, LDAP_CONNECTION_TIMEOUT);
149         if (conn->sock < 0) {
150                 talloc_free(conn);
151                 return NULL;
152         }
153
154         return conn;
155 }
156
157 struct ldap_message *new_ldap_message(TALLOC_CTX *mem_ctx)
158 {
159         struct ldap_message *result;
160
161         result = talloc_p(mem_ctx, struct ldap_message);
162
163         if (!result) {
164                 return NULL;
165         }
166
167         result->mem_ctx = result;
168
169         return result;
170 }
171
172 BOOL ldap_send_msg(struct ldap_connection *conn, struct ldap_message *msg,
173                    const struct timeval *endtime)
174 {
175         DATA_BLOB request;
176         BOOL result;
177         struct ldap_queue_entry *entry;
178
179         msg->messageid = conn->next_msgid++;
180
181         if (!ldap_encode(msg, &request))
182                 return False;
183
184         result = (write_data_until(conn->sock, request.data, request.length,
185                                    endtime) == request.length);
186
187         data_blob_free(&request);
188
189         if (!result)
190                 return result;
191
192         /* abandon and unbind don't expect results */
193
194         if ((msg->type == LDAP_TAG_AbandonRequest) ||
195             (msg->type == LDAP_TAG_UnbindRequest))
196                 return True;
197
198         entry = malloc_p(struct ldap_queue_entry);
199
200         if (entry == NULL)
201                 return False;
202
203         entry->msgid = msg->messageid;
204         entry->msg = NULL;
205         DLIST_ADD(conn->outstanding, entry);
206
207         return True;
208 }
209
210 BOOL ldap_receive_msg(struct ldap_connection *conn, struct ldap_message *msg,
211                       const struct timeval *endtime)
212 {
213         struct asn1_data data;
214         BOOL result;
215
216         if (!asn1_read_sequence_until(conn->sock, &data, endtime))
217                 return False;
218
219         result = ldap_decode(&data, msg);
220
221         asn1_free(&data);
222         return result;
223 }
224
225 static struct ldap_message *recv_from_queue(struct ldap_connection *conn,
226                                             int msgid)
227 {
228         struct ldap_queue_entry *e;
229
230         for (e = conn->outstanding; e != NULL; e = e->next) {
231
232                 if (e->msgid == msgid) {
233                         struct ldap_message *result = e->msg;
234                         DLIST_REMOVE(conn->outstanding, e);
235                         SAFE_FREE(e);
236                         return result;
237                 }
238         }
239
240         return NULL;
241 }
242
243 static void add_search_entry(struct ldap_connection *conn,
244                              struct ldap_message *msg)
245 {
246         struct ldap_queue_entry *e = malloc_p(struct ldap_queue_entry);
247
248         if (e == NULL)
249                 return;
250
251         e->msg = msg;
252         DLIST_ADD_END(conn->search_entries, e, struct ldap_queue_entry *);
253         return;
254 }
255
256 static void fill_outstanding_request(struct ldap_connection *conn,
257                                      struct ldap_message *msg)
258 {
259         struct ldap_queue_entry *e;
260
261         for (e = conn->outstanding; e != NULL; e = e->next) {
262                 if (e->msgid == msg->messageid) {
263                         e->msg = msg;
264                         return;
265                 }
266         }
267
268         /* This reply has not been expected, destroy the incoming msg */
269         talloc_free(msg);
270         return;
271 }
272
273 struct ldap_message *ldap_receive(struct ldap_connection *conn, int msgid,
274                                   const struct timeval *endtime)
275 {
276         struct ldap_message *result = recv_from_queue(conn, msgid);
277
278         if (result != NULL)
279                 return result;
280
281         while (True) {
282                 struct asn1_data data;
283                 BOOL res;
284
285                 result = new_ldap_message(conn);
286
287                 if (!asn1_read_sequence_until(conn->sock, &data, endtime))
288                         return NULL;
289
290                 res = ldap_decode(&data, result);
291                 asn1_free(&data);
292
293                 if (!res)
294                         return NULL;
295
296                 if (result->messageid == msgid)
297                         return result;
298
299                 if (result->type == LDAP_TAG_SearchResultEntry) {
300                         add_search_entry(conn, result);
301                 } else {
302                         fill_outstanding_request(conn, result);
303                 }
304         }
305
306         return NULL;
307 }
308
309 struct ldap_message *ldap_transaction(struct ldap_connection *conn,
310                                       struct ldap_message *request)
311 {
312         if (!ldap_send_msg(conn, request, NULL))
313                 return False;
314
315         return ldap_receive(conn, request->messageid, NULL);
316 }
317
318 int ldap_bind_simple(struct ldap_connection *conn, const char *userdn, const char *password)
319 {
320         struct ldap_message *response;
321         struct ldap_message *msg;
322         const char *dn, *pw;
323         int result = LDAP_OTHER;
324
325         if (conn == NULL)
326                 return result;
327
328         if (userdn) {
329                 dn = userdn;
330         } else {
331                 if (conn->auth_dn) {
332                         dn = conn->auth_dn;
333                 } else {
334                         dn = "";
335                 }
336         }
337
338         if (password) {
339                 pw = password;
340         } else {
341                 if (conn->simple_pw) {
342                         pw = conn->simple_pw;
343                 } else {
344                         pw = "";
345                 }
346         }
347
348         msg =  new_ldap_simple_bind_msg(conn, dn, pw);
349         if (!msg)
350                 return result;
351
352         response = ldap_transaction(conn, msg);
353         if (!response) {
354                 talloc_free(msg);
355                 return result;
356         }
357                 
358         result = response->r.BindResponse.response.resultcode;
359
360         talloc_free(msg);
361         talloc_free(response);
362
363         return result;
364 }
365
366 int ldap_bind_sasl(struct ldap_connection *conn, const char *username, const char *domain, const char *password)
367 {
368         NTSTATUS status;
369         TALLOC_CTX *mem_ctx = NULL;
370         struct ldap_message *response;
371         struct ldap_message *msg;
372         DATA_BLOB input = data_blob(NULL, 0);
373         DATA_BLOB output = data_blob(NULL, 0);
374         int result = LDAP_OTHER;
375
376         if (conn == NULL)
377                 return result;
378
379         status = gensec_client_start(conn, &conn->gensec);
380         if (!NT_STATUS_IS_OK(status)) {
381                 DEBUG(0, ("Failed to start GENSEC engine (%s)\n", nt_errstr(status)));
382                 return result;
383         }
384
385         gensec_want_feature(conn->gensec, GENSEC_FEATURE_SIGN | GENSEC_FEATURE_SEAL);
386
387         status = gensec_set_domain(conn->gensec, domain);
388         if (!NT_STATUS_IS_OK(status)) {
389                 DEBUG(1, ("Failed to start set GENSEC client domain to %s: %s\n", 
390                           domain, nt_errstr(status)));
391                 goto done;
392         }
393
394         status = gensec_set_username(conn->gensec, username);
395         if (!NT_STATUS_IS_OK(status)) {
396                 DEBUG(1, ("Failed to start set GENSEC client username to %s: %s\n", 
397                           username, nt_errstr(status)));
398                 goto done;
399         }
400
401         status = gensec_set_password(conn->gensec, password);
402         if (!NT_STATUS_IS_OK(status)) {
403                 DEBUG(1, ("Failed to start set GENSEC client password: %s\n", 
404                           nt_errstr(status)));
405                 goto done;
406         }
407
408         status = gensec_set_target_hostname(conn->gensec, conn->host);
409         if (!NT_STATUS_IS_OK(status)) {
410                 DEBUG(1, ("Failed to start set GENSEC target hostname: %s\n", 
411                           nt_errstr(status)));
412                 goto done;
413         }
414
415         status = gensec_set_target_service(conn->gensec, "ldap");
416         if (!NT_STATUS_IS_OK(status)) {
417                 DEBUG(1, ("Failed to start set GENSEC target hostname: %s\n", 
418                           nt_errstr(status)));
419                 goto done;
420         }
421
422         status = gensec_start_mech_by_sasl_name(conn->gensec, "GSS-SPNEGO");
423         if (!NT_STATUS_IS_OK(status)) {
424                 DEBUG(1, ("Failed to start set GENSEC client SPNEGO mechanism: %s\n",
425                           nt_errstr(status)));
426                 goto done;
427         }
428
429         mem_ctx = talloc_init("ldap_bind_sasl");
430         if (!mem_ctx)
431                 goto done;
432
433         status = gensec_update(conn->gensec, mem_ctx,
434                                input,
435                                &output);
436
437         while(1) {
438                 if (NT_STATUS_IS_OK(status) && output.length == 0) {
439                         break;
440                 }
441                 if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED) && !NT_STATUS_IS_OK(status)) {
442                         break;
443                 }
444
445                 msg =  new_ldap_sasl_bind_msg(conn, "GSS-SPNEGO", &output);
446                 if (!msg)
447                         goto done;
448
449                 response = ldap_transaction(conn, msg);
450                 talloc_free(msg);
451
452                 if (!response) {
453                         goto done;
454                 }
455
456                 result = response->r.BindResponse.response.resultcode;
457
458                 if (result != LDAP_SUCCESS && result != LDAP_SASL_BIND_IN_PROGRESS) {
459                         break;
460                 }
461
462                 status = gensec_update(conn->gensec, mem_ctx,
463                                        response->r.BindResponse.SASL.secblob,
464                                        &output);
465
466                 talloc_free(response);
467         }
468
469 done:
470         if (mem_ctx)
471                 talloc_destroy(mem_ctx);
472
473         return result;
474 }
475
476 struct ldap_connection *ldap_setup_connection(TALLOC_CTX *mem_ctx, const char *url, 
477                                                 const char *userdn, const char *password)
478 {
479         struct ldap_connection *conn;
480         int result;
481
482         conn =ldap_connect(mem_ctx, url);
483         if (!conn) {
484                 return NULL;
485         }
486
487         result = ldap_bind_simple(conn, userdn, password);
488         if (result != LDAP_SUCCESS) {
489                 talloc_free(conn);
490                 return NULL;
491         }
492
493         return conn;
494 }
495
496 struct ldap_connection *ldap_setup_connection_with_sasl(TALLOC_CTX *mem_ctx, const char *url,
497                                                         const char *username, const char *domain, const char *password)
498 {
499         struct ldap_connection *conn;
500         int result;
501
502         conn =ldap_connect(mem_ctx, url);
503         if (!conn) {
504                 return NULL;
505         }
506
507         result = ldap_bind_sasl(conn, username, domain, password);
508         if (result != LDAP_SUCCESS) {
509                 talloc_free(conn);
510                 return NULL;
511         }
512
513         return conn;
514 }
515
516 BOOL ldap_abandon_message(struct ldap_connection *conn, int msgid,
517                                  const struct timeval *endtime)
518 {
519         struct ldap_message *msg = new_ldap_message(conn);
520         BOOL result;
521
522         if (msg == NULL)
523                 return False;
524
525         msg->type = LDAP_TAG_AbandonRequest;
526         msg->r.AbandonRequest.messageid = msgid;
527
528         result = ldap_send_msg(conn, msg, endtime);
529         talloc_free(msg);
530         return result;
531 }
532
533 BOOL ldap_setsearchent(struct ldap_connection *conn, struct ldap_message *msg,
534                        const struct timeval *endtime)
535 {
536         if ((conn->searchid != 0) &&
537             (!ldap_abandon_message(conn, conn->searchid, endtime)))
538                 return False;
539
540         conn->searchid = conn->next_msgid;
541         return ldap_send_msg(conn, msg, endtime);
542 }
543
544 struct ldap_message *ldap_getsearchent(struct ldap_connection *conn,
545                                        const struct timeval *endtime)
546 {
547         struct ldap_message *result;
548
549         if (conn->search_entries != NULL) {
550                 struct ldap_queue_entry *e = conn->search_entries;
551
552                 result = e->msg;
553                 DLIST_REMOVE(conn->search_entries, e);
554                 SAFE_FREE(e);
555                 return result;
556         }
557
558         result = ldap_receive(conn, conn->searchid, endtime);
559         if (!result) {
560                 return NULL;
561         }
562
563         if (result->type == LDAP_TAG_SearchResultEntry)
564                 return result;
565
566         if (result->type == LDAP_TAG_SearchResultDone) {
567                 /* TODO: Handle Paged Results */
568                 talloc_free(result);
569                 return NULL;
570         }
571
572         /* TODO: Handle Search References here */
573         return NULL;
574 }
575
576 void ldap_endsearchent(struct ldap_connection *conn,
577                        const struct timeval *endtime)
578 {
579         struct ldap_queue_entry *e;
580
581         e = conn->search_entries;
582
583         while (e != NULL) {
584                 struct ldap_queue_entry *next = e->next;
585                 DLIST_REMOVE(conn->search_entries, e);
586                 SAFE_FREE(e);
587                 e = next;
588         }
589 }
590
591 struct ldap_message *ldap_searchone(struct ldap_connection *conn,
592                                     struct ldap_message *msg,
593                                     const struct timeval *endtime)
594 {
595         struct ldap_message *res1, *res2 = NULL;
596         if (!ldap_setsearchent(conn, msg, endtime))
597                 return NULL;
598
599         res1 = ldap_getsearchent(conn, endtime);
600
601         if (res1 != NULL)
602                 res2 = ldap_getsearchent(conn, endtime);
603
604         ldap_endsearchent(conn, endtime);
605
606         if (res1 == NULL)
607                 return NULL;
608
609         if (res2 != NULL) {
610                 /* More than one entry */
611                 talloc_free(res1);
612                 talloc_free(res2);
613                 return NULL;
614         }
615
616         return res1;
617 }
618
619 BOOL ldap_find_single_value(struct ldap_message *msg, const char *attr,
620                             DATA_BLOB *value)
621 {
622         int i;
623         struct ldap_SearchResEntry *r = &msg->r.SearchResultEntry;
624
625         if (msg->type != LDAP_TAG_SearchResultEntry)
626                 return False;
627
628         for (i=0; i<r->num_attributes; i++) {
629                 if (strequal(attr, r->attributes[i].name)) {
630                         if (r->attributes[i].num_values != 1)
631                                 return False;
632
633                         *value = r->attributes[i].values[0];
634                         return True;
635                 }
636         }
637         return False;
638 }
639
640 BOOL ldap_find_single_string(struct ldap_message *msg, const char *attr,
641                              TALLOC_CTX *mem_ctx, char **value)
642 {
643         DATA_BLOB blob;
644
645         if (!ldap_find_single_value(msg, attr, &blob))
646                 return False;
647
648         *value = talloc(mem_ctx, blob.length+1);
649
650         if (*value == NULL)
651                 return False;
652
653         memcpy(*value, blob.data, blob.length);
654         (*value)[blob.length] = '\0';
655         return True;
656 }
657
658 BOOL ldap_find_single_int(struct ldap_message *msg, const char *attr,
659                           int *value)
660 {
661         DATA_BLOB blob;
662         char *val;
663         int errno_save;
664         BOOL res;
665
666         if (!ldap_find_single_value(msg, attr, &blob))
667                 return False;
668
669         val = malloc(blob.length+1);
670         if (val == NULL)
671                 return False;
672
673         memcpy(val, blob.data, blob.length);
674         val[blob.length] = '\0';
675
676         errno_save = errno;
677         errno = 0;
678
679         *value = strtol(val, NULL, 10);
680
681         res = (errno == 0);
682
683         free(val);
684         errno = errno_save;
685
686         return res;
687 }
688
689 int ldap_error(struct ldap_connection *conn)
690 {
691         return 0;
692 }
693
694 NTSTATUS ldap2nterror(int ldaperror)
695 {
696         return NT_STATUS_OK;
697 }