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