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