db8de4e0ed4fe91cbbdc2e10545d0fd83f6cd123
[samba.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_internal.h" /* TODO: remove this */
31 #include "source4/auth/gensec/gensec_tstream.h"
32 #include "auth/credentials/credentials.h"
33 #include "lib/stream/packet.h"
34 #include "param/param.h"
35 #include "param/loadparm.h"
36
37 struct ldap_simple_creds {
38         const char *dn;
39         const char *pw;
40 };
41
42 _PUBLIC_ NTSTATUS ldap_rebind(struct ldap_connection *conn)
43 {
44         NTSTATUS status;
45         struct ldap_simple_creds *creds;
46
47         switch (conn->bind.type) {
48         case LDAP_BIND_SASL:
49                 status = ldap_bind_sasl(conn, (struct cli_credentials *)conn->bind.creds,
50                                         conn->lp_ctx);
51                 break;
52                 
53         case LDAP_BIND_SIMPLE:
54                 creds = (struct ldap_simple_creds *)conn->bind.creds;
55
56                 if (creds == NULL) {
57                         return NT_STATUS_UNSUCCESSFUL;
58                 }
59
60                 status = ldap_bind_simple(conn, creds->dn, creds->pw);
61                 break;
62
63         default:
64                 return NT_STATUS_UNSUCCESSFUL;
65         }
66
67         return status;
68 }
69
70
71 static struct ldap_message *new_ldap_simple_bind_msg(struct ldap_connection *conn, 
72                                                      const char *dn, const char *pw)
73 {
74         struct ldap_message *res;
75
76         res = new_ldap_message(conn);
77         if (!res) {
78                 return NULL;
79         }
80
81         res->type = LDAP_TAG_BindRequest;
82         res->r.BindRequest.version = 3;
83         res->r.BindRequest.dn = talloc_strdup(res, dn);
84         res->r.BindRequest.mechanism = LDAP_AUTH_MECH_SIMPLE;
85         res->r.BindRequest.creds.password = talloc_strdup(res, pw);
86         res->controls = NULL;
87
88         return res;
89 }
90
91
92 /*
93   perform a simple username/password bind
94 */
95 _PUBLIC_ NTSTATUS ldap_bind_simple(struct ldap_connection *conn, 
96                           const char *userdn, const char *password)
97 {
98         struct ldap_request *req;
99         struct ldap_message *msg;
100         const char *dn, *pw;
101         NTSTATUS status;
102
103         if (conn == NULL) {
104                 return NT_STATUS_INVALID_CONNECTION;
105         }
106
107         if (userdn) {
108                 dn = userdn;
109         } else {
110                 if (conn->auth_dn) {
111                         dn = conn->auth_dn;
112                 } else {
113                         dn = "";
114                 }
115         }
116
117         if (password) {
118                 pw = password;
119         } else {
120                 if (conn->simple_pw) {
121                         pw = conn->simple_pw;
122                 } else {
123                         pw = "";
124                 }
125         }
126
127         msg = new_ldap_simple_bind_msg(conn, dn, pw);
128         NT_STATUS_HAVE_NO_MEMORY(msg);
129
130         /* send the request */
131         req = ldap_request_send(conn, msg);
132         talloc_free(msg);
133         NT_STATUS_HAVE_NO_MEMORY(req);
134
135         /* wait for replies */
136         status = ldap_request_wait(req);
137         if (!NT_STATUS_IS_OK(status)) {
138                 talloc_free(req);
139                 return status;
140         }
141
142         /* check its a valid reply */
143         msg = req->replies[0];
144         if (msg->type != LDAP_TAG_BindResponse) {
145                 talloc_free(req);
146                 return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
147         }
148
149         status = ldap_check_response(conn, &msg->r.BindResponse.response);
150
151         talloc_free(req);
152
153         if (NT_STATUS_IS_OK(status)) {
154                 struct ldap_simple_creds *creds = talloc(conn, struct ldap_simple_creds);
155                 if (creds == NULL) {
156                         return NT_STATUS_NO_MEMORY;
157                 }
158                 creds->dn = talloc_strdup(creds, dn);
159                 creds->pw = talloc_strdup(creds, pw);
160                 if (creds->dn == NULL || creds->pw == NULL) {
161                         return NT_STATUS_NO_MEMORY;
162                 }
163                 conn->bind.type = LDAP_BIND_SIMPLE;
164                 conn->bind.creds = creds;
165         }
166
167         return status;
168 }
169
170
171 static struct ldap_message *new_ldap_sasl_bind_msg(struct ldap_connection *conn, 
172                                                    const char *sasl_mechanism, 
173                                                    DATA_BLOB *secblob)
174 {
175         struct ldap_message *res;
176
177         res = new_ldap_message(conn);
178         if (!res) {
179                 return NULL;
180         }
181
182         res->type = LDAP_TAG_BindRequest;
183         res->r.BindRequest.version = 3;
184         res->r.BindRequest.dn = "";
185         res->r.BindRequest.mechanism = LDAP_AUTH_MECH_SASL;
186         res->r.BindRequest.creds.SASL.mechanism = talloc_strdup(res, sasl_mechanism);
187         if (secblob) {
188                 res->r.BindRequest.creds.SASL.secblob = talloc(res, DATA_BLOB);
189                 if (!res->r.BindRequest.creds.SASL.secblob) {
190                         talloc_free(res);
191                         return NULL;
192                 }
193                 *res->r.BindRequest.creds.SASL.secblob = *secblob;
194         } else {
195                 res->r.BindRequest.creds.SASL.secblob = NULL;
196         }
197         res->controls = NULL;
198
199         return res;
200 }
201
202
203 /*
204   perform a sasl bind using the given credentials
205 */
206 _PUBLIC_ NTSTATUS ldap_bind_sasl(struct ldap_connection *conn,
207                         struct cli_credentials *creds,
208                         struct loadparm_context *lp_ctx)
209 {
210         NTSTATUS status;
211         TALLOC_CTX *tmp_ctx = NULL;
212
213         DATA_BLOB input = data_blob(NULL, 0);
214         DATA_BLOB output = data_blob(NULL, 0);
215
216         struct ldap_message **sasl_mechs_msgs;
217         struct ldap_SearchResEntry *search;
218         int count, i;
219         bool first = true;
220         int wrap_flags = 0;
221         const char **sasl_names;
222         uint32_t old_gensec_features;
223         static const char *supported_sasl_mech_attrs[] = {
224                 "supportedSASLMechanisms", 
225                 NULL 
226         };
227         unsigned int logon_retries = 0;
228         size_t queue_length;
229
230         if (conn->sockets.active == NULL) {
231                 status = NT_STATUS_CONNECTION_DISCONNECTED;
232                 goto failed;
233         }
234
235         queue_length = tevent_queue_length(conn->sockets.send_queue);
236         if (queue_length != 0) {
237                 status = NT_STATUS_INVALID_PARAMETER_MIX;
238                 DEBUG(1, ("SASL bind triggered with non empty send_queue[%zu]: %s\n",
239                           queue_length, nt_errstr(status)));
240                 goto failed;
241         }
242
243         if (conn->pending != NULL) {
244                 status = NT_STATUS_INVALID_PARAMETER_MIX;
245                 DEBUG(1, ("SASL bind triggered with pending requests: %s\n",
246                           nt_errstr(status)));
247                 goto failed;
248         }
249
250         status = ildap_search(conn, "", LDAP_SEARCH_SCOPE_BASE, "", supported_sasl_mech_attrs,
251                               false, NULL, NULL, &sasl_mechs_msgs);
252         if (!NT_STATUS_IS_OK(status)) {
253                 DEBUG(1, ("Failed to inquire of target's available sasl mechs in rootdse search: %s\n",
254                           nt_errstr(status)));
255                 goto failed;
256         }
257
258         count = ildap_count_entries(conn, sasl_mechs_msgs);
259         if (count != 1) {
260                 DEBUG(1, ("Failed to inquire of target's available sasl mechs in rootdse search: wrong number of replies: %d\n",
261                           count));
262                 goto failed;
263         }
264
265         tmp_ctx = talloc_new(conn);
266         if (tmp_ctx == NULL) goto failed;
267
268         search = &sasl_mechs_msgs[0]->r.SearchResultEntry;
269         if (search->num_attributes != 1) {
270                 DEBUG(1, ("Failed to inquire of target's available sasl mechs in rootdse search: wrong number of attributes: %d != 1\n",
271                           search->num_attributes));
272                 goto failed;
273         }
274
275         sasl_names = talloc_array(tmp_ctx, const char *, search->attributes[0].num_values + 1);
276         if (!sasl_names) {
277                 DEBUG(1, ("talloc_arry(char *, %d) failed\n",
278                           count));
279                 goto failed;
280         }
281
282         for (i=0; i<search->attributes[0].num_values; i++) {
283                 sasl_names[i] = (const char *)search->attributes[0].values[i].data;
284         }
285         sasl_names[i] = NULL;
286
287         gensec_init();
288
289         if (conn->sockets.active == conn->sockets.tls) {
290                 /*
291                  * require Kerberos SIGN/SEAL only if we don't use SSL
292                  * Windows seem not to like double encryption
293                  */
294                 wrap_flags = 0;
295         } else if (cli_credentials_is_anonymous(creds)) {
296                 /*
297                  * anonymous isn't protected
298                  */
299                 wrap_flags = 0;
300         } else {
301                 wrap_flags = lpcfg_client_ldap_sasl_wrapping(lp_ctx);
302         }
303
304 try_logon_again:
305         /*
306           we loop back here on a logon failure, and re-create the
307           gensec session. The logon_retries counter ensures we don't
308           loop forever.
309          */
310         data_blob_free(&input);
311         TALLOC_FREE(conn->gensec);
312
313         status = gensec_client_start(conn, &conn->gensec,
314                                      lpcfg_gensec_settings(conn, lp_ctx));
315         if (!NT_STATUS_IS_OK(status)) {
316                 DEBUG(0, ("Failed to start GENSEC engine (%s)\n", nt_errstr(status)));
317                 goto failed;
318         }
319
320         old_gensec_features = cli_credentials_get_gensec_features(creds);
321         if (wrap_flags == 0) {
322                 cli_credentials_set_gensec_features(creds, old_gensec_features & ~(GENSEC_FEATURE_SIGN|GENSEC_FEATURE_SEAL));
323         }
324
325         /* this call also sets the gensec_want_features */
326         status = gensec_set_credentials(conn->gensec, creds);
327         if (!NT_STATUS_IS_OK(status)) {
328                 DEBUG(1, ("Failed to set GENSEC creds: %s\n", 
329                           nt_errstr(status)));
330                 goto failed;
331         }
332
333         /* reset the original gensec_features (on the credentials
334          * context, so we don't tatoo it ) */
335         cli_credentials_set_gensec_features(creds, old_gensec_features);
336
337         if (wrap_flags & ADS_AUTH_SASL_SEAL) {
338                 gensec_want_feature(conn->gensec, GENSEC_FEATURE_SIGN);
339                 gensec_want_feature(conn->gensec, GENSEC_FEATURE_SEAL);
340         }
341         if (wrap_flags & ADS_AUTH_SASL_SIGN) {
342                 gensec_want_feature(conn->gensec, GENSEC_FEATURE_SIGN);
343         }
344
345         /*
346          * This is an indication for the NTLMSSP backend to
347          * also encrypt when only GENSEC_FEATURE_SIGN is requested
348          * in gensec_[un]wrap().
349          */
350         gensec_want_feature(conn->gensec, GENSEC_FEATURE_LDAP_STYLE);
351
352         if (conn->host) {
353                 status = gensec_set_target_hostname(conn->gensec, conn->host);
354                 if (!NT_STATUS_IS_OK(status)) {
355                         DEBUG(1, ("Failed to set GENSEC target hostname: %s\n", 
356                                   nt_errstr(status)));
357                         goto failed;
358                 }
359         }
360
361         status = gensec_set_target_service(conn->gensec, "ldap");
362         if (!NT_STATUS_IS_OK(status)) {
363                 DEBUG(1, ("Failed to set GENSEC target service: %s\n", 
364                           nt_errstr(status)));
365                 goto failed;
366         }
367
368         status = gensec_start_mech_by_sasl_list(conn->gensec, sasl_names);
369         if (!NT_STATUS_IS_OK(status)) {
370                 DEBUG(1, ("None of the %d proposed SASL mechs were acceptable: %s\n",
371                           count, nt_errstr(status)));
372                 goto failed;
373         }
374
375         while (1) {
376                 NTSTATUS gensec_status;
377                 struct ldap_message *response;
378                 struct ldap_message *msg;
379                 struct ldap_request *req;
380                 int result = LDAP_OTHER;
381         
382                 status = gensec_update_ev(conn->gensec, tmp_ctx,
383                                        conn->event.event_ctx,
384                                        input,
385                                        &output);
386                 /* The status value here, from GENSEC is vital to the security
387                  * of the system.  Even if the other end accepts, if GENSEC
388                  * claims 'MORE_PROCESSING_REQUIRED' then you must keep
389                  * feeding it blobs, or else the remote host/attacker might
390                  * avoid mutal authentication requirements.
391                  *
392                  * Likewise, you must not feed GENSEC too much (after the OK),
393                  * it doesn't like that either.
394                  *
395                  * For SASL/EXTERNAL, there is no data to send, but we still
396                  * must send the actual Bind request the first time around.
397                  * Otherwise, a result of NT_STATUS_OK with 0 output means the
398                  * end of a multi-step authentication, and no message must be
399                  * sent.
400                  */
401
402                 gensec_status = status;
403
404                 if (!NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED) && 
405                     !NT_STATUS_IS_OK(status)) {
406                         break;
407                 }
408                 if (NT_STATUS_IS_OK(status) && output.length == 0) {
409                         if (!first)
410                                 break;
411                 }
412                 first = false;
413
414                 /* Perhaps we should make gensec_start_mech_by_sasl_list() return the name we got? */
415                 msg = new_ldap_sasl_bind_msg(tmp_ctx, conn->gensec->ops->sasl_name, (output.data?&output:NULL));
416                 if (msg == NULL) {
417                         status = NT_STATUS_NO_MEMORY;
418                         goto failed;
419                 }
420
421                 req = ldap_request_send(conn, msg);
422                 if (req == NULL) {
423                         status = NT_STATUS_NO_MEMORY;
424                         goto failed;
425                 }
426                 talloc_reparent(conn, tmp_ctx, req);
427
428                 status = ldap_result_n(req, 0, &response);
429                 if (!NT_STATUS_IS_OK(status)) {
430                         goto failed;
431                 }
432                 
433                 if (response->type != LDAP_TAG_BindResponse) {
434                         status = NT_STATUS_UNEXPECTED_NETWORK_ERROR;
435                         goto failed;
436                 }
437
438                 result = response->r.BindResponse.response.resultcode;
439
440                 if (result == LDAP_INVALID_CREDENTIALS) {
441                         /*
442                           try a second time on invalid credentials, to
443                           give the user a chance to re-enter the
444                           password and to handle the case where our
445                           kerberos ticket is invalid as the server
446                           password has changed
447                         */
448                         const char *principal;
449
450                         principal = gensec_get_target_principal(conn->gensec);
451                         if (principal == NULL) {
452                                 const char *hostname = gensec_get_target_hostname(conn->gensec);
453                                 const char *service  = gensec_get_target_service(conn->gensec);
454                                 if (hostname != NULL && service != NULL) {
455                                         principal = talloc_asprintf(tmp_ctx, "%s/%s", service, hostname);
456                                 }
457                         }
458
459                         if (cli_credentials_failed_kerberos_login(creds, principal, &logon_retries) ||
460                             cli_credentials_wrong_password(creds)) {
461                                 /*
462                                   destroy our gensec session and loop
463                                   back up to the top to retry,
464                                   offering the user a chance to enter
465                                   new credentials, or get a new ticket
466                                   if using kerberos
467                                  */
468                                 goto try_logon_again;
469                         }
470                 }
471
472                 if (result != LDAP_SUCCESS && result != LDAP_SASL_BIND_IN_PROGRESS) {
473                         status = ldap_check_response(conn, 
474                                                      &response->r.BindResponse.response);
475                         break;
476                 }
477
478                 /* This is where we check if GENSEC wanted to be fed more data */
479                 if (!NT_STATUS_EQUAL(gensec_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
480                         break;
481                 }
482                 if (response->r.BindResponse.SASL.secblob) {
483                         input = *response->r.BindResponse.SASL.secblob;
484                 } else {
485                         input = data_blob(NULL, 0);
486                 }
487         }
488
489         TALLOC_FREE(tmp_ctx);
490
491         if (!NT_STATUS_IS_OK(status)) {
492                 goto failed;
493         }
494
495         conn->bind.type = LDAP_BIND_SASL;
496         conn->bind.creds = creds;
497
498         if (!gensec_have_feature(conn->gensec, GENSEC_FEATURE_SIGN) &&
499             !gensec_have_feature(conn->gensec, GENSEC_FEATURE_SEAL)) {
500                 return NT_STATUS_OK;
501         }
502
503         status = gensec_create_tstream(conn->sockets.raw,
504                                        conn->gensec,
505                                        conn->sockets.raw,
506                                        &conn->sockets.sasl);
507         if (!NT_STATUS_IS_OK(status)) {
508                 goto failed;
509         }
510
511         conn->sockets.active = conn->sockets.sasl;
512
513         return NT_STATUS_OK;
514
515 failed:
516         talloc_free(tmp_ctx);
517         talloc_free(conn->gensec);
518         conn->gensec = NULL;
519         return status;
520 }