s3:ntlmssp: only include ntlmssp.h where actually needed
[nivanova/samba-autobuild/.git] / source3 / libsmb / cliconnect.c
1 /* 
2    Unix SMB/CIFS implementation.
3    client connect/disconnect routines
4    Copyright (C) Andrew Tridgell 1994-1998
5    Copyright (C) Andrew Bartlett 2001-2003
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "includes.h"
22 #include "../libcli/auth/libcli_auth.h"
23 #include "../libcli/auth/spnego.h"
24 #include "smb_krb5.h"
25 #include "ntlmssp.h"
26
27 static const struct {
28         int prot;
29         const char name[24];
30 } prots[10] = {
31         {PROTOCOL_CORE,         "PC NETWORK PROGRAM 1.0"},
32         {PROTOCOL_COREPLUS,     "MICROSOFT NETWORKS 1.03"},
33         {PROTOCOL_LANMAN1,      "MICROSOFT NETWORKS 3.0"},
34         {PROTOCOL_LANMAN1,      "LANMAN1.0"},
35         {PROTOCOL_LANMAN2,      "LM1.2X002"},
36         {PROTOCOL_LANMAN2,      "DOS LANMAN2.1"},
37         {PROTOCOL_LANMAN2,      "LANMAN2.1"},
38         {PROTOCOL_LANMAN2,      "Samba"},
39         {PROTOCOL_NT1,          "NT LANMAN 1.0"},
40         {PROTOCOL_NT1,          "NT LM 0.12"},
41 };
42
43 #define STAR_SMBSERVER "*SMBSERVER"
44
45 /**
46  * Set the user session key for a connection
47  * @param cli The cli structure to add it too
48  * @param session_key The session key used.  (A copy of this is taken for the cli struct)
49  *
50  */
51
52 static void cli_set_session_key (struct cli_state *cli, const DATA_BLOB session_key) 
53 {
54         cli->user_session_key = data_blob(session_key.data, session_key.length);
55 }
56
57 /****************************************************************************
58  Do an old lanman2 style session setup.
59 ****************************************************************************/
60
61 static NTSTATUS cli_session_setup_lanman2(struct cli_state *cli,
62                                           const char *user, 
63                                           const char *pass, size_t passlen,
64                                           const char *workgroup)
65 {
66         DATA_BLOB session_key = data_blob_null;
67         DATA_BLOB lm_response = data_blob_null;
68         NTSTATUS status;
69         fstring pword;
70         char *p;
71
72         if (passlen > sizeof(pword)-1) {
73                 return NT_STATUS_INVALID_PARAMETER;
74         }
75
76         /* LANMAN servers predate NT status codes and Unicode and ignore those 
77            smb flags so we must disable the corresponding default capabilities  
78            that would otherwise cause the Unicode and NT Status flags to be
79            set (and even returned by the server) */
80
81         cli->capabilities &= ~(CAP_UNICODE | CAP_STATUS32);
82
83         /* if in share level security then don't send a password now */
84         if (!(cli->sec_mode & NEGOTIATE_SECURITY_USER_LEVEL))
85                 passlen = 0;
86
87         if (passlen > 0 && (cli->sec_mode & NEGOTIATE_SECURITY_CHALLENGE_RESPONSE) && passlen != 24) {
88                 /* Encrypted mode needed, and non encrypted password supplied. */
89                 lm_response = data_blob(NULL, 24);
90                 if (!SMBencrypt(pass, cli->secblob.data,(uchar *)lm_response.data)) {
91                         DEBUG(1, ("Password is > 14 chars in length, and is therefore incompatible with Lanman authentication\n"));
92                         return NT_STATUS_ACCESS_DENIED;
93                 }
94         } else if ((cli->sec_mode & NEGOTIATE_SECURITY_CHALLENGE_RESPONSE) && passlen == 24) {
95                 /* Encrypted mode needed, and encrypted password supplied. */
96                 lm_response = data_blob(pass, passlen);
97         } else if (passlen > 0) {
98                 /* Plaintext mode needed, assume plaintext supplied. */
99                 passlen = clistr_push(cli, pword, pass, sizeof(pword), STR_TERMINATE);
100                 lm_response = data_blob(pass, passlen);
101         }
102
103         /* send a session setup command */
104         memset(cli->outbuf,'\0',smb_size);
105         cli_set_message(cli->outbuf,10, 0, True);
106         SCVAL(cli->outbuf,smb_com,SMBsesssetupX);
107         cli_setup_packet(cli);
108         
109         SCVAL(cli->outbuf,smb_vwv0,0xFF);
110         SSVAL(cli->outbuf,smb_vwv2,cli->max_xmit);
111         SSVAL(cli->outbuf,smb_vwv3,2);
112         SSVAL(cli->outbuf,smb_vwv4,1);
113         SIVAL(cli->outbuf,smb_vwv5,cli->sesskey);
114         SSVAL(cli->outbuf,smb_vwv7,lm_response.length);
115
116         p = smb_buf(cli->outbuf);
117         memcpy(p,lm_response.data,lm_response.length);
118         p += lm_response.length;
119         p += clistr_push(cli, p, user, -1, STR_TERMINATE|STR_UPPER);
120         p += clistr_push(cli, p, workgroup, -1, STR_TERMINATE|STR_UPPER);
121         p += clistr_push(cli, p, "Unix", -1, STR_TERMINATE);
122         p += clistr_push(cli, p, "Samba", -1, STR_TERMINATE);
123         cli_setup_bcc(cli, p);
124
125         if (!cli_send_smb(cli) || !cli_receive_smb(cli)) {
126                 return cli_nt_error(cli);
127         }
128
129         show_msg(cli->inbuf);
130
131         if (cli_is_error(cli)) {
132                 return cli_nt_error(cli);
133         }
134         
135         /* use the returned vuid from now on */
136         cli->vuid = SVAL(cli->inbuf,smb_uid);   
137         status = cli_set_username(cli, user);
138         if (!NT_STATUS_IS_OK(status)) {
139                 return status;
140         }
141
142         if (session_key.data) {
143                 /* Have plaintext orginal */
144                 cli_set_session_key(cli, session_key);
145         }
146
147         return NT_STATUS_OK;
148 }
149
150 /****************************************************************************
151  Work out suitable capabilities to offer the server.
152 ****************************************************************************/
153
154 static uint32 cli_session_setup_capabilities(struct cli_state *cli)
155 {
156         uint32 capabilities = CAP_NT_SMBS;
157
158         if (!cli->force_dos_errors)
159                 capabilities |= CAP_STATUS32;
160
161         if (cli->use_level_II_oplocks)
162                 capabilities |= CAP_LEVEL_II_OPLOCKS;
163
164         capabilities |= (cli->capabilities & (CAP_UNICODE|CAP_LARGE_FILES|CAP_LARGE_READX|CAP_LARGE_WRITEX|CAP_DFS));
165         return capabilities;
166 }
167
168 /****************************************************************************
169  Do a NT1 guest session setup.
170 ****************************************************************************/
171
172 struct cli_session_setup_guest_state {
173         struct cli_state *cli;
174         uint16_t vwv[16];
175         struct iovec bytes;
176 };
177
178 static void cli_session_setup_guest_done(struct tevent_req *subreq);
179
180 struct tevent_req *cli_session_setup_guest_create(TALLOC_CTX *mem_ctx,
181                                                   struct event_context *ev,
182                                                   struct cli_state *cli,
183                                                   struct tevent_req **psmbreq)
184 {
185         struct tevent_req *req, *subreq;
186         struct cli_session_setup_guest_state *state;
187         uint16_t *vwv;
188         uint8_t *bytes;
189
190         req = tevent_req_create(mem_ctx, &state,
191                                 struct cli_session_setup_guest_state);
192         if (req == NULL) {
193                 return NULL;
194         }
195         state->cli = cli;
196         vwv = state->vwv;
197
198         SCVAL(vwv+0, 0, 0xFF);
199         SCVAL(vwv+0, 1, 0);
200         SSVAL(vwv+1, 0, 0);
201         SSVAL(vwv+2, 0, CLI_BUFFER_SIZE);
202         SSVAL(vwv+3, 0, 2);
203         SSVAL(vwv+4, 0, cli->pid);
204         SIVAL(vwv+5, 0, cli->sesskey);
205         SSVAL(vwv+7, 0, 0);
206         SSVAL(vwv+8, 0, 0);
207         SSVAL(vwv+9, 0, 0);
208         SSVAL(vwv+10, 0, 0);
209         SIVAL(vwv+11, 0, cli_session_setup_capabilities(cli));
210
211         bytes = talloc_array(state, uint8_t, 0);
212
213         bytes = smb_bytes_push_str(bytes, cli_ucs2(cli), "",  1, /* username */
214                                    NULL);
215         bytes = smb_bytes_push_str(bytes, cli_ucs2(cli), "", 1, /* workgroup */
216                                    NULL);
217         bytes = smb_bytes_push_str(bytes, cli_ucs2(cli), "Unix", 5, NULL);
218         bytes = smb_bytes_push_str(bytes, cli_ucs2(cli), "Samba", 6, NULL);
219
220         if (bytes == NULL) {
221                 TALLOC_FREE(req);
222                 return NULL;
223         }
224
225         state->bytes.iov_base = (void *)bytes;
226         state->bytes.iov_len = talloc_get_size(bytes);
227
228         subreq = cli_smb_req_create(state, ev, cli, SMBsesssetupX, 0, 13, vwv,
229                                     1, &state->bytes);
230         if (subreq == NULL) {
231                 TALLOC_FREE(req);
232                 return NULL;
233         }
234         tevent_req_set_callback(subreq, cli_session_setup_guest_done, req);
235         *psmbreq = subreq;
236         return req;
237 }
238
239 struct tevent_req *cli_session_setup_guest_send(TALLOC_CTX *mem_ctx,
240                                                 struct event_context *ev,
241                                                 struct cli_state *cli)
242 {
243         struct tevent_req *req, *subreq;
244         NTSTATUS status;
245
246         req = cli_session_setup_guest_create(mem_ctx, ev, cli, &subreq);
247         if (req == NULL) {
248                 return NULL;
249         }
250
251         status = cli_smb_req_send(subreq);
252         if (NT_STATUS_IS_OK(status)) {
253                 tevent_req_nterror(req, status);
254                 return tevent_req_post(req, ev);
255         }
256         return req;
257 }
258
259 static void cli_session_setup_guest_done(struct tevent_req *subreq)
260 {
261         struct tevent_req *req = tevent_req_callback_data(
262                 subreq, struct tevent_req);
263         struct cli_session_setup_guest_state *state = tevent_req_data(
264                 req, struct cli_session_setup_guest_state);
265         struct cli_state *cli = state->cli;
266         uint32_t num_bytes;
267         char *inbuf;
268         uint8_t *bytes;
269         uint8_t *p;
270         NTSTATUS status;
271
272         status = cli_smb_recv(subreq, 0, NULL, NULL, &num_bytes, &bytes);
273         if (!NT_STATUS_IS_OK(status)) {
274                 TALLOC_FREE(subreq);
275                 tevent_req_nterror(req, status);
276                 return;
277         }
278
279         inbuf = (char *)cli_smb_inbuf(subreq);
280         p = bytes;
281
282         cli->vuid = SVAL(inbuf, smb_uid);
283
284         p += clistr_pull(inbuf, cli->server_os, (char *)p, sizeof(fstring),
285                          bytes+num_bytes-p, STR_TERMINATE);
286         p += clistr_pull(inbuf, cli->server_type, (char *)p, sizeof(fstring),
287                          bytes+num_bytes-p, STR_TERMINATE);
288         p += clistr_pull(inbuf, cli->server_domain, (char *)p, sizeof(fstring),
289                          bytes+num_bytes-p, STR_TERMINATE);
290
291         if (strstr(cli->server_type, "Samba")) {
292                 cli->is_samba = True;
293         }
294
295         TALLOC_FREE(subreq);
296
297         status = cli_set_username(cli, "");
298         if (!NT_STATUS_IS_OK(status)) {
299                 tevent_req_nterror(req, status);
300                 return;
301         }
302         tevent_req_done(req);
303 }
304
305 NTSTATUS cli_session_setup_guest_recv(struct tevent_req *req)
306 {
307         return tevent_req_simple_recv_ntstatus(req);
308 }
309
310 static NTSTATUS cli_session_setup_guest(struct cli_state *cli)
311 {
312         TALLOC_CTX *frame = talloc_stackframe();
313         struct event_context *ev;
314         struct tevent_req *req;
315         NTSTATUS status = NT_STATUS_OK;
316
317         if (cli_has_async_calls(cli)) {
318                 /*
319                  * Can't use sync call while an async call is in flight
320                  */
321                 status = NT_STATUS_INVALID_PARAMETER;
322                 goto fail;
323         }
324
325         ev = event_context_init(frame);
326         if (ev == NULL) {
327                 status = NT_STATUS_NO_MEMORY;
328                 goto fail;
329         }
330
331         req = cli_session_setup_guest_send(frame, ev, cli);
332         if (req == NULL) {
333                 status = NT_STATUS_NO_MEMORY;
334                 goto fail;
335         }
336
337         if (!tevent_req_poll(req, ev)) {
338                 status = map_nt_error_from_unix(errno);
339                 goto fail;
340         }
341
342         status = cli_session_setup_guest_recv(req);
343  fail:
344         TALLOC_FREE(frame);
345         if (!NT_STATUS_IS_OK(status)) {
346                 cli_set_error(cli, status);
347         }
348         return status;
349 }
350
351 /****************************************************************************
352  Do a NT1 plaintext session setup.
353 ****************************************************************************/
354
355 static NTSTATUS cli_session_setup_plaintext(struct cli_state *cli,
356                                             const char *user, const char *pass,
357                                             const char *workgroup)
358 {
359         uint32 capabilities = cli_session_setup_capabilities(cli);
360         char *p;
361         NTSTATUS status;
362         fstring lanman;
363         
364         fstr_sprintf( lanman, "Samba %s", samba_version_string());
365
366         memset(cli->outbuf, '\0', smb_size);
367         cli_set_message(cli->outbuf,13,0,True);
368         SCVAL(cli->outbuf,smb_com,SMBsesssetupX);
369         cli_setup_packet(cli);
370                         
371         SCVAL(cli->outbuf,smb_vwv0,0xFF);
372         SSVAL(cli->outbuf,smb_vwv2,CLI_BUFFER_SIZE);
373         SSVAL(cli->outbuf,smb_vwv3,2);
374         SSVAL(cli->outbuf,smb_vwv4,cli->pid);
375         SIVAL(cli->outbuf,smb_vwv5,cli->sesskey);
376         SSVAL(cli->outbuf,smb_vwv8,0);
377         SIVAL(cli->outbuf,smb_vwv11,capabilities); 
378         p = smb_buf(cli->outbuf);
379         
380         /* check wether to send the ASCII or UNICODE version of the password */
381         
382         if ( (capabilities & CAP_UNICODE) == 0 ) {
383                 p += clistr_push(cli, p, pass, -1, STR_TERMINATE); /* password */
384                 SSVAL(cli->outbuf,smb_vwv7,PTR_DIFF(p, smb_buf(cli->outbuf)));
385         }
386         else {
387                 /* For ucs2 passwords clistr_push calls ucs2_align, which causes
388                  * the space taken by the unicode password to be one byte too
389                  * long (as we're on an odd byte boundary here). Reduce the
390                  * count by 1 to cope with this. Fixes smbclient against NetApp
391                  * servers which can't cope. Fix from
392                  * bryan.kolodziej@allenlund.com in bug #3840.
393                  */
394                 p += clistr_push(cli, p, pass, -1, STR_UNICODE|STR_TERMINATE); /* unicode password */
395                 SSVAL(cli->outbuf,smb_vwv8,PTR_DIFF(p, smb_buf(cli->outbuf))-1);        
396         }
397         
398         p += clistr_push(cli, p, user, -1, STR_TERMINATE); /* username */
399         p += clistr_push(cli, p, workgroup, -1, STR_TERMINATE); /* workgroup */
400         p += clistr_push(cli, p, "Unix", -1, STR_TERMINATE);
401         p += clistr_push(cli, p, lanman, -1, STR_TERMINATE);
402         cli_setup_bcc(cli, p);
403
404         if (!cli_send_smb(cli) || !cli_receive_smb(cli)) {
405                 return cli_nt_error(cli);
406         }
407         
408         show_msg(cli->inbuf);
409         
410         if (cli_is_error(cli)) {
411                 return cli_nt_error(cli);
412         }
413
414         cli->vuid = SVAL(cli->inbuf,smb_uid);
415         p = smb_buf(cli->inbuf);
416         p += clistr_pull(cli->inbuf, cli->server_os, p, sizeof(fstring),
417                          -1, STR_TERMINATE);
418         p += clistr_pull(cli->inbuf, cli->server_type, p, sizeof(fstring),
419                          -1, STR_TERMINATE);
420         p += clistr_pull(cli->inbuf, cli->server_domain, p, sizeof(fstring),
421                          -1, STR_TERMINATE);
422         status = cli_set_username(cli, user);
423         if (!NT_STATUS_IS_OK(status)) {
424                 return status;
425         }
426         if (strstr(cli->server_type, "Samba")) {
427                 cli->is_samba = True;
428         }
429
430         return NT_STATUS_OK;
431 }
432
433 /****************************************************************************
434    do a NT1 NTLM/LM encrypted session setup - for when extended security
435    is not negotiated.
436    @param cli client state to create do session setup on
437    @param user username
438    @param pass *either* cleartext password (passlen !=24) or LM response.
439    @param ntpass NT response, implies ntpasslen >=24, implies pass is not clear
440    @param workgroup The user's domain.
441 ****************************************************************************/
442
443 static NTSTATUS cli_session_setup_nt1(struct cli_state *cli, const char *user, 
444                                       const char *pass, size_t passlen,
445                                       const char *ntpass, size_t ntpasslen,
446                                       const char *workgroup)
447 {
448         uint32 capabilities = cli_session_setup_capabilities(cli);
449         DATA_BLOB lm_response = data_blob_null;
450         DATA_BLOB nt_response = data_blob_null;
451         DATA_BLOB session_key = data_blob_null;
452         NTSTATUS result;
453         char *p;
454         bool ok;
455
456         if (passlen == 0) {
457                 /* do nothing - guest login */
458         } else if (passlen != 24) {
459                 if (lp_client_ntlmv2_auth()) {
460                         DATA_BLOB server_chal;
461                         DATA_BLOB names_blob;
462                         server_chal = data_blob(cli->secblob.data, MIN(cli->secblob.length, 8)); 
463
464                         /* note that the 'workgroup' here is a best guess - we don't know
465                            the server's domain at this point.  The 'server name' is also
466                            dodgy... 
467                         */
468                         names_blob = NTLMv2_generate_names_blob(NULL, cli->called.name, workgroup);
469
470                         if (!SMBNTLMv2encrypt(NULL, user, workgroup, pass, &server_chal, 
471                                               &names_blob,
472                                               &lm_response, &nt_response, NULL, &session_key)) {
473                                 data_blob_free(&names_blob);
474                                 data_blob_free(&server_chal);
475                                 return NT_STATUS_ACCESS_DENIED;
476                         }
477                         data_blob_free(&names_blob);
478                         data_blob_free(&server_chal);
479
480                 } else {
481                         uchar nt_hash[16];
482                         E_md4hash(pass, nt_hash);
483
484 #ifdef LANMAN_ONLY
485                         nt_response = data_blob_null;
486 #else
487                         nt_response = data_blob(NULL, 24);
488                         SMBNTencrypt(pass,cli->secblob.data,nt_response.data);
489 #endif
490                         /* non encrypted password supplied. Ignore ntpass. */
491                         if (lp_client_lanman_auth()) {
492                                 lm_response = data_blob(NULL, 24);
493                                 if (!SMBencrypt(pass,cli->secblob.data, lm_response.data)) {
494                                         /* Oops, the LM response is invalid, just put 
495                                            the NT response there instead */
496                                         data_blob_free(&lm_response);
497                                         lm_response = data_blob(nt_response.data, nt_response.length);
498                                 }
499                         } else {
500                                 /* LM disabled, place NT# in LM field instead */
501                                 lm_response = data_blob(nt_response.data, nt_response.length);
502                         }
503
504                         session_key = data_blob(NULL, 16);
505 #ifdef LANMAN_ONLY
506                         E_deshash(pass, session_key.data);
507                         memset(&session_key.data[8], '\0', 8);
508 #else
509                         SMBsesskeygen_ntv1(nt_hash, session_key.data);
510 #endif
511                 }
512                 cli_temp_set_signing(cli);
513         } else {
514                 /* pre-encrypted password supplied.  Only used for 
515                    security=server, can't do
516                    signing because we don't have original key */
517
518                 lm_response = data_blob(pass, passlen);
519                 nt_response = data_blob(ntpass, ntpasslen);
520         }
521
522         /* send a session setup command */
523         memset(cli->outbuf,'\0',smb_size);
524
525         cli_set_message(cli->outbuf,13,0,True);
526         SCVAL(cli->outbuf,smb_com,SMBsesssetupX);
527         cli_setup_packet(cli);
528                         
529         SCVAL(cli->outbuf,smb_vwv0,0xFF);
530         SSVAL(cli->outbuf,smb_vwv2,CLI_BUFFER_SIZE);
531         SSVAL(cli->outbuf,smb_vwv3,2);
532         SSVAL(cli->outbuf,smb_vwv4,cli->pid);
533         SIVAL(cli->outbuf,smb_vwv5,cli->sesskey);
534         SSVAL(cli->outbuf,smb_vwv7,lm_response.length);
535         SSVAL(cli->outbuf,smb_vwv8,nt_response.length);
536         SIVAL(cli->outbuf,smb_vwv11,capabilities); 
537         p = smb_buf(cli->outbuf);
538         if (lm_response.length) {
539                 memcpy(p,lm_response.data, lm_response.length); p += lm_response.length;
540         }
541         if (nt_response.length) {
542                 memcpy(p,nt_response.data, nt_response.length); p += nt_response.length;
543         }
544         p += clistr_push(cli, p, user, -1, STR_TERMINATE);
545
546         /* Upper case here might help some NTLMv2 implementations */
547         p += clistr_push(cli, p, workgroup, -1, STR_TERMINATE|STR_UPPER);
548         p += clistr_push(cli, p, "Unix", -1, STR_TERMINATE);
549         p += clistr_push(cli, p, "Samba", -1, STR_TERMINATE);
550         cli_setup_bcc(cli, p);
551
552         if (!cli_send_smb(cli) || !cli_receive_smb(cli)) {
553                 result = cli_nt_error(cli);
554                 goto end;
555         }
556
557         /* show_msg(cli->inbuf); */
558
559         if (cli_is_error(cli)) {
560                 result = cli_nt_error(cli);
561                 goto end;
562         }
563
564 #ifdef LANMAN_ONLY
565         ok = cli_simple_set_signing(cli, session_key, lm_response);
566 #else
567         ok = cli_simple_set_signing(cli, session_key, nt_response);
568 #endif
569         if (ok) {
570                 if (!cli_check_sign_mac(cli, cli->inbuf, 1)) {
571                         result = NT_STATUS_ACCESS_DENIED;
572                         goto end;
573                 }
574         }
575
576         /* use the returned vuid from now on */
577         cli->vuid = SVAL(cli->inbuf,smb_uid);
578         
579         p = smb_buf(cli->inbuf);
580         p += clistr_pull(cli->inbuf, cli->server_os, p, sizeof(fstring),
581                          -1, STR_TERMINATE);
582         p += clistr_pull(cli->inbuf, cli->server_type, p, sizeof(fstring),
583                          -1, STR_TERMINATE);
584         p += clistr_pull(cli->inbuf, cli->server_domain, p, sizeof(fstring),
585                          -1, STR_TERMINATE);
586
587         if (strstr(cli->server_type, "Samba")) {
588                 cli->is_samba = True;
589         }
590
591         result = cli_set_username(cli, user);
592         if (!NT_STATUS_IS_OK(result)) {
593                 goto end;
594         }
595
596         if (session_key.data) {
597                 /* Have plaintext orginal */
598                 cli_set_session_key(cli, session_key);
599         }
600
601         result = NT_STATUS_OK;
602 end:    
603         data_blob_free(&lm_response);
604         data_blob_free(&nt_response);
605         data_blob_free(&session_key);
606         return result;
607 }
608
609 /****************************************************************************
610  Send a extended security session setup blob
611 ****************************************************************************/
612
613 static bool cli_session_setup_blob_send(struct cli_state *cli, DATA_BLOB blob)
614 {
615         uint32 capabilities = cli_session_setup_capabilities(cli);
616         char *p;
617
618         capabilities |= CAP_EXTENDED_SECURITY;
619
620         /* send a session setup command */
621         memset(cli->outbuf,'\0',smb_size);
622
623         cli_set_message(cli->outbuf,12,0,True);
624         SCVAL(cli->outbuf,smb_com,SMBsesssetupX);
625
626         cli_setup_packet(cli);
627
628         SCVAL(cli->outbuf,smb_vwv0,0xFF);
629         SSVAL(cli->outbuf,smb_vwv2,CLI_BUFFER_SIZE);
630         SSVAL(cli->outbuf,smb_vwv3,2);
631         SSVAL(cli->outbuf,smb_vwv4,1);
632         SIVAL(cli->outbuf,smb_vwv5,0);
633         SSVAL(cli->outbuf,smb_vwv7,blob.length);
634         SIVAL(cli->outbuf,smb_vwv10,capabilities); 
635         p = smb_buf(cli->outbuf);
636         memcpy(p, blob.data, blob.length);
637         p += blob.length;
638         p += clistr_push(cli, p, "Unix", -1, STR_TERMINATE);
639         p += clistr_push(cli, p, "Samba", -1, STR_TERMINATE);
640         cli_setup_bcc(cli, p);
641         return cli_send_smb(cli);
642 }
643
644 /****************************************************************************
645  Send a extended security session setup blob, returning a reply blob.
646 ****************************************************************************/
647
648 static DATA_BLOB cli_session_setup_blob_receive(struct cli_state *cli)
649 {
650         DATA_BLOB blob2 = data_blob_null;
651         char *p;
652         size_t len;
653
654         if (!cli_receive_smb(cli))
655                 return blob2;
656
657         show_msg(cli->inbuf);
658
659         if (cli_is_error(cli) && !NT_STATUS_EQUAL(cli_nt_error(cli),
660                                                   NT_STATUS_MORE_PROCESSING_REQUIRED)) {
661                 return blob2;
662         }
663
664         /* use the returned vuid from now on */
665         cli->vuid = SVAL(cli->inbuf,smb_uid);
666
667         p = smb_buf(cli->inbuf);
668
669         blob2 = data_blob(p, SVAL(cli->inbuf, smb_vwv3));
670
671         p += blob2.length;
672         p += clistr_pull(cli->inbuf, cli->server_os, p, sizeof(fstring),
673                          -1, STR_TERMINATE);
674
675         /* w2k with kerberos doesn't properly null terminate this field */
676         len = smb_bufrem(cli->inbuf, p);
677         if (p + len < cli->inbuf + cli->bufsize+SAFETY_MARGIN - 2) {
678                 char *end_of_buf = p + len;
679
680                 SSVAL(p, len, 0);
681                 /* Now it's null terminated. */
682                 p += clistr_pull(cli->inbuf, cli->server_type, p, sizeof(fstring),
683                         -1, STR_TERMINATE);
684                 /*
685                  * See if there's another string. If so it's the
686                  * server domain (part of the 'standard' Samba
687                  * server signature).
688                  */
689                 if (p < end_of_buf) {
690                         p += clistr_pull(cli->inbuf, cli->server_domain, p, sizeof(fstring),
691                                 -1, STR_TERMINATE);
692                 }
693         } else {
694                 /*
695                  * No room to null terminate so we can't see if there
696                  * is another string (server_domain) afterwards.
697                  */
698                 p += clistr_pull(cli->inbuf, cli->server_type, p, sizeof(fstring),
699                                  len, 0);
700         }
701         return blob2;
702 }
703
704 #ifdef HAVE_KRB5
705 /****************************************************************************
706  Send a extended security session setup blob, returning a reply blob.
707 ****************************************************************************/
708
709 /* The following is calculated from :
710  * (smb_size-4) = 35
711  * (smb_wcnt * 2) = 24 (smb_wcnt == 12 in cli_session_setup_blob_send() )
712  * (strlen("Unix") + 1 + strlen("Samba") + 1) * 2 = 22 (unicode strings at
713  * end of packet.
714  */
715
716 #define BASE_SESSSETUP_BLOB_PACKET_SIZE (35 + 24 + 22)
717
718 static bool cli_session_setup_blob(struct cli_state *cli, DATA_BLOB blob)
719 {
720         int32 remaining = blob.length;
721         int32 cur = 0;
722         DATA_BLOB send_blob = data_blob_null;
723         int32 max_blob_size = 0;
724         DATA_BLOB receive_blob = data_blob_null;
725
726         if (cli->max_xmit < BASE_SESSSETUP_BLOB_PACKET_SIZE + 1) {
727                 DEBUG(0,("cli_session_setup_blob: cli->max_xmit too small "
728                         "(was %u, need minimum %u)\n",
729                         (unsigned int)cli->max_xmit,
730                         BASE_SESSSETUP_BLOB_PACKET_SIZE));
731                 cli_set_nt_error(cli, NT_STATUS_INVALID_PARAMETER);
732                 return False;
733         }
734
735         max_blob_size = cli->max_xmit - BASE_SESSSETUP_BLOB_PACKET_SIZE;
736
737         while ( remaining > 0) {
738                 if (remaining >= max_blob_size) {
739                         send_blob.length = max_blob_size;
740                         remaining -= max_blob_size;
741                 } else {
742                         send_blob.length = remaining; 
743                         remaining = 0;
744                 }
745
746                 send_blob.data =  &blob.data[cur];
747                 cur += send_blob.length;
748
749                 DEBUG(10, ("cli_session_setup_blob: Remaining (%u) sending (%u) current (%u)\n", 
750                         (unsigned int)remaining,
751                         (unsigned int)send_blob.length,
752                         (unsigned int)cur ));
753
754                 if (!cli_session_setup_blob_send(cli, send_blob)) {
755                         DEBUG(0, ("cli_session_setup_blob: send failed\n"));
756                         return False;
757                 }
758
759                 receive_blob = cli_session_setup_blob_receive(cli);
760                 data_blob_free(&receive_blob);
761
762                 if (cli_is_error(cli) &&
763                                 !NT_STATUS_EQUAL( cli_get_nt_error(cli), 
764                                         NT_STATUS_MORE_PROCESSING_REQUIRED)) {
765                         DEBUG(0, ("cli_session_setup_blob: receive failed "
766                                   "(%s)\n", nt_errstr(cli_get_nt_error(cli))));
767                         cli->vuid = 0;
768                         return False;
769                 }
770         }
771
772         return True;
773 }
774
775 /****************************************************************************
776  Use in-memory credentials cache
777 ****************************************************************************/
778
779 static void use_in_memory_ccache(void) {
780         setenv(KRB5_ENV_CCNAME, "MEMORY:cliconnect", 1);
781 }
782
783 /****************************************************************************
784  Do a spnego/kerberos encrypted session setup.
785 ****************************************************************************/
786
787 static ADS_STATUS cli_session_setup_kerberos(struct cli_state *cli, const char *principal, const char *workgroup)
788 {
789         DATA_BLOB negTokenTarg;
790         DATA_BLOB session_key_krb5;
791         NTSTATUS nt_status;
792         int rc;
793
794         cli_temp_set_signing(cli);
795
796         DEBUG(2,("Doing kerberos session setup\n"));
797
798         /* generate the encapsulated kerberos5 ticket */
799         rc = spnego_gen_negTokenTarg(principal, 0, &negTokenTarg, &session_key_krb5, 0, NULL);
800
801         if (rc) {
802                 DEBUG(1, ("cli_session_setup_kerberos: spnego_gen_negTokenTarg failed: %s\n",
803                         error_message(rc)));
804                 return ADS_ERROR_KRB5(rc);
805         }
806
807 #if 0
808         file_save("negTokenTarg.dat", negTokenTarg.data, negTokenTarg.length);
809 #endif
810
811         if (!cli_session_setup_blob(cli, negTokenTarg)) {
812                 nt_status = cli_nt_error(cli);
813                 goto nt_error;
814         }
815
816         if (cli_is_error(cli)) {
817                 nt_status = cli_nt_error(cli);
818                 if (NT_STATUS_IS_OK(nt_status)) {
819                         nt_status = NT_STATUS_UNSUCCESSFUL;
820                 }
821                 goto nt_error;
822         }
823
824         cli_set_session_key(cli, session_key_krb5);
825
826         if (cli_simple_set_signing(
827                     cli, session_key_krb5, data_blob_null)) {
828
829                 if (!cli_check_sign_mac(cli, cli->inbuf, 1)) {
830                         nt_status = NT_STATUS_ACCESS_DENIED;
831                         goto nt_error;
832                 }
833         }
834
835         data_blob_free(&negTokenTarg);
836         data_blob_free(&session_key_krb5);
837
838         return ADS_ERROR_NT(NT_STATUS_OK);
839
840 nt_error:
841         data_blob_free(&negTokenTarg);
842         data_blob_free(&session_key_krb5);
843         cli->vuid = 0;
844         return ADS_ERROR_NT(nt_status);
845 }
846 #endif  /* HAVE_KRB5 */
847
848
849 /****************************************************************************
850  Do a spnego/NTLMSSP encrypted session setup.
851 ****************************************************************************/
852
853 static NTSTATUS cli_session_setup_ntlmssp(struct cli_state *cli, const char *user, 
854                                           const char *pass, const char *domain)
855 {
856         struct ntlmssp_state *ntlmssp_state;
857         NTSTATUS nt_status;
858         int turn = 1;
859         DATA_BLOB msg1;
860         DATA_BLOB blob = data_blob_null;
861         DATA_BLOB blob_in = data_blob_null;
862         DATA_BLOB blob_out = data_blob_null;
863
864         cli_temp_set_signing(cli);
865
866         if (!NT_STATUS_IS_OK(nt_status = ntlmssp_client_start(&ntlmssp_state))) {
867                 return nt_status;
868         }
869         ntlmssp_want_feature(ntlmssp_state, NTLMSSP_FEATURE_SESSION_KEY);
870
871         if (!NT_STATUS_IS_OK(nt_status = ntlmssp_set_username(ntlmssp_state, user))) {
872                 return nt_status;
873         }
874         if (!NT_STATUS_IS_OK(nt_status = ntlmssp_set_domain(ntlmssp_state, domain))) {
875                 return nt_status;
876         }
877         if (!NT_STATUS_IS_OK(nt_status = ntlmssp_set_password(ntlmssp_state, pass))) {
878                 return nt_status;
879         }
880
881         do {
882                 nt_status = ntlmssp_update(ntlmssp_state, 
883                                                   blob_in, &blob_out);
884                 data_blob_free(&blob_in);
885                 if (NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED) || NT_STATUS_IS_OK(nt_status)) {
886                         if (turn == 1) {
887                                 /* and wrap it in a SPNEGO wrapper */
888                                 msg1 = gen_negTokenInit(OID_NTLMSSP, blob_out);
889                         } else {
890                                 /* wrap it in SPNEGO */
891                                 msg1 = spnego_gen_auth(blob_out);
892                         }
893
894                         /* now send that blob on its way */
895                         if (!cli_session_setup_blob_send(cli, msg1)) {
896                                 DEBUG(3, ("Failed to send NTLMSSP/SPNEGO blob to server!\n"));
897                                 nt_status = NT_STATUS_UNSUCCESSFUL;
898                         } else {
899                                 blob = cli_session_setup_blob_receive(cli);
900
901                                 nt_status = cli_nt_error(cli);
902                                 if (cli_is_error(cli) && NT_STATUS_IS_OK(nt_status)) {
903                                         if (cli->smb_rw_error == SMB_READ_BAD_SIG) {
904                                                 nt_status = NT_STATUS_ACCESS_DENIED;
905                                         } else {
906                                                 nt_status = NT_STATUS_UNSUCCESSFUL;
907                                         }
908                                 }
909                         }
910                         data_blob_free(&msg1);
911                 }
912
913                 if (!blob.length) {
914                         if (NT_STATUS_IS_OK(nt_status)) {
915                                 nt_status = NT_STATUS_UNSUCCESSFUL;
916                         }
917                 } else if ((turn == 1) && 
918                            NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
919                         DATA_BLOB tmp_blob = data_blob_null;
920                         /* the server might give us back two challenges */
921                         if (!spnego_parse_challenge(blob, &blob_in, 
922                                                     &tmp_blob)) {
923                                 DEBUG(3,("Failed to parse challenges\n"));
924                                 nt_status = NT_STATUS_INVALID_PARAMETER;
925                         }
926                         data_blob_free(&tmp_blob);
927                 } else {
928                         if (!spnego_parse_auth_response(blob, nt_status, OID_NTLMSSP, 
929                                                         &blob_in)) {
930                                 DEBUG(3,("Failed to parse auth response\n"));
931                                 if (NT_STATUS_IS_OK(nt_status) 
932                                     || NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) 
933                                         nt_status = NT_STATUS_INVALID_PARAMETER;
934                         }
935                 }
936                 data_blob_free(&blob);
937                 data_blob_free(&blob_out);
938                 turn++;
939         } while (NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED));
940
941         data_blob_free(&blob_in);
942
943         if (NT_STATUS_IS_OK(nt_status)) {
944
945                 if (cli->server_domain[0] == '\0') {
946                         fstrcpy(cli->server_domain, ntlmssp_state->server_domain);
947                 }
948                 cli_set_session_key(cli, ntlmssp_state->session_key);
949
950                 if (cli_simple_set_signing(
951                             cli, ntlmssp_state->session_key, data_blob_null)) {
952
953                         if (!cli_check_sign_mac(cli, cli->inbuf, 1)) {
954                                 nt_status = NT_STATUS_ACCESS_DENIED;
955                         }
956                 }
957         }
958
959         /* we have a reference conter on ntlmssp_state, if we are signing
960            then the state will be kept by the signing engine */
961
962         ntlmssp_end(&ntlmssp_state);
963
964         if (!NT_STATUS_IS_OK(nt_status)) {
965                 cli->vuid = 0;
966         }
967         return nt_status;
968 }
969
970 /****************************************************************************
971  Do a spnego encrypted session setup.
972
973  user_domain: The shortname of the domain the user/machine is a member of.
974  dest_realm: The realm we're connecting to, if NULL we use our default realm.
975 ****************************************************************************/
976
977 ADS_STATUS cli_session_setup_spnego(struct cli_state *cli, const char *user, 
978                               const char *pass, const char *user_domain,
979                               const char * dest_realm)
980 {
981         char *principal = NULL;
982         char *OIDs[ASN1_MAX_OIDS];
983         int i;
984         DATA_BLOB blob;
985         const char *p = NULL;
986         char *account = NULL;
987         NTSTATUS status;
988
989         DEBUG(3,("Doing spnego session setup (blob length=%lu)\n", (unsigned long)cli->secblob.length));
990
991         /* the server might not even do spnego */
992         if (cli->secblob.length <= 16) {
993                 DEBUG(3,("server didn't supply a full spnego negprot\n"));
994                 goto ntlmssp;
995         }
996
997 #if 0
998         file_save("negprot.dat", cli->secblob.data, cli->secblob.length);
999 #endif
1000
1001         /* there is 16 bytes of GUID before the real spnego packet starts */
1002         blob = data_blob(cli->secblob.data+16, cli->secblob.length-16);
1003
1004         /* The server sent us the first part of the SPNEGO exchange in the
1005          * negprot reply. It is WRONG to depend on the principal sent in the
1006          * negprot reply, but right now we do it. If we don't receive one,
1007          * we try to best guess, then fall back to NTLM.  */
1008         if (!spnego_parse_negTokenInit(blob, OIDs, &principal)) {
1009                 data_blob_free(&blob);
1010                 return ADS_ERROR_NT(NT_STATUS_INVALID_PARAMETER);
1011         }
1012         data_blob_free(&blob);
1013
1014         /* make sure the server understands kerberos */
1015         for (i=0;OIDs[i];i++) {
1016                 if (i == 0)
1017                         DEBUG(3,("got OID=%s\n", OIDs[i]));
1018                 else
1019                         DEBUGADD(3,("got OID=%s\n", OIDs[i]));
1020                 if (strcmp(OIDs[i], OID_KERBEROS5_OLD) == 0 ||
1021                     strcmp(OIDs[i], OID_KERBEROS5) == 0) {
1022                         cli->got_kerberos_mechanism = True;
1023                 }
1024                 talloc_free(OIDs[i]);
1025         }
1026
1027         DEBUG(3,("got principal=%s\n", principal ? principal : "<null>"));
1028
1029         status = cli_set_username(cli, user);
1030         if (!NT_STATUS_IS_OK(status)) {
1031                 return ADS_ERROR_NT(status);
1032         }
1033
1034 #ifdef HAVE_KRB5
1035         /* If password is set we reauthenticate to kerberos server
1036          * and do not store results */
1037
1038         if (cli->got_kerberos_mechanism && cli->use_kerberos) {
1039                 ADS_STATUS rc;
1040
1041                 if (pass && *pass) {
1042                         int ret;
1043
1044                         use_in_memory_ccache();
1045                         ret = kerberos_kinit_password(user, pass, 0 /* no time correction for now */, NULL);
1046
1047                         if (ret){
1048                                 TALLOC_FREE(principal);
1049                                 DEBUG(0, ("Kinit failed: %s\n", error_message(ret)));
1050                                 if (cli->fallback_after_kerberos)
1051                                         goto ntlmssp;
1052                                 return ADS_ERROR_KRB5(ret);
1053                         }
1054                 }
1055
1056                 /* If we get a bad principal, try to guess it if
1057                    we have a valid host NetBIOS name.
1058                  */
1059                 if (strequal(principal, ADS_IGNORE_PRINCIPAL)) {
1060                         TALLOC_FREE(principal);
1061                 }
1062
1063                 if (principal == NULL &&
1064                         !is_ipaddress(cli->desthost) &&
1065                         !strequal(STAR_SMBSERVER,
1066                                 cli->desthost)) {
1067                         char *realm = NULL;
1068                         char *machine = NULL;
1069                         char *host = NULL;
1070                         DEBUG(3,("cli_session_setup_spnego: got a "
1071                                 "bad server principal, trying to guess ...\n"));
1072
1073                         host = strchr_m(cli->desthost, '.');
1074                         if (host) {
1075                                 machine = SMB_STRNDUP(cli->desthost,
1076                                         host - cli->desthost);
1077                         } else {
1078                                 machine = SMB_STRDUP(cli->desthost);
1079                         }
1080                         if (machine == NULL) {
1081                                 return ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
1082                         }
1083
1084                         if (dest_realm) {
1085                                 realm = SMB_STRDUP(dest_realm);
1086                                 strupper_m(realm);
1087                         } else {
1088                                 realm = kerberos_get_default_realm_from_ccache();
1089                         }
1090                         if (realm && *realm) {
1091                                 principal = talloc_asprintf(NULL, "%s$@%s",
1092                                                         machine, realm);
1093                                 if (!principal) {
1094                                         SAFE_FREE(machine);
1095                                         SAFE_FREE(realm);
1096                                         return ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
1097                                 }
1098                                 DEBUG(3,("cli_session_setup_spnego: guessed "
1099                                         "server principal=%s\n",
1100                                         principal ? principal : "<null>"));
1101                         }
1102                         SAFE_FREE(machine);
1103                         SAFE_FREE(realm);
1104                 }
1105
1106                 if (principal) {
1107                         rc = cli_session_setup_kerberos(cli, principal,
1108                                 dest_realm);
1109                         if (ADS_ERR_OK(rc) || !cli->fallback_after_kerberos) {
1110                                 TALLOC_FREE(principal);
1111                                 return rc;
1112                         }
1113                 }
1114         }
1115 #endif
1116
1117         TALLOC_FREE(principal);
1118
1119 ntlmssp:
1120
1121         account = talloc_strdup(talloc_tos(), user);
1122         if (!account) {
1123                 return ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
1124         }
1125
1126         /* when falling back to ntlmssp while authenticating with a machine
1127          * account strip off the realm - gd */
1128
1129         if ((p = strchr_m(user, '@')) != NULL) {
1130                 account[PTR_DIFF(p,user)] = '\0';
1131         }
1132
1133         return ADS_ERROR_NT(cli_session_setup_ntlmssp(cli, account, pass, user_domain));
1134 }
1135
1136 /****************************************************************************
1137  Send a session setup. The username and workgroup is in UNIX character
1138  format and must be converted to DOS codepage format before sending. If the
1139  password is in plaintext, the same should be done.
1140 ****************************************************************************/
1141
1142 NTSTATUS cli_session_setup(struct cli_state *cli,
1143                            const char *user,
1144                            const char *pass, int passlen,
1145                            const char *ntpass, int ntpasslen,
1146                            const char *workgroup)
1147 {
1148         char *p;
1149         fstring user2;
1150
1151         if (user) {
1152                 fstrcpy(user2, user);
1153         } else {
1154                 user2[0] ='\0';
1155         }
1156
1157         if (!workgroup) {
1158                 workgroup = "";
1159         }
1160
1161         /* allow for workgroups as part of the username */
1162         if ((p=strchr_m(user2,'\\')) || (p=strchr_m(user2,'/')) ||
1163             (p=strchr_m(user2,*lp_winbind_separator()))) {
1164                 *p = 0;
1165                 user = p+1;
1166                 workgroup = user2;
1167         }
1168
1169         if (cli->protocol < PROTOCOL_LANMAN1) {
1170                 return NT_STATUS_OK;
1171         }
1172
1173         /* now work out what sort of session setup we are going to
1174            do. I have split this into separate functions to make the
1175            flow a bit easier to understand (tridge) */
1176
1177         /* if its an older server then we have to use the older request format */
1178
1179         if (cli->protocol < PROTOCOL_NT1) {
1180                 if (!lp_client_lanman_auth() && passlen != 24 && (*pass)) {
1181                         DEBUG(1, ("Server requested LM password but 'client lanman auth'"
1182                                   " is disabled\n"));
1183                         return NT_STATUS_ACCESS_DENIED;
1184                 }
1185
1186                 if ((cli->sec_mode & NEGOTIATE_SECURITY_CHALLENGE_RESPONSE) == 0 &&
1187                     !lp_client_plaintext_auth() && (*pass)) {
1188                         DEBUG(1, ("Server requested plaintext password but "
1189                                   "'client plaintext auth' is disabled\n"));
1190                         return NT_STATUS_ACCESS_DENIED;
1191                 }
1192
1193                 return cli_session_setup_lanman2(cli, user, pass, passlen,
1194                                                  workgroup);
1195         }
1196
1197         /* if no user is supplied then we have to do an anonymous connection.
1198            passwords are ignored */
1199
1200         if (!user || !*user)
1201                 return cli_session_setup_guest(cli);
1202
1203         /* if the server is share level then send a plaintext null
1204            password at this point. The password is sent in the tree
1205            connect */
1206
1207         if ((cli->sec_mode & NEGOTIATE_SECURITY_USER_LEVEL) == 0) 
1208                 return cli_session_setup_plaintext(cli, user, "", workgroup);
1209
1210         /* if the server doesn't support encryption then we have to use 
1211            plaintext. The second password is ignored */
1212
1213         if ((cli->sec_mode & NEGOTIATE_SECURITY_CHALLENGE_RESPONSE) == 0) {
1214                 if (!lp_client_plaintext_auth() && (*pass)) {
1215                         DEBUG(1, ("Server requested plaintext password but "
1216                                   "'client plaintext auth' is disabled\n"));
1217                         return NT_STATUS_ACCESS_DENIED;
1218                 }
1219                 return cli_session_setup_plaintext(cli, user, pass, workgroup);
1220         }
1221
1222         /* if the server supports extended security then use SPNEGO */
1223
1224         if (cli->capabilities & CAP_EXTENDED_SECURITY) {
1225                 ADS_STATUS status = cli_session_setup_spnego(cli, user, pass,
1226                                                              workgroup, NULL);
1227                 if (!ADS_ERR_OK(status)) {
1228                         DEBUG(3, ("SPNEGO login failed: %s\n", ads_errstr(status)));
1229                         return ads_ntstatus(status);
1230                 }
1231         } else {
1232                 NTSTATUS status;
1233
1234                 /* otherwise do a NT1 style session setup */
1235                 status = cli_session_setup_nt1(cli, user, pass, passlen,
1236                                                ntpass, ntpasslen, workgroup);
1237                 if (!NT_STATUS_IS_OK(status)) {
1238                         DEBUG(3,("cli_session_setup: NT1 session setup "
1239                                  "failed: %s\n", nt_errstr(status)));
1240                         return status;
1241                 }
1242         }
1243
1244         if (strstr(cli->server_type, "Samba")) {
1245                 cli->is_samba = True;
1246         }
1247
1248         return NT_STATUS_OK;
1249 }
1250
1251 /****************************************************************************
1252  Send a uloggoff.
1253 *****************************************************************************/
1254
1255 bool cli_ulogoff(struct cli_state *cli)
1256 {
1257         memset(cli->outbuf,'\0',smb_size);
1258         cli_set_message(cli->outbuf,2,0,True);
1259         SCVAL(cli->outbuf,smb_com,SMBulogoffX);
1260         cli_setup_packet(cli);
1261         SSVAL(cli->outbuf,smb_vwv0,0xFF);
1262         SSVAL(cli->outbuf,smb_vwv2,0);  /* no additional info */
1263
1264         cli_send_smb(cli);
1265         if (!cli_receive_smb(cli))
1266                 return False;
1267
1268         if (cli_is_error(cli)) {
1269                 return False;
1270         }
1271
1272         cli->vuid = -1;
1273         return True;
1274 }
1275
1276 /****************************************************************************
1277  Send a tconX.
1278 ****************************************************************************/
1279
1280 struct cli_tcon_andx_state {
1281         struct cli_state *cli;
1282         uint16_t vwv[4];
1283         struct iovec bytes;
1284 };
1285
1286 static void cli_tcon_andx_done(struct tevent_req *subreq);
1287
1288 struct tevent_req *cli_tcon_andx_create(TALLOC_CTX *mem_ctx,
1289                                         struct event_context *ev,
1290                                         struct cli_state *cli,
1291                                         const char *share, const char *dev,
1292                                         const char *pass, int passlen,
1293                                         struct tevent_req **psmbreq)
1294 {
1295         struct tevent_req *req, *subreq;
1296         struct cli_tcon_andx_state *state;
1297         fstring pword;
1298         uint16_t *vwv;
1299         char *tmp = NULL;
1300         uint8_t *bytes;
1301
1302         req = tevent_req_create(mem_ctx, &state, struct cli_tcon_andx_state);
1303         if (req == NULL) {
1304                 return NULL;
1305         }
1306         state->cli = cli;
1307         vwv = state->vwv;
1308
1309         fstrcpy(cli->share, share);
1310
1311         /* in user level security don't send a password now */
1312         if (cli->sec_mode & NEGOTIATE_SECURITY_USER_LEVEL) {
1313                 passlen = 1;
1314                 pass = "";
1315         } else if (pass == NULL) {
1316                 DEBUG(1, ("Server not using user level security and no "
1317                           "password supplied.\n"));
1318                 goto access_denied;
1319         }
1320
1321         if ((cli->sec_mode & NEGOTIATE_SECURITY_CHALLENGE_RESPONSE) &&
1322             *pass && passlen != 24) {
1323                 if (!lp_client_lanman_auth()) {
1324                         DEBUG(1, ("Server requested LANMAN password "
1325                                   "(share-level security) but "
1326                                   "'client lanman auth' is disabled\n"));
1327                         goto access_denied;
1328                 }
1329
1330                 /*
1331                  * Non-encrypted passwords - convert to DOS codepage before
1332                  * encryption.
1333                  */
1334                 passlen = 24;
1335                 SMBencrypt(pass, cli->secblob.data, (uchar *)pword);
1336         } else {
1337                 if((cli->sec_mode & (NEGOTIATE_SECURITY_USER_LEVEL
1338                                      |NEGOTIATE_SECURITY_CHALLENGE_RESPONSE))
1339                    == 0) {
1340                         if (!lp_client_plaintext_auth() && (*pass)) {
1341                                 DEBUG(1, ("Server requested plaintext "
1342                                           "password but 'client plaintext "
1343                                           "auth' is disabled\n"));
1344                                 goto access_denied;
1345                         }
1346
1347                         /*
1348                          * Non-encrypted passwords - convert to DOS codepage
1349                          * before using.
1350                          */
1351                         passlen = clistr_push(cli, pword, pass, sizeof(pword),
1352                                               STR_TERMINATE);
1353                         if (passlen == -1) {
1354                                 DEBUG(1, ("clistr_push(pword) failed\n"));
1355                                 goto access_denied;
1356                         }
1357                 } else {
1358                         if (passlen) {
1359                                 memcpy(pword, pass, passlen);
1360                         }
1361                 }
1362         }
1363
1364         SCVAL(vwv+0, 0, 0xFF);
1365         SCVAL(vwv+0, 1, 0);
1366         SSVAL(vwv+1, 0, 0);
1367         SSVAL(vwv+2, 0, TCONX_FLAG_EXTENDED_RESPONSE);
1368         SSVAL(vwv+3, 0, passlen);
1369
1370         if (passlen) {
1371                 bytes = (uint8_t *)talloc_memdup(state, pword, passlen);
1372         } else {
1373                 bytes = talloc_array(state, uint8_t, 0);
1374         }
1375
1376         /*
1377          * Add the sharename
1378          */
1379         tmp = talloc_asprintf_strupper_m(talloc_tos(), "\\\\%s\\%s",
1380                                          cli->desthost, share);
1381         if (tmp == NULL) {
1382                 TALLOC_FREE(req);
1383                 return NULL;
1384         }
1385         bytes = smb_bytes_push_str(bytes, cli_ucs2(cli), tmp, strlen(tmp)+1,
1386                                    NULL);
1387         TALLOC_FREE(tmp);
1388
1389         /*
1390          * Add the devicetype
1391          */
1392         tmp = talloc_strdup_upper(talloc_tos(), dev);
1393         if (tmp == NULL) {
1394                 TALLOC_FREE(req);
1395                 return NULL;
1396         }
1397         bytes = smb_bytes_push_str(bytes, false, tmp, strlen(tmp)+1, NULL);
1398         TALLOC_FREE(tmp);
1399
1400         if (bytes == NULL) {
1401                 TALLOC_FREE(req);
1402                 return NULL;
1403         }
1404
1405         state->bytes.iov_base = (void *)bytes;
1406         state->bytes.iov_len = talloc_get_size(bytes);
1407
1408         subreq = cli_smb_req_create(state, ev, cli, SMBtconX, 0, 4, vwv,
1409                                     1, &state->bytes);
1410         if (subreq == NULL) {
1411                 TALLOC_FREE(req);
1412                 return NULL;
1413         }
1414         tevent_req_set_callback(subreq, cli_tcon_andx_done, req);
1415         *psmbreq = subreq;
1416         return req;
1417
1418  access_denied:
1419         tevent_req_nterror(req, NT_STATUS_ACCESS_DENIED);
1420         return tevent_req_post(req, ev);
1421 }
1422
1423 struct tevent_req *cli_tcon_andx_send(TALLOC_CTX *mem_ctx,
1424                                       struct event_context *ev,
1425                                       struct cli_state *cli,
1426                                       const char *share, const char *dev,
1427                                       const char *pass, int passlen)
1428 {
1429         struct tevent_req *req, *subreq;
1430         NTSTATUS status;
1431
1432         req = cli_tcon_andx_create(mem_ctx, ev, cli, share, dev, pass, passlen,
1433                                    &subreq);
1434         if (req == NULL) {
1435                 return NULL;
1436         }
1437         status = cli_smb_req_send(subreq);
1438         if (!NT_STATUS_IS_OK(status)) {
1439                 tevent_req_nterror(req, status);
1440                 return tevent_req_post(req, ev);
1441         }
1442         return req;
1443 }
1444
1445 static void cli_tcon_andx_done(struct tevent_req *subreq)
1446 {
1447         struct tevent_req *req = tevent_req_callback_data(
1448                 subreq, struct tevent_req);
1449         struct cli_tcon_andx_state *state = tevent_req_data(
1450                 req, struct cli_tcon_andx_state);
1451         struct cli_state *cli = state->cli;
1452         char *inbuf = (char *)cli_smb_inbuf(subreq);
1453         uint8_t wct;
1454         uint16_t *vwv;
1455         uint32_t num_bytes;
1456         uint8_t *bytes;
1457         NTSTATUS status;
1458
1459         status = cli_smb_recv(subreq, 0, &wct, &vwv, &num_bytes, &bytes);
1460         if (!NT_STATUS_IS_OK(status)) {
1461                 TALLOC_FREE(subreq);
1462                 tevent_req_nterror(req, status);
1463                 return;
1464         }
1465
1466         clistr_pull(inbuf, cli->dev, bytes, sizeof(fstring), num_bytes,
1467                     STR_TERMINATE|STR_ASCII);
1468
1469         if ((cli->protocol >= PROTOCOL_NT1) && (num_bytes == 3)) {
1470                 /* almost certainly win95 - enable bug fixes */
1471                 cli->win95 = True;
1472         }
1473
1474         /*
1475          * Make sure that we have the optional support 16-bit field. WCT > 2.
1476          * Avoids issues when connecting to Win9x boxes sharing files
1477          */
1478
1479         cli->dfsroot = false;
1480
1481         if ((wct > 2) && (cli->protocol >= PROTOCOL_LANMAN2)) {
1482                 cli->dfsroot = ((SVAL(vwv+2, 0) & SMB_SHARE_IN_DFS) != 0);
1483         }
1484
1485         cli->cnum = SVAL(inbuf,smb_tid);
1486         tevent_req_done(req);
1487 }
1488
1489 NTSTATUS cli_tcon_andx_recv(struct tevent_req *req)
1490 {
1491         return tevent_req_simple_recv_ntstatus(req);
1492 }
1493
1494 NTSTATUS cli_tcon_andx(struct cli_state *cli, const char *share,
1495                        const char *dev, const char *pass, int passlen)
1496 {
1497         TALLOC_CTX *frame = talloc_stackframe();
1498         struct event_context *ev;
1499         struct tevent_req *req;
1500         NTSTATUS status = NT_STATUS_OK;
1501
1502         if (cli_has_async_calls(cli)) {
1503                 /*
1504                  * Can't use sync call while an async call is in flight
1505                  */
1506                 status = NT_STATUS_INVALID_PARAMETER;
1507                 goto fail;
1508         }
1509
1510         ev = event_context_init(frame);
1511         if (ev == NULL) {
1512                 status = NT_STATUS_NO_MEMORY;
1513                 goto fail;
1514         }
1515
1516         req = cli_tcon_andx_send(frame, ev, cli, share, dev, pass, passlen);
1517         if (req == NULL) {
1518                 status = NT_STATUS_NO_MEMORY;
1519                 goto fail;
1520         }
1521
1522         if (!tevent_req_poll(req, ev)) {
1523                 status = map_nt_error_from_unix(errno);
1524                 goto fail;
1525         }
1526
1527         status = cli_tcon_andx_recv(req);
1528  fail:
1529         TALLOC_FREE(frame);
1530         if (!NT_STATUS_IS_OK(status)) {
1531                 cli_set_error(cli, status);
1532         }
1533         return status;
1534 }
1535
1536 /****************************************************************************
1537  Send a tree disconnect.
1538 ****************************************************************************/
1539
1540 bool cli_tdis(struct cli_state *cli)
1541 {
1542         memset(cli->outbuf,'\0',smb_size);
1543         cli_set_message(cli->outbuf,0,0,True);
1544         SCVAL(cli->outbuf,smb_com,SMBtdis);
1545         SSVAL(cli->outbuf,smb_tid,cli->cnum);
1546         cli_setup_packet(cli);
1547
1548         cli_send_smb(cli);
1549         if (!cli_receive_smb(cli))
1550                 return False;
1551
1552         if (cli_is_error(cli)) {
1553                 return False;
1554         }
1555
1556         cli->cnum = -1;
1557         return True;
1558 }
1559
1560 /****************************************************************************
1561  Send a negprot command.
1562 ****************************************************************************/
1563
1564 void cli_negprot_sendsync(struct cli_state *cli)
1565 {
1566         char *p;
1567         int numprots;
1568
1569         if (cli->protocol < PROTOCOL_NT1)
1570                 cli->use_spnego = False;
1571
1572         memset(cli->outbuf,'\0',smb_size);
1573
1574         /* setup the protocol strings */
1575         cli_set_message(cli->outbuf,0,0,True);
1576
1577         p = smb_buf(cli->outbuf);
1578         for (numprots=0; numprots < ARRAY_SIZE(prots); numprots++) {
1579                 if (prots[numprots].prot > cli->protocol) {
1580                         break;
1581                 }
1582                 *p++ = 2;
1583                 p += clistr_push(cli, p, prots[numprots].name, -1, STR_TERMINATE);
1584         }
1585
1586         SCVAL(cli->outbuf,smb_com,SMBnegprot);
1587         cli_setup_bcc(cli, p);
1588         cli_setup_packet(cli);
1589
1590         SCVAL(smb_buf(cli->outbuf),0,2);
1591
1592         cli_send_smb(cli);
1593 }
1594
1595 /****************************************************************************
1596  Send a negprot command.
1597 ****************************************************************************/
1598
1599 struct cli_negprot_state {
1600         struct cli_state *cli;
1601 };
1602
1603 static void cli_negprot_done(struct tevent_req *subreq);
1604
1605 struct tevent_req *cli_negprot_send(TALLOC_CTX *mem_ctx,
1606                                     struct event_context *ev,
1607                                     struct cli_state *cli)
1608 {
1609         struct tevent_req *req, *subreq;
1610         struct cli_negprot_state *state;
1611         uint8_t *bytes = NULL;
1612         int numprots;
1613         uint16_t cnum;
1614
1615         req = tevent_req_create(mem_ctx, &state, struct cli_negprot_state);
1616         if (req == NULL) {
1617                 return NULL;
1618         }
1619         state->cli = cli;
1620
1621         if (cli->protocol < PROTOCOL_NT1)
1622                 cli->use_spnego = False;
1623
1624         /* setup the protocol strings */
1625         for (numprots=0; numprots < ARRAY_SIZE(prots); numprots++) {
1626                 uint8_t c = 2;
1627                 if (prots[numprots].prot > cli->protocol) {
1628                         break;
1629                 }
1630                 bytes = (uint8_t *)talloc_append_blob(
1631                         state, bytes, data_blob_const(&c, sizeof(c)));
1632                 if (tevent_req_nomem(bytes, req)) {
1633                         return tevent_req_post(req, ev);
1634                 }
1635                 bytes = smb_bytes_push_str(bytes, false,
1636                                            prots[numprots].name,
1637                                            strlen(prots[numprots].name)+1,
1638                                            NULL);
1639                 if (tevent_req_nomem(bytes, req)) {
1640                         return tevent_req_post(req, ev);
1641                 }
1642         }
1643
1644         cnum = cli->cnum;
1645
1646         cli->cnum = 0;
1647         subreq = cli_smb_send(state, ev, cli, SMBnegprot, 0, 0, NULL,
1648                               talloc_get_size(bytes), bytes);
1649         cli->cnum = cnum;
1650
1651         if (tevent_req_nomem(subreq, req)) {
1652                 return tevent_req_post(req, ev);
1653         }
1654         tevent_req_set_callback(subreq, cli_negprot_done, req);
1655         return req;
1656 }
1657
1658 static void cli_negprot_done(struct tevent_req *subreq)
1659 {
1660         struct tevent_req *req = tevent_req_callback_data(
1661                 subreq, struct tevent_req);
1662         struct cli_negprot_state *state = tevent_req_data(
1663                 req, struct cli_negprot_state);
1664         struct cli_state *cli = state->cli;
1665         uint8_t wct;
1666         uint16_t *vwv;
1667         uint32_t num_bytes;
1668         uint8_t *bytes;
1669         NTSTATUS status;
1670         uint16_t protnum;
1671
1672         status = cli_smb_recv(subreq, 1, &wct, &vwv, &num_bytes, &bytes);
1673         if (!NT_STATUS_IS_OK(status)) {
1674                 TALLOC_FREE(subreq);
1675                 tevent_req_nterror(req, status);
1676                 return;
1677         }
1678
1679         protnum = SVAL(vwv, 0);
1680
1681         if ((protnum >= ARRAY_SIZE(prots))
1682             || (prots[protnum].prot > cli->protocol)) {
1683                 tevent_req_nterror(req, NT_STATUS_INVALID_NETWORK_RESPONSE);
1684                 return;
1685         }
1686
1687         cli->protocol = prots[protnum].prot;
1688
1689         if ((cli->protocol < PROTOCOL_NT1) &&
1690             client_is_signing_mandatory(cli)) {
1691                 DEBUG(0,("cli_negprot: SMB signing is mandatory and the selected protocol level doesn't support it.\n"));
1692                 tevent_req_nterror(req, NT_STATUS_ACCESS_DENIED);
1693                 return;
1694         }
1695
1696         if (cli->protocol >= PROTOCOL_NT1) {    
1697                 struct timespec ts;
1698                 bool negotiated_smb_signing = false;
1699
1700                 /* NT protocol */
1701                 cli->sec_mode = CVAL(vwv + 1, 0);
1702                 cli->max_mux = SVAL(vwv + 1, 1);
1703                 cli->max_xmit = IVAL(vwv + 3, 1);
1704                 cli->sesskey = IVAL(vwv + 7, 1);
1705                 cli->serverzone = SVALS(vwv + 15, 1);
1706                 cli->serverzone *= 60;
1707                 /* this time arrives in real GMT */
1708                 ts = interpret_long_date(((char *)(vwv+11))+1);
1709                 cli->servertime = ts.tv_sec;
1710                 cli->secblob = data_blob(bytes, num_bytes);
1711                 cli->capabilities = IVAL(vwv + 9, 1);
1712                 if (cli->capabilities & CAP_RAW_MODE) {
1713                         cli->readbraw_supported = True;
1714                         cli->writebraw_supported = True;      
1715                 }
1716                 /* work out if they sent us a workgroup */
1717                 if (!(cli->capabilities & CAP_EXTENDED_SECURITY) &&
1718                     smb_buflen(cli->inbuf) > 8) {
1719                         clistr_pull(cli->inbuf, cli->server_domain,
1720                                     bytes+8, sizeof(cli->server_domain),
1721                                     num_bytes-8,
1722                                     STR_UNICODE|STR_NOALIGN);
1723                 }
1724
1725                 /*
1726                  * As signing is slow we only turn it on if either the client or
1727                  * the server require it. JRA.
1728                  */
1729
1730                 if (cli->sec_mode & NEGOTIATE_SECURITY_SIGNATURES_REQUIRED) {
1731                         /* Fail if server says signing is mandatory and we don't want to support it. */
1732                         if (!client_is_signing_allowed(cli)) {
1733                                 DEBUG(0,("cli_negprot: SMB signing is mandatory and we have disabled it.\n"));
1734                                 tevent_req_nterror(req,
1735                                                    NT_STATUS_ACCESS_DENIED);
1736                                 return;
1737                         }
1738                         negotiated_smb_signing = true;
1739                 } else if (client_is_signing_mandatory(cli) && client_is_signing_allowed(cli)) {
1740                         /* Fail if client says signing is mandatory and the server doesn't support it. */
1741                         if (!(cli->sec_mode & NEGOTIATE_SECURITY_SIGNATURES_ENABLED)) {
1742                                 DEBUG(1,("cli_negprot: SMB signing is mandatory and the server doesn't support it.\n"));
1743                                 tevent_req_nterror(req,
1744                                                    NT_STATUS_ACCESS_DENIED);
1745                                 return;
1746                         }
1747                         negotiated_smb_signing = true;
1748                 } else if (cli->sec_mode & NEGOTIATE_SECURITY_SIGNATURES_ENABLED) {
1749                         negotiated_smb_signing = true;
1750                 }
1751
1752                 if (negotiated_smb_signing) {
1753                         cli_set_signing_negotiated(cli);
1754                 }
1755
1756                 if (cli->capabilities & (CAP_LARGE_READX|CAP_LARGE_WRITEX)) {
1757                         SAFE_FREE(cli->outbuf);
1758                         SAFE_FREE(cli->inbuf);
1759                         cli->outbuf = (char *)SMB_MALLOC(CLI_SAMBA_MAX_LARGE_READX_SIZE+LARGE_WRITEX_HDR_SIZE+SAFETY_MARGIN);
1760                         cli->inbuf = (char *)SMB_MALLOC(CLI_SAMBA_MAX_LARGE_READX_SIZE+LARGE_WRITEX_HDR_SIZE+SAFETY_MARGIN);
1761                         cli->bufsize = CLI_SAMBA_MAX_LARGE_READX_SIZE + LARGE_WRITEX_HDR_SIZE;
1762                 }
1763
1764         } else if (cli->protocol >= PROTOCOL_LANMAN1) {
1765                 cli->use_spnego = False;
1766                 cli->sec_mode = SVAL(vwv + 1, 0);
1767                 cli->max_xmit = SVAL(vwv + 2, 0);
1768                 cli->max_mux = SVAL(vwv + 3, 0);
1769                 cli->sesskey = IVAL(vwv + 6, 0);
1770                 cli->serverzone = SVALS(vwv + 10, 0);
1771                 cli->serverzone *= 60;
1772                 /* this time is converted to GMT by make_unix_date */
1773                 cli->servertime = cli_make_unix_date(
1774                         cli, (char *)(vwv + 8));
1775                 cli->readbraw_supported = ((SVAL(vwv + 5, 0) & 0x1) != 0);
1776                 cli->writebraw_supported = ((SVAL(vwv + 5, 0) & 0x2) != 0);
1777                 cli->secblob = data_blob(bytes, num_bytes);
1778         } else {
1779                 /* the old core protocol */
1780                 cli->use_spnego = False;
1781                 cli->sec_mode = 0;
1782                 cli->serverzone = get_time_zone(time(NULL));
1783         }
1784
1785         cli->max_xmit = MIN(cli->max_xmit, CLI_BUFFER_SIZE);
1786
1787         /* a way to force ascii SMB */
1788         if (getenv("CLI_FORCE_ASCII"))
1789                 cli->capabilities &= ~CAP_UNICODE;
1790
1791         tevent_req_done(req);
1792 }
1793
1794 NTSTATUS cli_negprot_recv(struct tevent_req *req)
1795 {
1796         return tevent_req_simple_recv_ntstatus(req);
1797 }
1798
1799 NTSTATUS cli_negprot(struct cli_state *cli)
1800 {
1801         TALLOC_CTX *frame = talloc_stackframe();
1802         struct event_context *ev;
1803         struct tevent_req *req;
1804         NTSTATUS status = NT_STATUS_OK;
1805
1806         if (cli_has_async_calls(cli)) {
1807                 /*
1808                  * Can't use sync call while an async call is in flight
1809                  */
1810                 status = NT_STATUS_INVALID_PARAMETER;
1811                 goto fail;
1812         }
1813
1814         ev = event_context_init(frame);
1815         if (ev == NULL) {
1816                 status = NT_STATUS_NO_MEMORY;
1817                 goto fail;
1818         }
1819
1820         req = cli_negprot_send(frame, ev, cli);
1821         if (req == NULL) {
1822                 status = NT_STATUS_NO_MEMORY;
1823                 goto fail;
1824         }
1825
1826         if (!tevent_req_poll(req, ev)) {
1827                 status = map_nt_error_from_unix(errno);
1828                 goto fail;
1829         }
1830
1831         status = cli_negprot_recv(req);
1832  fail:
1833         TALLOC_FREE(frame);
1834         if (!NT_STATUS_IS_OK(status)) {
1835                 cli_set_error(cli, status);
1836         }
1837         return status;
1838 }
1839
1840 /****************************************************************************
1841  Send a session request. See rfc1002.txt 4.3 and 4.3.2.
1842 ****************************************************************************/
1843
1844 bool cli_session_request(struct cli_state *cli,
1845                          struct nmb_name *calling, struct nmb_name *called)
1846 {
1847         char *p;
1848         int len = 4;
1849         char *tmp;
1850
1851         /* 445 doesn't have session request */
1852         if (cli->port == 445)
1853                 return True;
1854
1855         memcpy(&(cli->calling), calling, sizeof(*calling));
1856         memcpy(&(cli->called ), called , sizeof(*called ));
1857
1858         /* put in the destination name */
1859
1860         tmp = name_mangle(talloc_tos(), cli->called.name,
1861                           cli->called.name_type);
1862         if (tmp == NULL) {
1863                 return false;
1864         }
1865
1866         p = cli->outbuf+len;
1867         memcpy(p, tmp, name_len(tmp));
1868         len += name_len(tmp);
1869         TALLOC_FREE(tmp);
1870
1871         /* and my name */
1872
1873         tmp = name_mangle(talloc_tos(), cli->calling.name,
1874                           cli->calling.name_type);
1875         if (tmp == NULL) {
1876                 return false;
1877         }
1878
1879         p = cli->outbuf+len;
1880         memcpy(p, tmp, name_len(tmp));
1881         len += name_len(tmp);
1882         TALLOC_FREE(tmp);
1883
1884         /* send a session request (RFC 1002) */
1885         /* setup the packet length
1886          * Remove four bytes from the length count, since the length
1887          * field in the NBT Session Service header counts the number
1888          * of bytes which follow.  The cli_send_smb() function knows
1889          * about this and accounts for those four bytes.
1890          * CRH.
1891          */
1892         len -= 4;
1893         _smb_setlen(cli->outbuf,len);
1894         SCVAL(cli->outbuf,0,0x81);
1895
1896         cli_send_smb(cli);
1897         DEBUG(5,("Sent session request\n"));
1898
1899         if (!cli_receive_smb(cli))
1900                 return False;
1901
1902         if (CVAL(cli->inbuf,0) == 0x84) {
1903                 /* C. Hoch  9/14/95 Start */
1904                 /* For information, here is the response structure.
1905                  * We do the byte-twiddling to for portability.
1906                 struct RetargetResponse{
1907                 unsigned char type;
1908                 unsigned char flags;
1909                 int16 length;
1910                 int32 ip_addr;
1911                 int16 port;
1912                 };
1913                 */
1914                 uint16_t port = (CVAL(cli->inbuf,8)<<8)+CVAL(cli->inbuf,9);
1915                 struct in_addr dest_ip;
1916                 NTSTATUS status;
1917
1918                 /* SESSION RETARGET */
1919                 putip((char *)&dest_ip,cli->inbuf+4);
1920                 in_addr_to_sockaddr_storage(&cli->dest_ss, dest_ip);
1921
1922                 status = open_socket_out(&cli->dest_ss, port,
1923                                          LONG_CONNECT_TIMEOUT, &cli->fd);
1924                 if (!NT_STATUS_IS_OK(status)) {
1925                         return False;
1926                 }
1927
1928                 DEBUG(3,("Retargeted\n"));
1929
1930                 set_socket_options(cli->fd, lp_socket_options());
1931
1932                 /* Try again */
1933                 {
1934                         static int depth;
1935                         bool ret;
1936                         if (depth > 4) {
1937                                 DEBUG(0,("Retarget recursion - failing\n"));
1938                                 return False;
1939                         }
1940                         depth++;
1941                         ret = cli_session_request(cli, calling, called);
1942                         depth--;
1943                         return ret;
1944                 }
1945         } /* C. Hoch 9/14/95 End */
1946
1947         if (CVAL(cli->inbuf,0) != 0x82) {
1948                 /* This is the wrong place to put the error... JRA. */
1949                 cli->rap_error = CVAL(cli->inbuf,4);
1950                 return False;
1951         }
1952         return(True);
1953 }
1954
1955 struct fd_struct {
1956         int fd;
1957 };
1958
1959 static void smb_sock_connected(struct tevent_req *req)
1960 {
1961         struct fd_struct *pfd = tevent_req_callback_data(
1962                 req, struct fd_struct);
1963         int fd;
1964         NTSTATUS status;
1965
1966         status = open_socket_out_defer_recv(req, &fd);
1967         if (NT_STATUS_IS_OK(status)) {
1968                 pfd->fd = fd;
1969         }
1970 }
1971
1972 static NTSTATUS open_smb_socket(const struct sockaddr_storage *pss,
1973                                 uint16_t *port, int timeout, int *pfd)
1974 {
1975         struct event_context *ev;
1976         struct tevent_req *r139, *r445;
1977         struct fd_struct *fd139, *fd445;
1978         NTSTATUS status = NT_STATUS_NO_MEMORY;
1979
1980         if (*port != 0) {
1981                 return open_socket_out(pss, *port, timeout, pfd);
1982         }
1983
1984         ev = event_context_init(talloc_tos());
1985         if (ev == NULL) {
1986                 return NT_STATUS_NO_MEMORY;
1987         }
1988
1989         fd139 = talloc(ev, struct fd_struct);
1990         if (fd139 == NULL) {
1991                 goto done;
1992         }
1993         fd139->fd = -1;
1994
1995         fd445 = talloc(ev, struct fd_struct);
1996         if (fd445 == NULL) {
1997                 goto done;
1998         }
1999         fd445->fd = -1;
2000
2001         r445 = open_socket_out_defer_send(ev, ev, timeval_set(0, 0),
2002                                           pss, 445, timeout);
2003         r139 = open_socket_out_defer_send(ev, ev, timeval_set(0, 3000),
2004                                           pss, 139, timeout);
2005         if ((r445 == NULL) || (r139 == NULL)) {
2006                 goto done;
2007         }
2008         tevent_req_set_callback(r445, smb_sock_connected, fd445);
2009         tevent_req_set_callback(r139, smb_sock_connected, fd139);
2010
2011         while ((fd445->fd == -1) && (fd139->fd == -1)
2012                && (tevent_req_is_in_progress(r139)
2013                    || tevent_req_is_in_progress(r445))) {
2014                 event_loop_once(ev);
2015         }
2016
2017         if ((fd139->fd != -1) && (fd445->fd != -1)) {
2018                 close(fd139->fd);
2019                 fd139->fd = -1;
2020         }
2021
2022         if (fd445->fd != -1) {
2023                 *port = 445;
2024                 *pfd = fd445->fd;
2025                 status = NT_STATUS_OK;
2026                 goto done;
2027         }
2028         if (fd139->fd != -1) {
2029                 *port = 139;
2030                 *pfd = fd139->fd;
2031                 status = NT_STATUS_OK;
2032                 goto done;
2033         }
2034
2035         status = open_socket_out_defer_recv(r445, &fd445->fd);
2036  done:
2037         TALLOC_FREE(ev);
2038         return status;
2039 }
2040
2041 /****************************************************************************
2042  Open the client sockets.
2043 ****************************************************************************/
2044
2045 NTSTATUS cli_connect(struct cli_state *cli,
2046                 const char *host,
2047                 struct sockaddr_storage *dest_ss)
2048
2049 {
2050         int name_type = 0x20;
2051         TALLOC_CTX *frame = talloc_stackframe();
2052         unsigned int num_addrs = 0;
2053         unsigned int i = 0;
2054         struct sockaddr_storage *ss_arr = NULL;
2055         char *p = NULL;
2056
2057         /* reasonable default hostname */
2058         if (!host) {
2059                 host = STAR_SMBSERVER;
2060         }
2061
2062         fstrcpy(cli->desthost, host);
2063
2064         /* allow hostnames of the form NAME#xx and do a netbios lookup */
2065         if ((p = strchr(cli->desthost, '#'))) {
2066                 name_type = strtol(p+1, NULL, 16);
2067                 *p = 0;
2068         }
2069
2070         if (!dest_ss || is_zero_addr((struct sockaddr *)dest_ss)) {
2071                 NTSTATUS status =resolve_name_list(frame,
2072                                         cli->desthost,
2073                                         name_type,
2074                                         &ss_arr,
2075                                         &num_addrs);
2076                 if (!NT_STATUS_IS_OK(status)) {
2077                         TALLOC_FREE(frame);
2078                         return NT_STATUS_BAD_NETWORK_NAME;
2079                 }
2080         } else {
2081                 num_addrs = 1;
2082                 ss_arr = TALLOC_P(frame, struct sockaddr_storage);
2083                 if (!ss_arr) {
2084                         TALLOC_FREE(frame);
2085                         return NT_STATUS_NO_MEMORY;
2086                 }
2087                 *ss_arr = *dest_ss;
2088         }
2089
2090         for (i = 0; i < num_addrs; i++) {
2091                 cli->dest_ss = ss_arr[i];
2092                 if (getenv("LIBSMB_PROG")) {
2093                         cli->fd = sock_exec(getenv("LIBSMB_PROG"));
2094                 } else {
2095                         uint16_t port = cli->port;
2096                         NTSTATUS status;
2097                         status = open_smb_socket(&cli->dest_ss, &port,
2098                                                  cli->timeout, &cli->fd);
2099                         if (NT_STATUS_IS_OK(status)) {
2100                                 cli->port = port;
2101                         }
2102                 }
2103                 if (cli->fd == -1) {
2104                         char addr[INET6_ADDRSTRLEN];
2105                         print_sockaddr(addr, sizeof(addr), &ss_arr[i]);
2106                         DEBUG(2,("Error connecting to %s (%s)\n",
2107                                  dest_ss?addr:host,strerror(errno)));
2108                 } else {
2109                         /* Exit from loop on first connection. */
2110                         break;
2111                 }
2112         }
2113
2114         if (cli->fd == -1) {
2115                 TALLOC_FREE(frame);
2116                 return map_nt_error_from_unix(errno);
2117         }
2118
2119         if (dest_ss) {
2120                 *dest_ss = cli->dest_ss;
2121         }
2122
2123         set_socket_options(cli->fd, lp_socket_options());
2124
2125         TALLOC_FREE(frame);
2126         return NT_STATUS_OK;
2127 }
2128
2129 /**
2130    establishes a connection to after the negprot. 
2131    @param output_cli A fully initialised cli structure, non-null only on success
2132    @param dest_host The netbios name of the remote host
2133    @param dest_ss (optional) The the destination IP, NULL for name based lookup
2134    @param port (optional) The destination port (0 for default)
2135    @param retry bool. Did this connection fail with a retryable error ?
2136
2137 */
2138 NTSTATUS cli_start_connection(struct cli_state **output_cli, 
2139                               const char *my_name, 
2140                               const char *dest_host, 
2141                               struct sockaddr_storage *dest_ss, int port,
2142                               int signing_state, int flags,
2143                               bool *retry) 
2144 {
2145         NTSTATUS nt_status;
2146         struct nmb_name calling;
2147         struct nmb_name called;
2148         struct cli_state *cli;
2149         struct sockaddr_storage ss;
2150
2151         if (retry)
2152                 *retry = False;
2153
2154         if (!my_name) 
2155                 my_name = global_myname();
2156
2157         if (!(cli = cli_initialise_ex(signing_state))) {
2158                 return NT_STATUS_NO_MEMORY;
2159         }
2160
2161         make_nmb_name(&calling, my_name, 0x0);
2162         make_nmb_name(&called , dest_host, 0x20);
2163
2164         cli_set_port(cli, port);
2165         cli_set_timeout(cli, 10000); /* 10 seconds. */
2166
2167         if (dest_ss) {
2168                 ss = *dest_ss;
2169         } else {
2170                 zero_sockaddr(&ss);
2171         }
2172
2173 again:
2174
2175         DEBUG(3,("Connecting to host=%s\n", dest_host));
2176
2177         nt_status = cli_connect(cli, dest_host, &ss);
2178         if (!NT_STATUS_IS_OK(nt_status)) {
2179                 char addr[INET6_ADDRSTRLEN];
2180                 print_sockaddr(addr, sizeof(addr), &ss);
2181                 DEBUG(1,("cli_start_connection: failed to connect to %s (%s). Error %s\n",
2182                          nmb_namestr(&called), addr, nt_errstr(nt_status) ));
2183                 cli_shutdown(cli);
2184                 return nt_status;
2185         }
2186
2187         if (retry)
2188                 *retry = True;
2189
2190         if (!cli_session_request(cli, &calling, &called)) {
2191                 char *p;
2192                 DEBUG(1,("session request to %s failed (%s)\n",
2193                          called.name, cli_errstr(cli)));
2194                 if ((p=strchr(called.name, '.')) && !is_ipaddress(called.name)) {
2195                         *p = 0;
2196                         goto again;
2197                 }
2198                 if (strcmp(called.name, STAR_SMBSERVER)) {
2199                         make_nmb_name(&called , STAR_SMBSERVER, 0x20);
2200                         goto again;
2201                 }
2202                 return NT_STATUS_BAD_NETWORK_NAME;
2203         }
2204
2205         if (flags & CLI_FULL_CONNECTION_DONT_SPNEGO)
2206                 cli->use_spnego = False;
2207         else if (flags & CLI_FULL_CONNECTION_USE_KERBEROS)
2208                 cli->use_kerberos = True;
2209
2210         if ((flags & CLI_FULL_CONNECTION_FALLBACK_AFTER_KERBEROS) &&
2211              cli->use_kerberos) {
2212                 cli->fallback_after_kerberos = true;
2213         }
2214
2215         nt_status = cli_negprot(cli);
2216         if (!NT_STATUS_IS_OK(nt_status)) {
2217                 DEBUG(1, ("failed negprot: %s\n", nt_errstr(nt_status)));
2218                 cli_shutdown(cli);
2219                 return nt_status;
2220         }
2221
2222         *output_cli = cli;
2223         return NT_STATUS_OK;
2224 }
2225
2226
2227 /**
2228    establishes a connection right up to doing tconX, password specified.
2229    @param output_cli A fully initialised cli structure, non-null only on success
2230    @param dest_host The netbios name of the remote host
2231    @param dest_ip (optional) The the destination IP, NULL for name based lookup
2232    @param port (optional) The destination port (0 for default)
2233    @param service (optional) The share to make the connection to.  Should be 'unqualified' in any way.
2234    @param service_type The 'type' of serivice. 
2235    @param user Username, unix string
2236    @param domain User's domain
2237    @param password User's password, unencrypted unix string.
2238    @param retry bool. Did this connection fail with a retryable error ?
2239 */
2240
2241 NTSTATUS cli_full_connection(struct cli_state **output_cli, 
2242                              const char *my_name, 
2243                              const char *dest_host, 
2244                              struct sockaddr_storage *dest_ss, int port,
2245                              const char *service, const char *service_type,
2246                              const char *user, const char *domain, 
2247                              const char *password, int flags,
2248                              int signing_state,
2249                              bool *retry) 
2250 {
2251         NTSTATUS nt_status;
2252         struct cli_state *cli = NULL;
2253         int pw_len = password ? strlen(password)+1 : 0;
2254
2255         *output_cli = NULL;
2256
2257         if (password == NULL) {
2258                 password = "";
2259         }
2260
2261         nt_status = cli_start_connection(&cli, my_name, dest_host,
2262                                          dest_ss, port, signing_state,
2263                                          flags, retry);
2264
2265         if (!NT_STATUS_IS_OK(nt_status)) {
2266                 return nt_status;
2267         }
2268
2269         cli->use_oplocks = ((flags & CLI_FULL_CONNECTION_OPLOCKS) != 0);
2270         cli->use_level_II_oplocks =
2271                 ((flags & CLI_FULL_CONNECTION_LEVEL_II_OPLOCKS) != 0);
2272
2273         nt_status = cli_session_setup(cli, user, password, pw_len, password,
2274                                       pw_len, domain);
2275         if (!NT_STATUS_IS_OK(nt_status)) {
2276
2277                 if (!(flags & CLI_FULL_CONNECTION_ANONYMOUS_FALLBACK)) {
2278                         DEBUG(1,("failed session setup with %s\n",
2279                                  nt_errstr(nt_status)));
2280                         cli_shutdown(cli);
2281                         return nt_status;
2282                 }
2283
2284                 nt_status = cli_session_setup(cli, "", "", 0, "", 0, domain);
2285                 if (!NT_STATUS_IS_OK(nt_status)) {
2286                         DEBUG(1,("anonymous failed session setup with %s\n",
2287                                  nt_errstr(nt_status)));
2288                         cli_shutdown(cli);
2289                         return nt_status;
2290                 }
2291         }
2292
2293         if (service) {
2294                 nt_status = cli_tcon_andx(cli, service, service_type, password,
2295                                           pw_len);
2296                 if (!NT_STATUS_IS_OK(nt_status)) {
2297                         DEBUG(1,("failed tcon_X with %s\n", nt_errstr(nt_status)));
2298                         cli_shutdown(cli);
2299                         if (NT_STATUS_IS_OK(nt_status)) {
2300                                 nt_status = NT_STATUS_UNSUCCESSFUL;
2301                         }
2302                         return nt_status;
2303                 }
2304         }
2305
2306         nt_status = cli_init_creds(cli, user, domain, password);
2307         if (!NT_STATUS_IS_OK(nt_status)) {
2308                 cli_shutdown(cli);
2309                 return nt_status;
2310         }
2311
2312         *output_cli = cli;
2313         return NT_STATUS_OK;
2314 }
2315
2316 /****************************************************************************
2317  Attempt a NetBIOS session request, falling back to *SMBSERVER if needed.
2318 ****************************************************************************/
2319
2320 bool attempt_netbios_session_request(struct cli_state **ppcli, const char *srchost, const char *desthost,
2321                                      struct sockaddr_storage *pdest_ss)
2322 {
2323         struct nmb_name calling, called;
2324
2325         make_nmb_name(&calling, srchost, 0x0);
2326
2327         /*
2328          * If the called name is an IP address
2329          * then use *SMBSERVER immediately.
2330          */
2331
2332         if(is_ipaddress(desthost)) {
2333                 make_nmb_name(&called, STAR_SMBSERVER, 0x20);
2334         } else {
2335                 make_nmb_name(&called, desthost, 0x20);
2336         }
2337
2338         if (!cli_session_request(*ppcli, &calling, &called)) {
2339                 NTSTATUS status;
2340                 struct nmb_name smbservername;
2341
2342                 make_nmb_name(&smbservername, STAR_SMBSERVER, 0x20);
2343
2344                 /*
2345                  * If the name wasn't *SMBSERVER then
2346                  * try with *SMBSERVER if the first name fails.
2347                  */
2348
2349                 if (nmb_name_equal(&called, &smbservername)) {
2350
2351                         /*
2352                          * The name used was *SMBSERVER, don't bother with another name.
2353                          */
2354
2355                         DEBUG(0,("attempt_netbios_session_request: %s rejected the session for name *SMBSERVER \
2356 with error %s.\n", desthost, cli_errstr(*ppcli) ));
2357                         return False;
2358                 }
2359
2360                 /* Try again... */
2361                 cli_shutdown(*ppcli);
2362
2363                 *ppcli = cli_initialise();
2364                 if (!*ppcli) {
2365                         /* Out of memory... */
2366                         return False;
2367                 }
2368
2369                 status = cli_connect(*ppcli, desthost, pdest_ss);
2370                 if (!NT_STATUS_IS_OK(status) ||
2371                                 !cli_session_request(*ppcli, &calling, &smbservername)) {
2372                         DEBUG(0,("attempt_netbios_session_request: %s rejected the session for \
2373 name *SMBSERVER with error %s\n", desthost, cli_errstr(*ppcli) ));
2374                         return False;
2375                 }
2376         }
2377
2378         return True;
2379 }
2380
2381 /****************************************************************************
2382  Send an old style tcon.
2383 ****************************************************************************/
2384 NTSTATUS cli_raw_tcon(struct cli_state *cli, 
2385                       const char *service, const char *pass, const char *dev,
2386                       uint16 *max_xmit, uint16 *tid)
2387 {
2388         char *p;
2389
2390         if (!lp_client_plaintext_auth() && (*pass)) {
2391                 DEBUG(1, ("Server requested plaintext password but 'client "
2392                           "plaintext auth' is disabled\n"));
2393                 return NT_STATUS_ACCESS_DENIED;
2394         }
2395
2396         memset(cli->outbuf,'\0',smb_size);
2397         memset(cli->inbuf,'\0',smb_size);
2398
2399         cli_set_message(cli->outbuf, 0, 0, True);
2400         SCVAL(cli->outbuf,smb_com,SMBtcon);
2401         cli_setup_packet(cli);
2402
2403         p = smb_buf(cli->outbuf);
2404         *p++ = 4; p += clistr_push(cli, p, service, -1, STR_TERMINATE | STR_NOALIGN);
2405         *p++ = 4; p += clistr_push(cli, p, pass, -1, STR_TERMINATE | STR_NOALIGN);
2406         *p++ = 4; p += clistr_push(cli, p, dev, -1, STR_TERMINATE | STR_NOALIGN);
2407
2408         cli_setup_bcc(cli, p);
2409
2410         cli_send_smb(cli);
2411         if (!cli_receive_smb(cli)) {
2412                 return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
2413         }
2414
2415         if (cli_is_error(cli)) {
2416                 return cli_nt_error(cli);
2417         }
2418
2419         *max_xmit = SVAL(cli->inbuf, smb_vwv0);
2420         *tid = SVAL(cli->inbuf, smb_vwv1);
2421
2422         return NT_STATUS_OK;
2423 }
2424
2425 /* Return a cli_state pointing at the IPC$ share for the given server */
2426
2427 struct cli_state *get_ipc_connect(char *server,
2428                                 struct sockaddr_storage *server_ss,
2429                                 const struct user_auth_info *user_info)
2430 {
2431         struct cli_state *cli;
2432         NTSTATUS nt_status;
2433         uint32_t flags = CLI_FULL_CONNECTION_ANONYMOUS_FALLBACK;
2434
2435         if (user_info->use_kerberos) {
2436                 flags |= CLI_FULL_CONNECTION_USE_KERBEROS;
2437         }
2438
2439         nt_status = cli_full_connection(&cli, NULL, server, server_ss, 0, "IPC$", "IPC", 
2440                                         user_info->username ? user_info->username : "",
2441                                         lp_workgroup(),
2442                                         user_info->password ? user_info->password : "",
2443                                         flags,
2444                                         Undefined, NULL);
2445
2446         if (NT_STATUS_IS_OK(nt_status)) {
2447                 return cli;
2448         } else if (is_ipaddress(server)) {
2449             /* windows 9* needs a correct NMB name for connections */
2450             fstring remote_name;
2451
2452             if (name_status_find("*", 0, 0, server_ss, remote_name)) {
2453                 cli = get_ipc_connect(remote_name, server_ss, user_info);
2454                 if (cli)
2455                     return cli;
2456             }
2457         }
2458         return NULL;
2459 }
2460
2461 /*
2462  * Given the IP address of a master browser on the network, return its
2463  * workgroup and connect to it.
2464  *
2465  * This function is provided to allow additional processing beyond what
2466  * get_ipc_connect_master_ip_bcast() does, e.g. to retrieve the list of master
2467  * browsers and obtain each master browsers' list of domains (in case the
2468  * first master browser is recently on the network and has not yet
2469  * synchronized with other master browsers and therefore does not yet have the
2470  * entire network browse list)
2471  */
2472
2473 struct cli_state *get_ipc_connect_master_ip(TALLOC_CTX *ctx,
2474                                 struct ip_service *mb_ip,
2475                                 const struct user_auth_info *user_info,
2476                                 char **pp_workgroup_out)
2477 {
2478         char addr[INET6_ADDRSTRLEN];
2479         fstring name;
2480         struct cli_state *cli;
2481         struct sockaddr_storage server_ss;
2482
2483         *pp_workgroup_out = NULL;
2484
2485         print_sockaddr(addr, sizeof(addr), &mb_ip->ss);
2486         DEBUG(99, ("Looking up name of master browser %s\n",
2487                    addr));
2488
2489         /*
2490          * Do a name status query to find out the name of the master browser.
2491          * We use <01><02>__MSBROWSE__<02>#01 if *#00 fails because a domain
2492          * master browser will not respond to a wildcard query (or, at least,
2493          * an NT4 server acting as the domain master browser will not).
2494          *
2495          * We might be able to use ONLY the query on MSBROWSE, but that's not
2496          * yet been tested with all Windows versions, so until it is, leave
2497          * the original wildcard query as the first choice and fall back to
2498          * MSBROWSE if the wildcard query fails.
2499          */
2500         if (!name_status_find("*", 0, 0x1d, &mb_ip->ss, name) &&
2501             !name_status_find(MSBROWSE, 1, 0x1d, &mb_ip->ss, name)) {
2502
2503                 DEBUG(99, ("Could not retrieve name status for %s\n",
2504                            addr));
2505                 return NULL;
2506         }
2507
2508         if (!find_master_ip(name, &server_ss)) {
2509                 DEBUG(99, ("Could not find master ip for %s\n", name));
2510                 return NULL;
2511         }
2512
2513         *pp_workgroup_out = talloc_strdup(ctx, name);
2514
2515         DEBUG(4, ("found master browser %s, %s\n", name, addr));
2516
2517         print_sockaddr(addr, sizeof(addr), &server_ss);
2518         cli = get_ipc_connect(addr, &server_ss, user_info);
2519
2520         return cli;
2521 }
2522
2523 /*
2524  * Return the IP address and workgroup of a master browser on the network, and
2525  * connect to it.
2526  */
2527
2528 struct cli_state *get_ipc_connect_master_ip_bcast(TALLOC_CTX *ctx,
2529                                         const struct user_auth_info *user_info,
2530                                         char **pp_workgroup_out)
2531 {
2532         struct ip_service *ip_list;
2533         struct cli_state *cli;
2534         int i, count;
2535
2536         *pp_workgroup_out = NULL;
2537
2538         DEBUG(99, ("Do broadcast lookup for workgroups on local network\n"));
2539
2540         /* Go looking for workgroups by broadcasting on the local network */
2541
2542         if (!NT_STATUS_IS_OK(name_resolve_bcast(MSBROWSE, 1, &ip_list,
2543                                                 &count))) {
2544                 DEBUG(99, ("No master browsers responded\n"));
2545                 return False;
2546         }
2547
2548         for (i = 0; i < count; i++) {
2549                 char addr[INET6_ADDRSTRLEN];
2550                 print_sockaddr(addr, sizeof(addr), &ip_list[i].ss);
2551                 DEBUG(99, ("Found master browser %s\n", addr));
2552
2553                 cli = get_ipc_connect_master_ip(ctx, &ip_list[i],
2554                                 user_info, pp_workgroup_out);
2555                 if (cli)
2556                         return(cli);
2557         }
2558
2559         return NULL;
2560 }