48e9187e7ce43fa7902a7af23cde2f7e39eef711
[metze/samba/wip.git] / source4 / libcli / ldap / ldap_bind.c
1 /* 
2    Unix SMB/CIFS mplementation.
3
4    LDAP bind calls
5    
6    Copyright (C) Andrew Tridgell  2005
7    Copyright (C) Volker Lendecke  2004
8     
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21    
22 */
23
24 #include "includes.h"
25 #include "libcli/ldap/libcli_ldap.h"
26 #include "libcli/ldap/ldap_proto.h"
27 #include "libcli/ldap/ldap_client.h"
28 #include "lib/tls/tls.h"
29 #include "auth/gensec/gensec.h"
30 #include "auth/gensec/gensec_socket.h"
31 #include "auth/credentials/credentials.h"
32 #include "lib/stream/packet.h"
33 #include "param/param.h"
34
35 struct ldap_simple_creds {
36         const char *dn;
37         const char *pw;
38 };
39
40 _PUBLIC_ NTSTATUS ldap_rebind(struct ldap_connection *conn)
41 {
42         NTSTATUS status;
43         struct ldap_simple_creds *creds;
44
45         switch (conn->bind.type) {
46         case LDAP_BIND_SASL:
47                 status = ldap_bind_sasl(conn, (struct cli_credentials *)conn->bind.creds,
48                                         conn->lp_ctx);
49                 break;
50                 
51         case LDAP_BIND_SIMPLE:
52                 creds = (struct ldap_simple_creds *)conn->bind.creds;
53
54                 if (creds == NULL) {
55                         return NT_STATUS_UNSUCCESSFUL;
56                 }
57
58                 status = ldap_bind_simple(conn, creds->dn, creds->pw);
59                 break;
60
61         default:
62                 return NT_STATUS_UNSUCCESSFUL;
63         }
64
65         return status;
66 }
67
68
69 static struct ldap_message *new_ldap_simple_bind_msg(struct ldap_connection *conn, 
70                                                      const char *dn, const char *pw)
71 {
72         struct ldap_message *res;
73
74         res = new_ldap_message(conn);
75         if (!res) {
76                 return NULL;
77         }
78
79         res->type = LDAP_TAG_BindRequest;
80         res->r.BindRequest.version = 3;
81         res->r.BindRequest.dn = talloc_strdup(res, dn);
82         res->r.BindRequest.mechanism = LDAP_AUTH_MECH_SIMPLE;
83         res->r.BindRequest.creds.password = talloc_strdup(res, pw);
84         res->controls = NULL;
85
86         return res;
87 }
88
89
90 /*
91   perform a simple username/password bind
92 */
93 _PUBLIC_ NTSTATUS ldap_bind_simple(struct ldap_connection *conn, 
94                           const char *userdn, const char *password)
95 {
96         struct ldap_request *req;
97         struct ldap_message *msg;
98         const char *dn, *pw;
99         NTSTATUS status;
100
101         if (conn == NULL) {
102                 return NT_STATUS_INVALID_CONNECTION;
103         }
104
105         if (userdn) {
106                 dn = userdn;
107         } else {
108                 if (conn->auth_dn) {
109                         dn = conn->auth_dn;
110                 } else {
111                         dn = "";
112                 }
113         }
114
115         if (password) {
116                 pw = password;
117         } else {
118                 if (conn->simple_pw) {
119                         pw = conn->simple_pw;
120                 } else {
121                         pw = "";
122                 }
123         }
124
125         msg = new_ldap_simple_bind_msg(conn, dn, pw);
126         NT_STATUS_HAVE_NO_MEMORY(msg);
127
128         /* send the request */
129         req = ldap_request_send(conn, msg);
130         talloc_free(msg);
131         NT_STATUS_HAVE_NO_MEMORY(req);
132
133         /* wait for replies */
134         status = ldap_request_wait(req);
135         if (!NT_STATUS_IS_OK(status)) {
136                 talloc_free(req);
137                 return status;
138         }
139
140         /* check its a valid reply */
141         msg = req->replies[0];
142         if (msg->type != LDAP_TAG_BindResponse) {
143                 talloc_free(req);
144                 return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
145         }
146
147         status = ldap_check_response(conn, &msg->r.BindResponse.response);
148
149         talloc_free(req);
150
151         if (NT_STATUS_IS_OK(status)) {
152                 struct ldap_simple_creds *creds = talloc(conn, struct ldap_simple_creds);
153                 if (creds == NULL) {
154                         return NT_STATUS_NO_MEMORY;
155                 }
156                 creds->dn = talloc_strdup(creds, dn);
157                 creds->pw = talloc_strdup(creds, pw);
158                 if (creds->dn == NULL || creds->pw == NULL) {
159                         return NT_STATUS_NO_MEMORY;
160                 }
161                 conn->bind.type = LDAP_BIND_SIMPLE;
162                 conn->bind.creds = creds;
163         }
164
165         return status;
166 }
167
168
169 static struct ldap_message *new_ldap_sasl_bind_msg(struct ldap_connection *conn, 
170                                                    const char *sasl_mechanism, 
171                                                    DATA_BLOB *secblob)
172 {
173         struct ldap_message *res;
174
175         res = new_ldap_message(conn);
176         if (!res) {
177                 return NULL;
178         }
179
180         res->type = LDAP_TAG_BindRequest;
181         res->r.BindRequest.version = 3;
182         res->r.BindRequest.dn = "";
183         res->r.BindRequest.mechanism = LDAP_AUTH_MECH_SASL;
184         res->r.BindRequest.creds.SASL.mechanism = talloc_strdup(res, sasl_mechanism);
185         if (secblob) {
186                 res->r.BindRequest.creds.SASL.secblob = talloc(res, DATA_BLOB);
187                 if (!res->r.BindRequest.creds.SASL.secblob) {
188                         talloc_free(res);
189                         return NULL;
190                 }
191                 *res->r.BindRequest.creds.SASL.secblob = *secblob;
192         } else {
193                 res->r.BindRequest.creds.SASL.secblob = NULL;
194         }
195         res->controls = NULL;
196
197         return res;
198 }
199
200
201 /*
202   perform a sasl bind using the given credentials
203 */
204 _PUBLIC_ NTSTATUS ldap_bind_sasl(struct ldap_connection *conn,
205                         struct cli_credentials *creds,
206                         struct loadparm_context *lp_ctx)
207 {
208         NTSTATUS status;
209         TALLOC_CTX *tmp_ctx = NULL;
210
211         DATA_BLOB input = data_blob(NULL, 0);
212         DATA_BLOB output = data_blob(NULL, 0);
213
214         struct ldap_message **sasl_mechs_msgs;
215         struct ldap_SearchResEntry *search;
216         int count, i;
217
218         const char **sasl_names;
219         uint32_t old_gensec_features;
220         static const char *supported_sasl_mech_attrs[] = {
221                 "supportedSASLMechanisms", 
222                 NULL 
223         };
224         unsigned int logon_retries = 0;
225
226         status = ildap_search(conn, "", LDAP_SEARCH_SCOPE_BASE, "", supported_sasl_mech_attrs,
227                               false, NULL, NULL, &sasl_mechs_msgs);
228         if (!NT_STATUS_IS_OK(status)) {
229                 DEBUG(1, ("Failed to inquire of target's available sasl mechs in rootdse search: %s\n",
230                           nt_errstr(status)));
231                 goto failed;
232         }
233
234         count = ildap_count_entries(conn, sasl_mechs_msgs);
235         if (count != 1) {
236                 DEBUG(1, ("Failed to inquire of target's available sasl mechs in rootdse search: wrong number of replies: %d\n",
237                           count));
238                 goto failed;
239         }
240
241         tmp_ctx = talloc_new(conn);
242         if (tmp_ctx == NULL) goto failed;
243
244         search = &sasl_mechs_msgs[0]->r.SearchResultEntry;
245         if (search->num_attributes != 1) {
246                 DEBUG(1, ("Failed to inquire of target's available sasl mechs in rootdse search: wrong number of attributes: %d != 1\n",
247                           search->num_attributes));
248                 goto failed;
249         }
250
251         sasl_names = talloc_array(tmp_ctx, const char *, search->attributes[0].num_values + 1);
252         if (!sasl_names) {
253                 DEBUG(1, ("talloc_arry(char *, %d) failed\n",
254                           count));
255                 goto failed;
256         }
257
258         for (i=0; i<search->attributes[0].num_values; i++) {
259                 sasl_names[i] = (const char *)search->attributes[0].values[i].data;
260         }
261         sasl_names[i] = NULL;
262
263         gensec_init();
264
265 try_logon_again:
266         /*
267           we loop back here on a logon failure, and re-create the
268           gensec session. The logon_retries counter ensures we don't
269           loop forever.
270          */
271
272         status = gensec_client_start(conn, &conn->gensec,
273                                      lpcfg_gensec_settings(conn, lp_ctx));
274         if (!NT_STATUS_IS_OK(status)) {
275                 DEBUG(0, ("Failed to start GENSEC engine (%s)\n", nt_errstr(status)));
276                 goto failed;
277         }
278
279         /* require Kerberos SIGN/SEAL only if we don't use SSL
280          * Windows seem not to like double encryption */
281         old_gensec_features = cli_credentials_get_gensec_features(creds);
282         if (tls_enabled(conn->sock)) {
283                 cli_credentials_set_gensec_features(creds, old_gensec_features & ~(GENSEC_FEATURE_SIGN|GENSEC_FEATURE_SEAL));
284         }
285
286         cli_credentials_set_gensec_features(creds, old_gensec_features | GENSEC_FEATURE_SIGN|GENSEC_FEATURE_SEAL);
287         /* this call also sets the gensec_want_features */
288         status = gensec_set_credentials(conn->gensec, creds);
289         if (!NT_STATUS_IS_OK(status)) {
290                 DEBUG(1, ("Failed to set GENSEC creds: %s\n", 
291                           nt_errstr(status)));
292                 goto failed;
293         }
294
295         /* reset the original gensec_features (on the credentials
296          * context, so we don't tatoo it ) */
297         cli_credentials_set_gensec_features(creds, old_gensec_features);
298
299         if (conn->host) {
300                 status = gensec_set_target_hostname(conn->gensec, conn->host);
301                 if (!NT_STATUS_IS_OK(status)) {
302                         DEBUG(1, ("Failed to set GENSEC target hostname: %s\n", 
303                                   nt_errstr(status)));
304                         goto failed;
305                 }
306         }
307
308         status = gensec_set_target_service(conn->gensec, "ldap");
309         if (!NT_STATUS_IS_OK(status)) {
310                 DEBUG(1, ("Failed to set GENSEC target service: %s\n", 
311                           nt_errstr(status)));
312                 goto failed;
313         }
314
315         status = gensec_start_mech_by_sasl_list(conn->gensec, sasl_names);
316         if (!NT_STATUS_IS_OK(status)) {
317                 DEBUG(1, ("None of the %d proposed SASL mechs were acceptable: %s\n",
318                           count, nt_errstr(status)));
319                 goto failed;
320         }
321
322         while (1) {
323                 NTSTATUS gensec_status;
324                 struct ldap_message *response;
325                 struct ldap_message *msg;
326                 struct ldap_request *req;
327                 int result = LDAP_OTHER;
328         
329                 status = gensec_update(conn->gensec, tmp_ctx,
330                                        conn->event.event_ctx,
331                                        input,
332                                        &output);
333                 /* The status value here, from GENSEC is vital to the security
334                  * of the system.  Even if the other end accepts, if GENSEC
335                  * claims 'MORE_PROCESSING_REQUIRED' then you must keep
336                  * feeding it blobs, or else the remote host/attacker might
337                  * avoid mutal authentication requirements.
338                  *
339                  * Likewise, you must not feed GENSEC too much (after the OK),
340                  * it doesn't like that either
341                  */
342
343                 gensec_status = status;
344
345                 if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED) && 
346                     !NT_STATUS_IS_OK(status)) {
347                         break;
348                 }
349                 if (NT_STATUS_IS_OK(status) && output.length == 0) {
350                         break;
351                 }
352
353                 /* Perhaps we should make gensec_start_mech_by_sasl_list() return the name we got? */
354                 msg = new_ldap_sasl_bind_msg(tmp_ctx, conn->gensec->ops->sasl_name, (output.data?&output:NULL));
355                 if (msg == NULL) {
356                         status = NT_STATUS_NO_MEMORY;
357                         goto failed;
358                 }
359
360                 req = ldap_request_send(conn, msg);
361                 if (req == NULL) {
362                         status = NT_STATUS_NO_MEMORY;
363                         goto failed;
364                 }
365                 talloc_reparent(conn, tmp_ctx, req);
366
367                 status = ldap_result_n(req, 0, &response);
368                 if (!NT_STATUS_IS_OK(status)) {
369                         goto failed;
370                 }
371                 
372                 if (response->type != LDAP_TAG_BindResponse) {
373                         status = NT_STATUS_UNEXPECTED_NETWORK_ERROR;
374                         goto failed;
375                 }
376
377                 result = response->r.BindResponse.response.resultcode;
378
379                 if (result == LDAP_INVALID_CREDENTIALS) {
380                         /*
381                           try a second time on invalid credentials, to
382                           give the user a chance to re-enter the
383                           password and to handle the case where our
384                           kerberos ticket is invalid as the server
385                           password has changed
386                         */
387                         const char *principal;
388
389                         principal = gensec_get_target_principal(conn->gensec);
390                         if (principal == NULL) {
391                                 const char *hostname = gensec_get_target_hostname(conn->gensec);
392                                 const char *service  = gensec_get_target_service(conn->gensec);
393                                 if (hostname != NULL && service != NULL) {
394                                         principal = talloc_asprintf(tmp_ctx, "%s/%s", service, hostname);
395                                 }
396                         }
397
398                         if (cli_credentials_failed_kerberos_login(creds, principal, &logon_retries) ||
399                             cli_credentials_wrong_password(creds)) {
400                                 /*
401                                   destroy our gensec session and loop
402                                   back up to the top to retry,
403                                   offering the user a chance to enter
404                                   new credentials, or get a new ticket
405                                   if using kerberos
406                                  */
407                                 talloc_free(conn->gensec);
408                                 conn->gensec = NULL;
409                                 goto try_logon_again;
410                         }
411                 }
412
413                 if (result != LDAP_SUCCESS && result != LDAP_SASL_BIND_IN_PROGRESS) {
414                         status = ldap_check_response(conn, 
415                                                      &response->r.BindResponse.response);
416                         break;
417                 }
418
419                 /* This is where we check if GENSEC wanted to be fed more data */
420                 if (!NT_STATUS_EQUAL(gensec_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
421                         break;
422                 }
423                 if (response->r.BindResponse.SASL.secblob) {
424                         input = *response->r.BindResponse.SASL.secblob;
425                 } else {
426                         input = data_blob(NULL, 0);
427                 }
428         }
429
430         talloc_free(tmp_ctx);
431
432         if (NT_STATUS_IS_OK(status)) {
433                 struct socket_context *sasl_socket;
434                 status = gensec_socket_init(conn->gensec, 
435                                             conn,
436                                             conn->sock,
437                                             conn->event.event_ctx, 
438                                             ldap_read_io_handler,
439                                             conn,
440                                             &sasl_socket);
441                 if (!NT_STATUS_IS_OK(status)) goto failed;
442
443                 conn->sock = sasl_socket;
444                 packet_set_socket(conn->packet, conn->sock);
445
446                 conn->bind.type = LDAP_BIND_SASL;
447                 conn->bind.creds = creds;
448         }
449
450         return status;
451
452 failed:
453         talloc_free(tmp_ctx);
454         talloc_free(conn->gensec);
455         conn->gensec = NULL;
456         return status;
457 }