r2466: Fix memleak found by sean.chandler@verizon.net.
[amitay/samba.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 2 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, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21
22 #define NO_SYSLOG
23
24 #include "includes.h"
25
26
27 static const struct {
28         int prot;
29         const char *name;
30 } prots[] = {
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,"Samba"},
38         {PROTOCOL_NT1,"NT LANMAN 1.0"},
39         {PROTOCOL_NT1,"NT LM 0.12"},
40         {-1,NULL}
41 };
42
43 /**
44  * Set the user session key for a connection
45  * @param cli The cli structure to add it too
46  * @param session_key The session key used.  (A copy of this is taken for the cli struct)
47  *
48  */
49
50 static void cli_set_session_key (struct cli_state *cli, const DATA_BLOB session_key) 
51 {
52         cli->user_session_key = data_blob(session_key.data, session_key.length);
53 }
54
55 /****************************************************************************
56  Do an old lanman2 style session setup.
57 ****************************************************************************/
58
59 static BOOL cli_session_setup_lanman2(struct cli_state *cli, const char *user, 
60                                       const char *pass, size_t passlen, const char *workgroup)
61 {
62         DATA_BLOB session_key = data_blob(NULL, 0);
63         DATA_BLOB lm_response = data_blob(NULL, 0);
64         fstring pword;
65         char *p;
66
67         if (passlen > sizeof(pword)-1)
68                 return False;
69
70         /* LANMAN servers predate NT status codes and Unicode and ignore those 
71            smb flags so we must disable the corresponding default capabilities  
72            that would otherwise cause the Unicode and NT Status flags to be
73            set (and even returned by the server) */
74
75         cli->capabilities &= ~(CAP_UNICODE | CAP_STATUS32);
76
77         /* if in share level security then don't send a password now */
78         if (!(cli->sec_mode & NEGOTIATE_SECURITY_USER_LEVEL))
79                 passlen = 0;
80
81         if (passlen > 0 && (cli->sec_mode & NEGOTIATE_SECURITY_CHALLENGE_RESPONSE) && passlen != 24) {
82                 /* Encrypted mode needed, and non encrypted password supplied. */
83                 lm_response = data_blob(NULL, 24);
84                 if (!SMBencrypt(pass, cli->secblob.data,(uchar *)lm_response.data)) {
85                         DEBUG(1, ("Password is > 14 chars in length, and is therefore incompatible with Lanman authentication\n"));
86                         return False;
87                 }
88         } else if ((cli->sec_mode & NEGOTIATE_SECURITY_CHALLENGE_RESPONSE) && passlen == 24) {
89                 /* Encrypted mode needed, and encrypted password supplied. */
90                 lm_response = data_blob(pass, passlen);
91         } else if (passlen > 0) {
92                 /* Plaintext mode needed, assume plaintext supplied. */
93                 passlen = clistr_push(cli, pword, pass, sizeof(pword), STR_TERMINATE);
94                 lm_response = data_blob(pass, passlen);
95         }
96
97         /* send a session setup command */
98         memset(cli->outbuf,'\0',smb_size);
99         set_message(cli->outbuf,10, 0, True);
100         SCVAL(cli->outbuf,smb_com,SMBsesssetupX);
101         cli_setup_packet(cli);
102         
103         SCVAL(cli->outbuf,smb_vwv0,0xFF);
104         SSVAL(cli->outbuf,smb_vwv2,cli->max_xmit);
105         SSVAL(cli->outbuf,smb_vwv3,2);
106         SSVAL(cli->outbuf,smb_vwv4,1);
107         SIVAL(cli->outbuf,smb_vwv5,cli->sesskey);
108         SSVAL(cli->outbuf,smb_vwv7,lm_response.length);
109
110         p = smb_buf(cli->outbuf);
111         memcpy(p,lm_response.data,lm_response.length);
112         p += lm_response.length;
113         p += clistr_push(cli, p, user, -1, STR_TERMINATE|STR_UPPER);
114         p += clistr_push(cli, p, workgroup, -1, STR_TERMINATE|STR_UPPER);
115         p += clistr_push(cli, p, "Unix", -1, STR_TERMINATE);
116         p += clistr_push(cli, p, "Samba", -1, STR_TERMINATE);
117         cli_setup_bcc(cli, p);
118
119         cli_send_smb(cli);
120         if (!cli_receive_smb(cli))
121                 return False;
122
123         show_msg(cli->inbuf);
124
125         if (cli_is_error(cli))
126                 return False;
127         
128         /* use the returned vuid from now on */
129         cli->vuid = SVAL(cli->inbuf,smb_uid);   
130         fstrcpy(cli->user_name, user);
131
132         if (session_key.data) {
133                 /* Have plaintext orginal */
134                 cli_set_session_key(cli, session_key);
135         }
136
137         return True;
138 }
139
140 /****************************************************************************
141  Work out suitable capabilities to offer the server.
142 ****************************************************************************/
143
144 static uint32 cli_session_setup_capabilities(struct cli_state *cli)
145 {
146         uint32 capabilities = CAP_NT_SMBS;
147
148         if (!cli->force_dos_errors)
149                 capabilities |= CAP_STATUS32;
150
151         if (cli->use_level_II_oplocks)
152                 capabilities |= CAP_LEVEL_II_OPLOCKS;
153
154         if (cli->capabilities & CAP_UNICODE)
155                 capabilities |= CAP_UNICODE;
156
157         if (cli->capabilities & CAP_LARGE_FILES)
158                 capabilities |= CAP_LARGE_FILES;
159
160         return capabilities;
161 }
162
163 /****************************************************************************
164  Do a NT1 guest session setup.
165 ****************************************************************************/
166
167 static BOOL cli_session_setup_guest(struct cli_state *cli)
168 {
169         char *p;
170         uint32 capabilities = cli_session_setup_capabilities(cli);
171
172         set_message(cli->outbuf,13,0,True);
173         SCVAL(cli->outbuf,smb_com,SMBsesssetupX);
174         cli_setup_packet(cli);
175                         
176         SCVAL(cli->outbuf,smb_vwv0,0xFF);
177         SSVAL(cli->outbuf,smb_vwv2,CLI_BUFFER_SIZE);
178         SSVAL(cli->outbuf,smb_vwv3,2);
179         SSVAL(cli->outbuf,smb_vwv4,cli->pid);
180         SIVAL(cli->outbuf,smb_vwv5,cli->sesskey);
181         SSVAL(cli->outbuf,smb_vwv7,0);
182         SSVAL(cli->outbuf,smb_vwv8,0);
183         SIVAL(cli->outbuf,smb_vwv11,capabilities); 
184         p = smb_buf(cli->outbuf);
185         p += clistr_push(cli, p, "", -1, STR_TERMINATE); /* username */
186         p += clistr_push(cli, p, "", -1, STR_TERMINATE); /* workgroup */
187         p += clistr_push(cli, p, "Unix", -1, STR_TERMINATE);
188         p += clistr_push(cli, p, "Samba", -1, STR_TERMINATE);
189         cli_setup_bcc(cli, p);
190
191         cli_send_smb(cli);
192         if (!cli_receive_smb(cli))
193               return False;
194         
195         show_msg(cli->inbuf);
196         
197         if (cli_is_error(cli))
198                 return False;
199
200         cli->vuid = SVAL(cli->inbuf,smb_uid);
201
202         p = smb_buf(cli->inbuf);
203         p += clistr_pull(cli, cli->server_os, p, sizeof(fstring), -1, STR_TERMINATE);
204         p += clistr_pull(cli, cli->server_type, p, sizeof(fstring), -1, STR_TERMINATE);
205         p += clistr_pull(cli, cli->server_domain, p, sizeof(fstring), -1, STR_TERMINATE);
206
207         fstrcpy(cli->user_name, "");
208
209         return True;
210 }
211
212 /****************************************************************************
213  Do a NT1 plaintext session setup.
214 ****************************************************************************/
215
216 static BOOL cli_session_setup_plaintext(struct cli_state *cli, const char *user, 
217                                         const char *pass, const char *workgroup)
218 {
219         uint32 capabilities = cli_session_setup_capabilities(cli);
220         char *p;
221         fstring lanman;
222         
223         fstr_sprintf( lanman, "Samba %s", SAMBA_VERSION_STRING);
224
225         set_message(cli->outbuf,13,0,True);
226         SCVAL(cli->outbuf,smb_com,SMBsesssetupX);
227         cli_setup_packet(cli);
228                         
229         SCVAL(cli->outbuf,smb_vwv0,0xFF);
230         SSVAL(cli->outbuf,smb_vwv2,CLI_BUFFER_SIZE);
231         SSVAL(cli->outbuf,smb_vwv3,2);
232         SSVAL(cli->outbuf,smb_vwv4,cli->pid);
233         SIVAL(cli->outbuf,smb_vwv5,cli->sesskey);
234         SSVAL(cli->outbuf,smb_vwv8,0);
235         SIVAL(cli->outbuf,smb_vwv11,capabilities); 
236         p = smb_buf(cli->outbuf);
237         
238         /* check wether to send the ASCII or UNICODE version of the password */
239         
240         if ( (capabilities & CAP_UNICODE) == 0 ) {
241                 p += clistr_push(cli, p, pass, -1, STR_TERMINATE); /* password */
242                 SSVAL(cli->outbuf,smb_vwv7,PTR_DIFF(p, smb_buf(cli->outbuf)));
243         }
244         else { 
245                 p += clistr_push(cli, p, pass, -1, STR_UNICODE|STR_TERMINATE); /* unicode password */
246                 SSVAL(cli->outbuf,smb_vwv8,PTR_DIFF(p, smb_buf(cli->outbuf)));  
247         }
248         
249         p += clistr_push(cli, p, user, -1, STR_TERMINATE); /* username */
250         p += clistr_push(cli, p, workgroup, -1, STR_TERMINATE); /* workgroup */
251         p += clistr_push(cli, p, "Unix", -1, STR_TERMINATE);
252         p += clistr_push(cli, p, lanman, -1, STR_TERMINATE);
253         cli_setup_bcc(cli, p);
254
255         cli_send_smb(cli);
256         if (!cli_receive_smb(cli))
257               return False;
258         
259         show_msg(cli->inbuf);
260         
261         if (cli_is_error(cli))
262                 return False;
263
264         cli->vuid = SVAL(cli->inbuf,smb_uid);
265         p = smb_buf(cli->inbuf);
266         p += clistr_pull(cli, cli->server_os, p, sizeof(fstring), -1, STR_TERMINATE);
267         p += clistr_pull(cli, cli->server_type, p, sizeof(fstring), -1, STR_TERMINATE);
268         p += clistr_pull(cli, cli->server_domain, p, sizeof(fstring), -1, STR_TERMINATE);
269         fstrcpy(cli->user_name, user);
270
271         return True;
272 }
273
274 /****************************************************************************
275    do a NT1 NTLM/LM encrypted session setup - for when extended security
276    is not negotiated.
277    @param cli client state to create do session setup on
278    @param user username
279    @param pass *either* cleartext password (passlen !=24) or LM response.
280    @param ntpass NT response, implies ntpasslen >=24, implies pass is not clear
281    @param workgroup The user's domain.
282 ****************************************************************************/
283
284 static BOOL cli_session_setup_nt1(struct cli_state *cli, const char *user, 
285                                   const char *pass, size_t passlen,
286                                   const char *ntpass, size_t ntpasslen,
287                                   const char *workgroup)
288 {
289         uint32 capabilities = cli_session_setup_capabilities(cli);
290         DATA_BLOB lm_response = data_blob(NULL, 0);
291         DATA_BLOB nt_response = data_blob(NULL, 0);
292         DATA_BLOB session_key = data_blob(NULL, 0);
293         BOOL ret = False;
294         char *p;
295
296         if (passlen == 0) {
297                 /* do nothing - guest login */
298         } else if (passlen != 24) {
299                 if (lp_client_ntlmv2_auth()) {
300                         DATA_BLOB server_chal;
301                         DATA_BLOB names_blob;
302                         server_chal = data_blob(cli->secblob.data, MIN(cli->secblob.length, 8)); 
303
304                         /* note that the 'workgroup' here is a best guess - we don't know
305                            the server's domain at this point.  The 'server name' is also
306                            dodgy... 
307                         */
308                         names_blob = NTLMv2_generate_names_blob(cli->called.name, workgroup);
309
310                         if (!SMBNTLMv2encrypt(user, workgroup, pass, &server_chal, 
311                                               &names_blob,
312                                               &lm_response, &nt_response, &session_key)) {
313                                 data_blob_free(&names_blob);
314                                 data_blob_free(&server_chal);
315                                 return False;
316                         }
317                         data_blob_free(&names_blob);
318                         data_blob_free(&server_chal);
319
320                 } else {
321                         uchar nt_hash[16];
322                         E_md4hash(pass, nt_hash);
323
324 #ifdef LANMAN_ONLY
325                         nt_response = data_blob(NULL, 0);
326 #else
327                         nt_response = data_blob(NULL, 24);
328                         SMBNTencrypt(pass,cli->secblob.data,nt_response.data);
329 #endif
330                         /* non encrypted password supplied. Ignore ntpass. */
331                         if (lp_client_lanman_auth()) {
332                                 lm_response = data_blob(NULL, 24);
333                                 if (!SMBencrypt(pass,cli->secblob.data, lm_response.data)) {
334                                         /* Oops, the LM response is invalid, just put 
335                                            the NT response there instead */
336                                         data_blob_free(&lm_response);
337                                         lm_response = data_blob(nt_response.data, nt_response.length);
338                                 }
339                         } else {
340                                 /* LM disabled, place NT# in LM field instead */
341                                 lm_response = data_blob(nt_response.data, nt_response.length);
342                         }
343
344                         session_key = data_blob(NULL, 16);
345 #ifdef LANMAN_ONLY
346                         E_deshash(pass, session_key.data);
347                         memset(&session_key.data[8], '\0', 8);
348 #else
349                         SMBsesskeygen_ntv1(nt_hash, NULL, session_key.data);
350 #endif
351                 }
352 #ifdef LANMAN_ONLY
353                 cli_simple_set_signing(cli, session_key, lm_response); 
354 #else
355                 cli_simple_set_signing(cli, session_key, nt_response); 
356 #endif
357         } else {
358                 /* pre-encrypted password supplied.  Only used for 
359                    security=server, can't do
360                    signing because we don't have original key */
361
362                 lm_response = data_blob(pass, passlen);
363                 nt_response = data_blob(ntpass, ntpasslen);
364         }
365
366         /* send a session setup command */
367         memset(cli->outbuf,'\0',smb_size);
368
369         set_message(cli->outbuf,13,0,True);
370         SCVAL(cli->outbuf,smb_com,SMBsesssetupX);
371         cli_setup_packet(cli);
372                         
373         SCVAL(cli->outbuf,smb_vwv0,0xFF);
374         SSVAL(cli->outbuf,smb_vwv2,CLI_BUFFER_SIZE);
375         SSVAL(cli->outbuf,smb_vwv3,2);
376         SSVAL(cli->outbuf,smb_vwv4,cli->pid);
377         SIVAL(cli->outbuf,smb_vwv5,cli->sesskey);
378         SSVAL(cli->outbuf,smb_vwv7,lm_response.length);
379         SSVAL(cli->outbuf,smb_vwv8,nt_response.length);
380         SIVAL(cli->outbuf,smb_vwv11,capabilities); 
381         p = smb_buf(cli->outbuf);
382         if (lm_response.length) {
383                 memcpy(p,lm_response.data, lm_response.length); p += lm_response.length;
384         }
385         if (nt_response.length) {
386                 memcpy(p,nt_response.data, nt_response.length); p += nt_response.length;
387         }
388         p += clistr_push(cli, p, user, -1, STR_TERMINATE);
389
390         /* Upper case here might help some NTLMv2 implementations */
391         p += clistr_push(cli, p, workgroup, -1, STR_TERMINATE|STR_UPPER);
392         p += clistr_push(cli, p, "Unix", -1, STR_TERMINATE);
393         p += clistr_push(cli, p, "Samba", -1, STR_TERMINATE);
394         cli_setup_bcc(cli, p);
395
396         if (!cli_send_smb(cli) || !cli_receive_smb(cli)) {
397                 ret = False;
398                 goto end;
399         }
400
401         /* show_msg(cli->inbuf); */
402
403         if (cli_is_error(cli)) {
404                 ret = False;
405                 goto end;
406         }
407
408         /* use the returned vuid from now on */
409         cli->vuid = SVAL(cli->inbuf,smb_uid);
410         
411         p = smb_buf(cli->inbuf);
412         p += clistr_pull(cli, cli->server_os, p, sizeof(fstring), -1, STR_TERMINATE);
413         p += clistr_pull(cli, cli->server_type, p, sizeof(fstring), -1, STR_TERMINATE);
414         p += clistr_pull(cli, cli->server_domain, p, sizeof(fstring), -1, STR_TERMINATE);
415
416         fstrcpy(cli->user_name, user);
417
418         if (session_key.data) {
419                 /* Have plaintext orginal */
420                 cli_set_session_key(cli, session_key);
421         }
422
423         ret = True;
424 end:    
425         data_blob_free(&lm_response);
426         data_blob_free(&nt_response);
427         data_blob_free(&session_key);
428         return ret;
429 }
430
431 /****************************************************************************
432  Send a extended security session setup blob
433 ****************************************************************************/
434
435 static BOOL cli_session_setup_blob_send(struct cli_state *cli, DATA_BLOB blob)
436 {
437         uint32 capabilities = cli_session_setup_capabilities(cli);
438         char *p;
439
440         capabilities |= CAP_EXTENDED_SECURITY;
441
442         /* send a session setup command */
443         memset(cli->outbuf,'\0',smb_size);
444
445         set_message(cli->outbuf,12,0,True);
446         SCVAL(cli->outbuf,smb_com,SMBsesssetupX);
447
448         cli_setup_packet(cli);
449                         
450         SCVAL(cli->outbuf,smb_vwv0,0xFF);
451         SSVAL(cli->outbuf,smb_vwv2,CLI_BUFFER_SIZE);
452         SSVAL(cli->outbuf,smb_vwv3,2);
453         SSVAL(cli->outbuf,smb_vwv4,1);
454         SIVAL(cli->outbuf,smb_vwv5,0);
455         SSVAL(cli->outbuf,smb_vwv7,blob.length);
456         SIVAL(cli->outbuf,smb_vwv10,capabilities); 
457         p = smb_buf(cli->outbuf);
458         memcpy(p, blob.data, blob.length);
459         p += blob.length;
460         p += clistr_push(cli, p, "Unix", -1, STR_TERMINATE);
461         p += clistr_push(cli, p, "Samba", -1, STR_TERMINATE);
462         cli_setup_bcc(cli, p);
463         return cli_send_smb(cli);
464 }
465
466 /****************************************************************************
467  Send a extended security session setup blob, returning a reply blob.
468 ****************************************************************************/
469
470 static DATA_BLOB cli_session_setup_blob_receive(struct cli_state *cli)
471 {
472         DATA_BLOB blob2 = data_blob(NULL, 0);
473         char *p;
474         size_t len;
475
476         if (!cli_receive_smb(cli))
477                 return blob2;
478
479         show_msg(cli->inbuf);
480
481         if (cli_is_error(cli) && !NT_STATUS_EQUAL(cli_nt_error(cli),
482                                                   NT_STATUS_MORE_PROCESSING_REQUIRED)) {
483                 return blob2;
484         }
485         
486         /* use the returned vuid from now on */
487         cli->vuid = SVAL(cli->inbuf,smb_uid);
488         
489         p = smb_buf(cli->inbuf);
490
491         blob2 = data_blob(p, SVAL(cli->inbuf, smb_vwv3));
492
493         p += blob2.length;
494         p += clistr_pull(cli, cli->server_os, p, sizeof(fstring), -1, STR_TERMINATE);
495
496         /* w2k with kerberos doesn't properly null terminate this field */
497         len = smb_buflen(cli->inbuf) - PTR_DIFF(p, smb_buf(cli->inbuf));
498         p += clistr_pull(cli, cli->server_type, p, sizeof(fstring), len, 0);
499
500         return blob2;
501 }
502
503 #ifdef HAVE_KRB5
504
505 /****************************************************************************
506  Send a extended security session setup blob, returning a reply blob.
507 ****************************************************************************/
508
509 static DATA_BLOB cli_session_setup_blob(struct cli_state *cli, DATA_BLOB blob)
510 {
511         DATA_BLOB blob2 = data_blob(NULL, 0);
512         if (!cli_session_setup_blob_send(cli, blob)) {
513                 return blob2;
514         }
515                 
516         return cli_session_setup_blob_receive(cli);
517 }
518
519 /****************************************************************************
520  Use in-memory credentials cache
521 ****************************************************************************/
522
523 static void use_in_memory_ccache(void) {
524         setenv(KRB5_ENV_CCNAME, "MEMORY:cliconnect", 1);
525 }
526
527 /****************************************************************************
528  Do a spnego/kerberos encrypted session setup.
529 ****************************************************************************/
530
531 static ADS_STATUS cli_session_setup_kerberos(struct cli_state *cli, const char *principal, const char *workgroup)
532 {
533         DATA_BLOB blob2, negTokenTarg;
534         DATA_BLOB session_key_krb5;
535         DATA_BLOB null_blob = data_blob(NULL, 0);
536         int rc;
537
538         DEBUG(2,("Doing kerberos session setup\n"));
539
540         /* generate the encapsulated kerberos5 ticket */
541         rc = spnego_gen_negTokenTarg(principal, 0, &negTokenTarg, &session_key_krb5);
542
543         if (rc) {
544                 DEBUG(1, ("spnego_gen_negTokenTarg failed: %s\n", error_message(rc)));
545                 return ADS_ERROR_KRB5(rc);
546         }
547
548 #if 0
549         file_save("negTokenTarg.dat", negTokenTarg.data, negTokenTarg.length);
550 #endif
551
552         cli_simple_set_signing(cli, session_key_krb5, null_blob); 
553                         
554         blob2 = cli_session_setup_blob(cli, negTokenTarg);
555
556         /* we don't need this blob for kerberos */
557         data_blob_free(&blob2);
558
559         cli_set_session_key(cli, session_key_krb5);
560
561         data_blob_free(&negTokenTarg);
562         data_blob_free(&session_key_krb5);
563
564         if (cli_is_error(cli)) {
565                 if (NT_STATUS_IS_OK(cli_nt_error(cli))) {
566                         return ADS_ERROR_NT(NT_STATUS_UNSUCCESSFUL);
567                 }
568         } 
569         return ADS_ERROR_NT(cli_nt_error(cli));
570 }
571 #endif  /* HAVE_KRB5 */
572
573
574 /****************************************************************************
575  Do a spnego/NTLMSSP encrypted session setup.
576 ****************************************************************************/
577
578 static NTSTATUS cli_session_setup_ntlmssp(struct cli_state *cli, const char *user, 
579                                           const char *pass, const char *domain)
580 {
581         struct ntlmssp_state *ntlmssp_state;
582         NTSTATUS nt_status;
583         int turn = 1;
584         DATA_BLOB msg1;
585         DATA_BLOB blob = data_blob(NULL, 0);
586         DATA_BLOB blob_in = data_blob(NULL, 0);
587         DATA_BLOB blob_out = data_blob(NULL, 0);
588
589         cli_temp_set_signing(cli);
590
591         if (!NT_STATUS_IS_OK(nt_status = ntlmssp_client_start(&ntlmssp_state))) {
592                 return nt_status;
593         }
594
595         if (!NT_STATUS_IS_OK(nt_status = ntlmssp_set_username(ntlmssp_state, user))) {
596                 return nt_status;
597         }
598         if (!NT_STATUS_IS_OK(nt_status = ntlmssp_set_domain(ntlmssp_state, domain))) {
599                 return nt_status;
600         }
601         if (!NT_STATUS_IS_OK(nt_status = ntlmssp_set_password(ntlmssp_state, pass))) {
602                 return nt_status;
603         }
604
605         do {
606                 nt_status = ntlmssp_update(ntlmssp_state, 
607                                                   blob_in, &blob_out);
608                 data_blob_free(&blob_in);
609                 if (NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
610                         if (turn == 1) {
611                                 /* and wrap it in a SPNEGO wrapper */
612                                 msg1 = gen_negTokenInit(OID_NTLMSSP, blob_out);
613                         } else {
614                                 /* wrap it in SPNEGO */
615                                 msg1 = spnego_gen_auth(blob_out);
616                         }
617                 
618                         /* now send that blob on its way */
619                         if (!cli_session_setup_blob_send(cli, msg1)) {
620                                 DEBUG(3, ("Failed to send NTLMSSP/SPNEGO blob to server!\n"));
621                                 nt_status = NT_STATUS_UNSUCCESSFUL;
622                         } else {
623                                 data_blob_free(&msg1);
624                                 
625                                 blob = cli_session_setup_blob_receive(cli);
626                                 
627                                 nt_status = cli_nt_error(cli);
628                                 if (cli_is_error(cli) && NT_STATUS_IS_OK(nt_status)) {
629                                         if (cli->smb_rw_error == READ_BAD_SIG) {
630                                                 nt_status = NT_STATUS_ACCESS_DENIED;
631                                         } else {
632                                                 nt_status = NT_STATUS_UNSUCCESSFUL;
633                                         }
634                                 }
635                         }
636                 }
637                 
638                 if (!blob.length) {
639                         if (NT_STATUS_IS_OK(nt_status)) {
640                                 nt_status = NT_STATUS_UNSUCCESSFUL;
641                         }
642                 } else if ((turn == 1) && 
643                            NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) {
644                         DATA_BLOB tmp_blob = data_blob(NULL, 0);
645                         /* the server might give us back two challenges */
646                         if (!spnego_parse_challenge(blob, &blob_in, 
647                                                     &tmp_blob)) {
648                                 DEBUG(3,("Failed to parse challenges\n"));
649                                 nt_status = NT_STATUS_INVALID_PARAMETER;
650                         }
651                         data_blob_free(&tmp_blob);
652                 } else {
653                         if (!spnego_parse_auth_response(blob, nt_status, 
654                                                         &blob_in)) {
655                                 DEBUG(3,("Failed to parse auth response\n"));
656                                 if (NT_STATUS_IS_OK(nt_status) 
657                                     || NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED)) 
658                                         nt_status = NT_STATUS_INVALID_PARAMETER;
659                         }
660                 }
661                 data_blob_free(&blob);
662                 data_blob_free(&blob_out);
663                 turn++;
664         } while (NT_STATUS_EQUAL(nt_status, NT_STATUS_MORE_PROCESSING_REQUIRED));
665
666         if (NT_STATUS_IS_OK(nt_status)) {
667
668                 DATA_BLOB key = data_blob(ntlmssp_state->session_key.data,
669                                           ntlmssp_state->session_key.length);
670                 DATA_BLOB null_blob = data_blob(NULL, 0);
671                 BOOL res;
672
673                 fstrcpy(cli->server_domain, ntlmssp_state->server_domain);
674                 cli_set_session_key(cli, ntlmssp_state->session_key);
675
676                 res = cli_simple_set_signing(cli, key, null_blob);
677
678                 data_blob_free(&key);
679
680                 if (res) {
681                         
682                         /* 'resign' the last message, so we get the right sequence numbers
683                            for checking the first reply from the server */
684                         cli_calculate_sign_mac(cli);
685                         
686                         if (!cli_check_sign_mac(cli)) {
687                                 nt_status = NT_STATUS_ACCESS_DENIED;
688                         }
689                 }
690         }
691
692         /* we have a reference conter on ntlmssp_state, if we are signing
693            then the state will be kept by the signing engine */
694
695         ntlmssp_end(&ntlmssp_state);
696
697         return nt_status;
698 }
699
700 /****************************************************************************
701  Do a spnego encrypted session setup.
702 ****************************************************************************/
703
704 ADS_STATUS cli_session_setup_spnego(struct cli_state *cli, const char *user, 
705                               const char *pass, const char *domain)
706 {
707         char *principal;
708         char *OIDs[ASN1_MAX_OIDS];
709         int i;
710         BOOL got_kerberos_mechanism = False;
711         DATA_BLOB blob;
712
713         DEBUG(3,("Doing spnego session setup (blob length=%lu)\n", (unsigned long)cli->secblob.length));
714
715         /* the server might not even do spnego */
716         if (cli->secblob.length <= 16) {
717                 DEBUG(3,("server didn't supply a full spnego negprot\n"));
718                 goto ntlmssp;
719         }
720
721 #if 0
722         file_save("negprot.dat", cli->secblob.data, cli->secblob.length);
723 #endif
724
725         /* there is 16 bytes of GUID before the real spnego packet starts */
726         blob = data_blob(cli->secblob.data+16, cli->secblob.length-16);
727
728         /* the server sent us the first part of the SPNEGO exchange in the negprot 
729            reply */
730         if (!spnego_parse_negTokenInit(blob, OIDs, &principal)) {
731                 data_blob_free(&blob);
732                 return ADS_ERROR_NT(NT_STATUS_INVALID_PARAMETER);
733         }
734         data_blob_free(&blob);
735
736         /* make sure the server understands kerberos */
737         for (i=0;OIDs[i];i++) {
738                 DEBUG(3,("got OID=%s\n", OIDs[i]));
739                 if (strcmp(OIDs[i], OID_KERBEROS5_OLD) == 0 ||
740                     strcmp(OIDs[i], OID_KERBEROS5) == 0) {
741                         got_kerberos_mechanism = True;
742                 }
743                 free(OIDs[i]);
744         }
745         DEBUG(3,("got principal=%s\n", principal));
746
747         fstrcpy(cli->user_name, user);
748
749 #ifdef HAVE_KRB5
750         /* If password is set we reauthenticate to kerberos server
751          * and do not store results */
752
753         if (got_kerberos_mechanism && cli->use_kerberos) {
754                 ADS_STATUS rc;
755
756                 if (pass && *pass) {
757                         int ret;
758                         
759                         use_in_memory_ccache();
760                         ret = kerberos_kinit_password(user, pass, 0 /* no time correction for now */, NULL);
761                         
762                         if (ret){
763                                 SAFE_FREE(principal);
764                                 DEBUG(0, ("Kinit failed: %s\n", error_message(ret)));
765                                 return ADS_ERROR_KRB5(ret);
766                         }
767                 }
768                 
769                 rc = cli_session_setup_kerberos(cli, principal, domain);
770                 SAFE_FREE(principal);
771                 return rc;
772         }
773 #endif
774
775         SAFE_FREE(principal);
776
777 ntlmssp:
778
779         return ADS_ERROR_NT(cli_session_setup_ntlmssp(cli, user, pass, domain));
780 }
781
782 /****************************************************************************
783  Send a session setup. The username and workgroup is in UNIX character
784  format and must be converted to DOS codepage format before sending. If the
785  password is in plaintext, the same should be done.
786 ****************************************************************************/
787
788 BOOL cli_session_setup(struct cli_state *cli, 
789                        const char *user, 
790                        const char *pass, int passlen,
791                        const char *ntpass, int ntpasslen,
792                        const char *workgroup)
793 {
794         char *p;
795         fstring user2;
796
797         /* allow for workgroups as part of the username */
798         fstrcpy(user2, user);
799         if ((p=strchr_m(user2,'\\')) || (p=strchr_m(user2,'/')) ||
800             (p=strchr_m(user2,*lp_winbind_separator()))) {
801                 *p = 0;
802                 user = p+1;
803                 workgroup = user2;
804         }
805
806         if (cli->protocol < PROTOCOL_LANMAN1)
807                 return True;
808
809         /* now work out what sort of session setup we are going to
810            do. I have split this into separate functions to make the
811            flow a bit easier to understand (tridge) */
812
813         /* if its an older server then we have to use the older request format */
814
815         if (cli->protocol < PROTOCOL_NT1) {
816                 if (!lp_client_lanman_auth() && passlen != 24 && (*pass)) {
817                         DEBUG(1, ("Server requested LM password but 'client lanman auth'"
818                                   " is disabled\n"));
819                         return False;
820                 }
821
822                 if ((cli->sec_mode & NEGOTIATE_SECURITY_CHALLENGE_RESPONSE) == 0 &&
823                     !lp_client_plaintext_auth() && (*pass)) {
824                         DEBUG(1, ("Server requested plaintext password but 'client use plaintext auth'"
825                                   " is disabled\n"));
826                         return False;
827                 }
828
829                 return cli_session_setup_lanman2(cli, user, pass, passlen, workgroup);
830         }
831
832         /* if no user is supplied then we have to do an anonymous connection.
833            passwords are ignored */
834
835         if (!user || !*user)
836                 return cli_session_setup_guest(cli);
837
838         /* if the server is share level then send a plaintext null
839            password at this point. The password is sent in the tree
840            connect */
841
842         if ((cli->sec_mode & NEGOTIATE_SECURITY_USER_LEVEL) == 0) 
843                 return cli_session_setup_plaintext(cli, user, "", workgroup);
844
845         /* if the server doesn't support encryption then we have to use 
846            plaintext. The second password is ignored */
847
848         if ((cli->sec_mode & NEGOTIATE_SECURITY_CHALLENGE_RESPONSE) == 0) {
849                 if (!lp_client_plaintext_auth() && (*pass)) {
850                         DEBUG(1, ("Server requested plaintext password but 'client use plaintext auth'"
851                                   " is disabled\n"));
852                         return False;
853                 }
854                 return cli_session_setup_plaintext(cli, user, pass, workgroup);
855         }
856
857         /* if the server supports extended security then use SPNEGO */
858
859         if (cli->capabilities & CAP_EXTENDED_SECURITY) {
860                 ADS_STATUS status = cli_session_setup_spnego(cli, user, pass, workgroup);
861                 if (!ADS_ERR_OK(status)) {
862                         DEBUG(3, ("SPNEGO login failed: %s\n", ads_errstr(status)));
863                         return False;
864                 }
865                 return True;
866         }
867
868         /* otherwise do a NT1 style session setup */
869
870         return cli_session_setup_nt1(cli, user, 
871                                      pass, passlen, ntpass, ntpasslen,
872                                      workgroup);        
873 }
874
875 /****************************************************************************
876  Send a uloggoff.
877 *****************************************************************************/
878
879 BOOL cli_ulogoff(struct cli_state *cli)
880 {
881         memset(cli->outbuf,'\0',smb_size);
882         set_message(cli->outbuf,2,0,True);
883         SCVAL(cli->outbuf,smb_com,SMBulogoffX);
884         cli_setup_packet(cli);
885         SSVAL(cli->outbuf,smb_vwv0,0xFF);
886         SSVAL(cli->outbuf,smb_vwv2,0);  /* no additional info */
887
888         cli_send_smb(cli);
889         if (!cli_receive_smb(cli))
890                 return False;
891
892         return !cli_is_error(cli);
893 }
894
895 /****************************************************************************
896  Send a tconX.
897 ****************************************************************************/
898 BOOL cli_send_tconX(struct cli_state *cli, 
899                     const char *share, const char *dev, const char *pass, int passlen)
900 {
901         fstring fullshare, pword;
902         char *p;
903         memset(cli->outbuf,'\0',smb_size);
904         memset(cli->inbuf,'\0',smb_size);
905
906         fstrcpy(cli->share, share);
907
908         /* in user level security don't send a password now */
909         if (cli->sec_mode & NEGOTIATE_SECURITY_USER_LEVEL) {
910                 passlen = 1;
911                 pass = "";
912         }
913
914         if ((cli->sec_mode & NEGOTIATE_SECURITY_CHALLENGE_RESPONSE) && *pass && passlen != 24) {
915                 if (!lp_client_lanman_auth()) {
916                         DEBUG(1, ("Server requested LANMAN password (share-level security) but 'client use lanman auth'"
917                                   " is disabled\n"));
918                         return False;
919                 }
920
921                 /*
922                  * Non-encrypted passwords - convert to DOS codepage before encryption.
923                  */
924                 passlen = 24;
925                 SMBencrypt(pass,cli->secblob.data,(uchar *)pword);
926         } else {
927                 if((cli->sec_mode & (NEGOTIATE_SECURITY_USER_LEVEL|NEGOTIATE_SECURITY_CHALLENGE_RESPONSE)) == 0) {
928                         if (!lp_client_plaintext_auth() && (*pass)) {
929                                 DEBUG(1, ("Server requested plaintext password but 'client use plaintext auth'"
930                                           " is disabled\n"));
931                                 return False;
932                         }
933
934                         /*
935                          * Non-encrypted passwords - convert to DOS codepage before using.
936                          */
937                         passlen = clistr_push(cli, pword, pass, sizeof(pword), STR_TERMINATE);
938                         
939                 } else {
940                         memcpy(pword, pass, passlen);
941                 }
942         }
943
944         slprintf(fullshare, sizeof(fullshare)-1,
945                  "\\\\%s\\%s", cli->desthost, share);
946
947         set_message(cli->outbuf,4, 0, True);
948         SCVAL(cli->outbuf,smb_com,SMBtconX);
949         cli_setup_packet(cli);
950
951         SSVAL(cli->outbuf,smb_vwv0,0xFF);
952         SSVAL(cli->outbuf,smb_vwv3,passlen);
953
954         p = smb_buf(cli->outbuf);
955         memcpy(p,pword,passlen);
956         p += passlen;
957         p += clistr_push(cli, p, fullshare, -1, STR_TERMINATE |STR_UPPER);
958         p += clistr_push(cli, p, dev, -1, STR_TERMINATE |STR_UPPER | STR_ASCII);
959
960         cli_setup_bcc(cli, p);
961
962         cli_send_smb(cli);
963         if (!cli_receive_smb(cli))
964                 return False;
965
966         if (cli_is_error(cli))
967                 return False;
968
969         clistr_pull(cli, cli->dev, smb_buf(cli->inbuf), sizeof(fstring), -1, STR_TERMINATE|STR_ASCII);
970
971         if (cli->protocol >= PROTOCOL_NT1 &&
972             smb_buflen(cli->inbuf) == 3) {
973                 /* almost certainly win95 - enable bug fixes */
974                 cli->win95 = True;
975         }
976
977         cli->cnum = SVAL(cli->inbuf,smb_tid);
978         return True;
979 }
980
981 /****************************************************************************
982  Send a tree disconnect.
983 ****************************************************************************/
984
985 BOOL cli_tdis(struct cli_state *cli)
986 {
987         memset(cli->outbuf,'\0',smb_size);
988         set_message(cli->outbuf,0,0,True);
989         SCVAL(cli->outbuf,smb_com,SMBtdis);
990         SSVAL(cli->outbuf,smb_tid,cli->cnum);
991         cli_setup_packet(cli);
992         
993         cli_send_smb(cli);
994         if (!cli_receive_smb(cli))
995                 return False;
996         
997         return !cli_is_error(cli);
998 }
999
1000 /****************************************************************************
1001  Send a negprot command.
1002 ****************************************************************************/
1003
1004 void cli_negprot_send(struct cli_state *cli)
1005 {
1006         char *p;
1007         int numprots;
1008
1009         if (cli->protocol < PROTOCOL_NT1)
1010                 cli->use_spnego = False;
1011
1012         memset(cli->outbuf,'\0',smb_size);
1013
1014         /* setup the protocol strings */
1015         set_message(cli->outbuf,0,0,True);
1016
1017         p = smb_buf(cli->outbuf);
1018         for (numprots=0;
1019              prots[numprots].name && prots[numprots].prot<=cli->protocol;
1020              numprots++) {
1021                 *p++ = 2;
1022                 p += clistr_push(cli, p, prots[numprots].name, -1, STR_TERMINATE);
1023         }
1024
1025         SCVAL(cli->outbuf,smb_com,SMBnegprot);
1026         cli_setup_bcc(cli, p);
1027         cli_setup_packet(cli);
1028
1029         SCVAL(smb_buf(cli->outbuf),0,2);
1030
1031         cli_send_smb(cli);
1032 }
1033
1034 /****************************************************************************
1035  Send a negprot command.
1036 ****************************************************************************/
1037
1038 BOOL cli_negprot(struct cli_state *cli)
1039 {
1040         char *p;
1041         int numprots;
1042         int plength;
1043
1044         if (cli->protocol < PROTOCOL_NT1)
1045                 cli->use_spnego = False;
1046
1047         memset(cli->outbuf,'\0',smb_size);
1048
1049         /* setup the protocol strings */
1050         for (plength=0,numprots=0;
1051              prots[numprots].name && prots[numprots].prot<=cli->protocol;
1052              numprots++)
1053                 plength += strlen(prots[numprots].name)+2;
1054     
1055         set_message(cli->outbuf,0,plength,True);
1056
1057         p = smb_buf(cli->outbuf);
1058         for (numprots=0;
1059              prots[numprots].name && prots[numprots].prot<=cli->protocol;
1060              numprots++) {
1061                 *p++ = 2;
1062                 p += clistr_push(cli, p, prots[numprots].name, -1, STR_TERMINATE);
1063         }
1064
1065         SCVAL(cli->outbuf,smb_com,SMBnegprot);
1066         cli_setup_packet(cli);
1067
1068         SCVAL(smb_buf(cli->outbuf),0,2);
1069
1070         cli_send_smb(cli);
1071         if (!cli_receive_smb(cli))
1072                 return False;
1073
1074         show_msg(cli->inbuf);
1075
1076         if (cli_is_error(cli) ||
1077             ((int)SVAL(cli->inbuf,smb_vwv0) >= numprots)) {
1078                 return(False);
1079         }
1080
1081         cli->protocol = prots[SVAL(cli->inbuf,smb_vwv0)].prot;  
1082
1083         if ((cli->protocol < PROTOCOL_NT1) && cli->sign_info.mandatory_signing) {
1084                 DEBUG(0,("cli_negprot: SMB signing is mandatory and the selected protocol level doesn't support it.\n"));
1085                 return False;
1086         }
1087
1088         if (cli->protocol >= PROTOCOL_NT1) {    
1089                 /* NT protocol */
1090                 cli->sec_mode = CVAL(cli->inbuf,smb_vwv1);
1091                 cli->max_mux = SVAL(cli->inbuf, smb_vwv1+1);
1092                 cli->max_xmit = IVAL(cli->inbuf,smb_vwv3+1);
1093                 cli->sesskey = IVAL(cli->inbuf,smb_vwv7+1);
1094                 cli->serverzone = SVALS(cli->inbuf,smb_vwv15+1);
1095                 cli->serverzone *= 60;
1096                 /* this time arrives in real GMT */
1097                 cli->servertime = interpret_long_date(cli->inbuf+smb_vwv11+1);
1098                 cli->secblob = data_blob(smb_buf(cli->inbuf),smb_buflen(cli->inbuf));
1099                 cli->capabilities = IVAL(cli->inbuf,smb_vwv9+1);
1100                 if (cli->capabilities & CAP_RAW_MODE) {
1101                         cli->readbraw_supported = True;
1102                         cli->writebraw_supported = True;      
1103                 }
1104                 /* work out if they sent us a workgroup */
1105                 if (!(cli->capabilities & CAP_EXTENDED_SECURITY) &&
1106                     smb_buflen(cli->inbuf) > 8) {
1107                         clistr_pull(cli, cli->server_domain, 
1108                                     smb_buf(cli->inbuf)+8, sizeof(cli->server_domain),
1109                                     smb_buflen(cli->inbuf)-8, STR_UNICODE|STR_NOALIGN);
1110                 }
1111
1112                 /*
1113                  * As signing is slow we only turn it on if either the client or
1114                  * the server require it. JRA.
1115                  */
1116
1117                 if (cli->sec_mode & NEGOTIATE_SECURITY_SIGNATURES_REQUIRED) {
1118                         /* Fail if server says signing is mandatory and we don't want to support it. */
1119                         if (!cli->sign_info.allow_smb_signing) {
1120                                 DEBUG(0,("cli_negprot: SMB signing is mandatory and we have disabled it.\n"));
1121                                 return False;
1122                         }
1123                         cli->sign_info.negotiated_smb_signing = True;
1124                         cli->sign_info.mandatory_signing = True;
1125                 } else if (cli->sign_info.mandatory_signing && cli->sign_info.allow_smb_signing) {
1126                         /* Fail if client says signing is mandatory and the server doesn't support it. */
1127                         if (!(cli->sec_mode & NEGOTIATE_SECURITY_SIGNATURES_ENABLED)) {
1128                                 DEBUG(1,("cli_negprot: SMB signing is mandatory and the server doesn't support it.\n"));
1129                                 return False;
1130                         }
1131                         cli->sign_info.negotiated_smb_signing = True;
1132                         cli->sign_info.mandatory_signing = True;
1133                 } else if (cli->sec_mode & NEGOTIATE_SECURITY_SIGNATURES_ENABLED) {
1134                         cli->sign_info.negotiated_smb_signing = True;
1135                 }
1136
1137         } else if (cli->protocol >= PROTOCOL_LANMAN1) {
1138                 cli->use_spnego = False;
1139                 cli->sec_mode = SVAL(cli->inbuf,smb_vwv1);
1140                 cli->max_xmit = SVAL(cli->inbuf,smb_vwv2);
1141                 cli->max_mux = SVAL(cli->inbuf, smb_vwv3); 
1142                 cli->sesskey = IVAL(cli->inbuf,smb_vwv6);
1143                 cli->serverzone = SVALS(cli->inbuf,smb_vwv10);
1144                 cli->serverzone *= 60;
1145                 /* this time is converted to GMT by make_unix_date */
1146                 cli->servertime = make_unix_date(cli->inbuf+smb_vwv8);
1147                 cli->readbraw_supported = ((SVAL(cli->inbuf,smb_vwv5) & 0x1) != 0);
1148                 cli->writebraw_supported = ((SVAL(cli->inbuf,smb_vwv5) & 0x2) != 0);
1149                 cli->secblob = data_blob(smb_buf(cli->inbuf),smb_buflen(cli->inbuf));
1150         } else {
1151                 /* the old core protocol */
1152                 cli->use_spnego = False;
1153                 cli->sec_mode = 0;
1154                 cli->serverzone = TimeDiff(time(NULL));
1155         }
1156
1157         cli->max_xmit = MIN(cli->max_xmit, CLI_BUFFER_SIZE);
1158
1159         /* a way to force ascii SMB */
1160         if (getenv("CLI_FORCE_ASCII"))
1161                 cli->capabilities &= ~CAP_UNICODE;
1162
1163         return True;
1164 }
1165
1166 /****************************************************************************
1167  Send a session request. See rfc1002.txt 4.3 and 4.3.2.
1168 ****************************************************************************/
1169
1170 BOOL cli_session_request(struct cli_state *cli,
1171                          struct nmb_name *calling, struct nmb_name *called)
1172 {
1173         char *p;
1174         int len = 4;
1175         extern pstring user_socket_options;
1176
1177         memcpy(&(cli->calling), calling, sizeof(*calling));
1178         memcpy(&(cli->called ), called , sizeof(*called ));
1179   
1180         /* put in the destination name */
1181         p = cli->outbuf+len;
1182         name_mangle(cli->called .name, p, cli->called .name_type);
1183         len += name_len(p);
1184
1185         /* and my name */
1186         p = cli->outbuf+len;
1187         name_mangle(cli->calling.name, p, cli->calling.name_type);
1188         len += name_len(p);
1189
1190         /* 445 doesn't have session request */
1191         if (cli->port == 445)
1192                 return True;
1193
1194         /* send a session request (RFC 1002) */
1195         /* setup the packet length
1196          * Remove four bytes from the length count, since the length
1197          * field in the NBT Session Service header counts the number
1198          * of bytes which follow.  The cli_send_smb() function knows
1199          * about this and accounts for those four bytes.
1200          * CRH.
1201          */
1202         len -= 4;
1203         _smb_setlen(cli->outbuf,len);
1204         SCVAL(cli->outbuf,0,0x81);
1205
1206         cli_send_smb(cli);
1207         DEBUG(5,("Sent session request\n"));
1208
1209         if (!cli_receive_smb(cli))
1210                 return False;
1211
1212         if (CVAL(cli->inbuf,0) == 0x84) {
1213                 /* C. Hoch  9/14/95 Start */
1214                 /* For information, here is the response structure.
1215                  * We do the byte-twiddling to for portability.
1216                 struct RetargetResponse{
1217                 unsigned char type;
1218                 unsigned char flags;
1219                 int16 length;
1220                 int32 ip_addr;
1221                 int16 port;
1222                 };
1223                 */
1224                 int port = (CVAL(cli->inbuf,8)<<8)+CVAL(cli->inbuf,9);
1225                 /* SESSION RETARGET */
1226                 putip((char *)&cli->dest_ip,cli->inbuf+4);
1227
1228                 cli->fd = open_socket_out(SOCK_STREAM, &cli->dest_ip, port, LONG_CONNECT_TIMEOUT);
1229                 if (cli->fd == -1)
1230                         return False;
1231
1232                 DEBUG(3,("Retargeted\n"));
1233
1234                 set_socket_options(cli->fd,user_socket_options);
1235
1236                 /* Try again */
1237                 {
1238                         static int depth;
1239                         BOOL ret;
1240                         if (depth > 4) {
1241                                 DEBUG(0,("Retarget recursion - failing\n"));
1242                                 return False;
1243                         }
1244                         depth++;
1245                         ret = cli_session_request(cli, calling, called);
1246                         depth--;
1247                         return ret;
1248                 }
1249         } /* C. Hoch 9/14/95 End */
1250
1251         if (CVAL(cli->inbuf,0) != 0x82) {
1252                 /* This is the wrong place to put the error... JRA. */
1253                 cli->rap_error = CVAL(cli->inbuf,4);
1254                 return False;
1255         }
1256         return(True);
1257 }
1258
1259 /****************************************************************************
1260  Open the client sockets.
1261 ****************************************************************************/
1262
1263 BOOL cli_connect(struct cli_state *cli, const char *host, struct in_addr *ip)
1264 {
1265         extern pstring user_socket_options;
1266         int name_type = 0x20;
1267         char *p;
1268
1269         /* reasonable default hostname */
1270         if (!host) host = "*SMBSERVER";
1271
1272         fstrcpy(cli->desthost, host);
1273
1274         /* allow hostnames of the form NAME#xx and do a netbios lookup */
1275         if ((p = strchr(cli->desthost, '#'))) {
1276                 name_type = strtol(p+1, NULL, 16);              
1277                 *p = 0;
1278         }
1279         
1280         if (!ip || is_zero_ip(*ip)) {
1281                 if (!resolve_name(cli->desthost, &cli->dest_ip, name_type)) {
1282                         return False;
1283                 }
1284                 if (ip) *ip = cli->dest_ip;
1285         } else {
1286                 cli->dest_ip = *ip;
1287         }
1288
1289         if (getenv("LIBSMB_PROG")) {
1290                 cli->fd = sock_exec(getenv("LIBSMB_PROG"));
1291         } else {
1292                 /* try 445 first, then 139 */
1293                 int port = cli->port?cli->port:445;
1294                 cli->fd = open_socket_out(SOCK_STREAM, &cli->dest_ip, 
1295                                           port, cli->timeout);
1296                 if (cli->fd == -1 && cli->port == 0) {
1297                         port = 139;
1298                         cli->fd = open_socket_out(SOCK_STREAM, &cli->dest_ip, 
1299                                                   port, cli->timeout);
1300                 }
1301                 if (cli->fd != -1)
1302                         cli->port = port;
1303         }
1304         if (cli->fd == -1) {
1305                 DEBUG(1,("Error connecting to %s (%s)\n",
1306                          ip?inet_ntoa(*ip):host,strerror(errno)));
1307                 return False;
1308         }
1309
1310         set_socket_options(cli->fd,user_socket_options);
1311
1312         return True;
1313 }
1314
1315 /****************************************************************************
1316  Initialise client credentials for authenticated pipe access.
1317 ****************************************************************************/
1318
1319 void init_creds(struct ntuser_creds *creds, const char* username,
1320                        const char* domain, const char* password)
1321 {
1322         ZERO_STRUCTP(creds);
1323
1324         pwd_set_cleartext(&creds->pwd, password);
1325
1326         fstrcpy(creds->user_name, username);
1327         fstrcpy(creds->domain, domain);
1328
1329         if (!*username) {
1330                 creds->pwd.null_pwd = True;
1331         }
1332 }
1333
1334 /**
1335    establishes a connection to after the negprot. 
1336    @param output_cli A fully initialised cli structure, non-null only on success
1337    @param dest_host The netbios name of the remote host
1338    @param dest_ip (optional) The the destination IP, NULL for name based lookup
1339    @param port (optional) The destination port (0 for default)
1340    @param retry BOOL. Did this connection fail with a retryable error ?
1341
1342 */
1343 NTSTATUS cli_start_connection(struct cli_state **output_cli, 
1344                               const char *my_name, 
1345                               const char *dest_host, 
1346                               struct in_addr *dest_ip, int port,
1347                               int signing_state, int flags,
1348                               BOOL *retry) 
1349 {
1350         NTSTATUS nt_status;
1351         struct nmb_name calling;
1352         struct nmb_name called;
1353         struct cli_state *cli;
1354         struct in_addr ip;
1355
1356         if (retry)
1357                 *retry = False;
1358
1359         if (!my_name) 
1360                 my_name = global_myname();
1361         
1362         if (!(cli = cli_initialise(NULL)))
1363                 return NT_STATUS_NO_MEMORY;
1364         
1365         make_nmb_name(&calling, my_name, 0x0);
1366         make_nmb_name(&called , dest_host, 0x20);
1367
1368         if (cli_set_port(cli, port) != port) {
1369                 cli_shutdown(cli);
1370                 return NT_STATUS_UNSUCCESSFUL;
1371         }
1372
1373         cli_set_timeout(cli, 10000); /* 10 seconds. */
1374
1375         if (dest_ip)
1376                 ip = *dest_ip;
1377         else
1378                 ZERO_STRUCT(ip);
1379
1380 again:
1381
1382         DEBUG(3,("Connecting to host=%s\n", dest_host));
1383         
1384         if (!cli_connect(cli, dest_host, &ip)) {
1385                 DEBUG(1,("cli_full_connection: failed to connect to %s (%s)\n",
1386                          nmb_namestr(&called), inet_ntoa(ip)));
1387                 cli_shutdown(cli);
1388                 return NT_STATUS_UNSUCCESSFUL;
1389         }
1390
1391         if (retry)
1392                 *retry = True;
1393
1394         if (!cli_session_request(cli, &calling, &called)) {
1395                 char *p;
1396                 DEBUG(1,("session request to %s failed (%s)\n", 
1397                          called.name, cli_errstr(cli)));
1398                 if ((p=strchr(called.name, '.')) && !is_ipaddress(called.name)) {
1399                         *p = 0;
1400                         goto again;
1401                 }
1402                 if (strcmp(called.name, "*SMBSERVER")) {
1403                         make_nmb_name(&called , "*SMBSERVER", 0x20);
1404                         goto again;
1405                 }
1406                 return NT_STATUS_UNSUCCESSFUL;
1407         }
1408
1409         cli_setup_signing_state(cli, signing_state);
1410
1411         if (flags & CLI_FULL_CONNECTION_DONT_SPNEGO)
1412                 cli->use_spnego = False;
1413         else if (flags & CLI_FULL_CONNECTION_USE_KERBEROS)
1414                 cli->use_kerberos = True;
1415
1416         if (!cli_negprot(cli)) {
1417                 DEBUG(1,("failed negprot\n"));
1418                 nt_status = NT_STATUS_UNSUCCESSFUL;
1419                 cli_shutdown(cli);
1420                 return nt_status;
1421         }
1422
1423         *output_cli = cli;
1424         return NT_STATUS_OK;
1425 }
1426
1427
1428 /**
1429    establishes a connection right up to doing tconX, password specified.
1430    @param output_cli A fully initialised cli structure, non-null only on success
1431    @param dest_host The netbios name of the remote host
1432    @param dest_ip (optional) The the destination IP, NULL for name based lookup
1433    @param port (optional) The destination port (0 for default)
1434    @param service (optional) The share to make the connection to.  Should be 'unqualified' in any way.
1435    @param service_type The 'type' of serivice. 
1436    @param user Username, unix string
1437    @param domain User's domain
1438    @param password User's password, unencrypted unix string.
1439    @param retry BOOL. Did this connection fail with a retryable error ?
1440 */
1441
1442 NTSTATUS cli_full_connection(struct cli_state **output_cli, 
1443                              const char *my_name, 
1444                              const char *dest_host, 
1445                              struct in_addr *dest_ip, int port,
1446                              const char *service, const char *service_type,
1447                              const char *user, const char *domain, 
1448                              const char *password, int flags,
1449                              int signing_state,
1450                              BOOL *retry) 
1451 {
1452         struct ntuser_creds creds;
1453         NTSTATUS nt_status;
1454         struct cli_state *cli = NULL;
1455
1456         nt_status = cli_start_connection(&cli, my_name, dest_host, 
1457                                          dest_ip, port, signing_state, flags, retry);
1458         
1459         if (!NT_STATUS_IS_OK(nt_status)) {
1460                 return nt_status;
1461         }
1462
1463         if (!cli_session_setup(cli, user, password, strlen(password)+1, 
1464                                password, strlen(password)+1, 
1465                                domain)) {
1466                 if ((flags & CLI_FULL_CONNECTION_ANNONYMOUS_FALLBACK)
1467                     && cli_session_setup(cli, "", "", 0, "", 0, domain)) {
1468                 } else {
1469                         nt_status = cli_nt_error(cli);
1470                         DEBUG(1,("failed session setup with %s\n", nt_errstr(nt_status)));
1471                         cli_shutdown(cli);
1472                         if (NT_STATUS_IS_OK(nt_status)) 
1473                                 nt_status = NT_STATUS_UNSUCCESSFUL;
1474                         return nt_status;
1475                 }
1476         } 
1477
1478         if (service) {
1479                 if (!cli_send_tconX(cli, service, service_type,
1480                                     password, strlen(password)+1)) {
1481                         nt_status = cli_nt_error(cli);
1482                         DEBUG(1,("failed tcon_X with %s\n", nt_errstr(nt_status)));
1483                         cli_shutdown(cli);
1484                         if (NT_STATUS_IS_OK(nt_status)) {
1485                                 nt_status = NT_STATUS_UNSUCCESSFUL;
1486                         }
1487                         return nt_status;
1488                 }
1489         }
1490
1491         init_creds(&creds, user, domain, password);
1492         cli_init_creds(cli, &creds);
1493
1494         *output_cli = cli;
1495         return NT_STATUS_OK;
1496 }
1497
1498 /****************************************************************************
1499  Attempt a NetBIOS session request, falling back to *SMBSERVER if needed.
1500 ****************************************************************************/
1501
1502 BOOL attempt_netbios_session_request(struct cli_state *cli, const char *srchost, const char *desthost,
1503                                      struct in_addr *pdest_ip)
1504 {
1505         struct nmb_name calling, called;
1506
1507         make_nmb_name(&calling, srchost, 0x0);
1508
1509         /*
1510          * If the called name is an IP address
1511          * then use *SMBSERVER immediately.
1512          */
1513
1514         if(is_ipaddress(desthost))
1515                 make_nmb_name(&called, "*SMBSERVER", 0x20);
1516         else
1517                 make_nmb_name(&called, desthost, 0x20);
1518
1519         if (!cli_session_request(cli, &calling, &called)) {
1520                 struct nmb_name smbservername;
1521
1522                 make_nmb_name(&smbservername , "*SMBSERVER", 0x20);
1523
1524                 /*
1525                  * If the name wasn't *SMBSERVER then
1526                  * try with *SMBSERVER if the first name fails.
1527                  */
1528
1529                 if (nmb_name_equal(&called, &smbservername)) {
1530
1531                         /*
1532                          * The name used was *SMBSERVER, don't bother with another name.
1533                          */
1534
1535                         DEBUG(0,("attempt_netbios_session_request: %s rejected the session for name *SMBSERVER \
1536 with error %s.\n", desthost, cli_errstr(cli) ));
1537                         return False;
1538                 }
1539
1540                 /*
1541                  * We need to close the connection here but can't call cli_shutdown as
1542                  * will free an allocated cli struct. cli_close_connection was invented
1543                  * for this purpose. JRA. Based on work by "Kim R. Pedersen" <krp@filanet.dk>.
1544                  */
1545
1546                 cli_close_connection(cli);
1547
1548                 if (!cli_initialise(cli) ||
1549                                 !cli_connect(cli, desthost, pdest_ip) ||
1550                                 !cli_session_request(cli, &calling, &smbservername)) {
1551                         DEBUG(0,("attempt_netbios_session_request: %s rejected the session for \
1552 name *SMBSERVER with error %s\n", desthost, cli_errstr(cli) ));
1553                         return False;
1554                 }
1555         }
1556
1557         return True;
1558 }
1559
1560
1561
1562
1563
1564 /****************************************************************************
1565  Send an old style tcon.
1566 ****************************************************************************/
1567 NTSTATUS cli_raw_tcon(struct cli_state *cli, 
1568                       const char *service, const char *pass, const char *dev,
1569                       uint16 *max_xmit, uint16 *tid)
1570 {
1571         char *p;
1572
1573         if (!lp_client_plaintext_auth() && (*pass)) {
1574                 DEBUG(1, ("Server requested plaintext password but 'client use plaintext auth'"
1575                           " is disabled\n"));
1576                 return NT_STATUS_ACCESS_DENIED;
1577         }
1578
1579         memset(cli->outbuf,'\0',smb_size);
1580         memset(cli->inbuf,'\0',smb_size);
1581
1582         set_message(cli->outbuf, 0, 0, True);
1583         SCVAL(cli->outbuf,smb_com,SMBtcon);
1584         cli_setup_packet(cli);
1585
1586         p = smb_buf(cli->outbuf);
1587         *p++ = 4; p += clistr_push(cli, p, service, -1, STR_TERMINATE | STR_NOALIGN);
1588         *p++ = 4; p += clistr_push(cli, p, pass, -1, STR_TERMINATE | STR_NOALIGN);
1589         *p++ = 4; p += clistr_push(cli, p, dev, -1, STR_TERMINATE | STR_NOALIGN);
1590
1591         cli_setup_bcc(cli, p);
1592
1593         cli_send_smb(cli);
1594         if (!cli_receive_smb(cli)) {
1595                 return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
1596         }
1597
1598         if (cli_is_error(cli)) {
1599                 return cli_nt_error(cli);
1600         }
1601
1602         *max_xmit = SVAL(cli->inbuf, smb_vwv0);
1603         *tid = SVAL(cli->inbuf, smb_vwv1);
1604
1605         return NT_STATUS_OK;
1606 }
1607
1608 /* Return a cli_state pointing at the IPC$ share for the given server */
1609
1610 struct cli_state *get_ipc_connect(char *server, struct in_addr *server_ip,
1611                                          struct user_auth_info *user_info)
1612 {
1613         struct cli_state *cli;
1614         pstring myname;
1615         NTSTATUS nt_status;
1616
1617         get_myname(myname);
1618         
1619         nt_status = cli_full_connection(&cli, myname, server, server_ip, 0, "IPC$", "IPC", 
1620                                         user_info->username, lp_workgroup(), user_info->password, 
1621                                         CLI_FULL_CONNECTION_ANNONYMOUS_FALLBACK, Undefined, NULL);
1622
1623         if (NT_STATUS_IS_OK(nt_status)) {
1624                 return cli;
1625         } else if (is_ipaddress(server)) {
1626             /* windows 9* needs a correct NMB name for connections */
1627             fstring remote_name;
1628
1629             if (name_status_find("*", 0, 0, *server_ip, remote_name)) {
1630                 cli = get_ipc_connect(remote_name, server_ip, user_info);
1631                 if (cli)
1632                     return cli;
1633             }
1634         }
1635         return NULL;
1636 }
1637
1638 /*
1639  * Given the IP address of a master browser on the network, return its
1640  * workgroup and connect to it.
1641  *
1642  * This function is provided to allow additional processing beyond what
1643  * get_ipc_connect_master_ip_bcast() does, e.g. to retrieve the list of master
1644  * browsers and obtain each master browsers' list of domains (in case the
1645  * first master browser is recently on the network and has not yet
1646  * synchronized with other master browsers and therefore does not yet have the
1647  * entire network browse list)
1648  */
1649
1650 struct cli_state *get_ipc_connect_master_ip(struct ip_service * mb_ip, pstring workgroup, struct user_auth_info *user_info)
1651 {
1652         static fstring name;
1653         struct cli_state *cli;
1654         struct in_addr server_ip; 
1655
1656         DEBUG(99, ("Looking up name of master browser %s\n",
1657                    inet_ntoa(mb_ip->ip)));
1658
1659         /*
1660          * Do a name status query to find out the name of the master browser.
1661          * We use <01><02>__MSBROWSE__<02>#01 if *#00 fails because a domain
1662          * master browser will not respond to a wildcard query (or, at least,
1663          * an NT4 server acting as the domain master browser will not).
1664          *
1665          * We might be able to use ONLY the query on MSBROWSE, but that's not
1666          * yet been tested with all Windows versions, so until it is, leave
1667          * the original wildcard query as the first choice and fall back to
1668          * MSBROWSE if the wildcard query fails.
1669          */
1670         if (!name_status_find("*", 0, 0x1d, mb_ip->ip, name) &&
1671             !name_status_find(MSBROWSE, 1, 0x1d, mb_ip->ip, name)) {
1672
1673                 DEBUG(99, ("Could not retrieve name status for %s\n",
1674                            inet_ntoa(mb_ip->ip)));
1675                 return NULL;
1676         }
1677
1678         if (!find_master_ip(name, &server_ip)) {
1679                 DEBUG(99, ("Could not find master ip for %s\n", name));
1680                 return NULL;
1681         }
1682
1683                 pstrcpy(workgroup, name);
1684
1685                 DEBUG(4, ("found master browser %s, %s\n", 
1686                   name, inet_ntoa(mb_ip->ip)));
1687
1688                 cli = get_ipc_connect(inet_ntoa(server_ip), &server_ip, user_info);
1689
1690                 return cli;
1691     
1692 }
1693
1694 /*
1695  * Return the IP address and workgroup of a master browser on the network, and
1696  * connect to it.
1697  */
1698
1699 struct cli_state *get_ipc_connect_master_ip_bcast(pstring workgroup, struct user_auth_info *user_info)
1700 {
1701         struct ip_service *ip_list;
1702         struct cli_state *cli;
1703         int i, count;
1704
1705         DEBUG(99, ("Do broadcast lookup for workgroups on local network\n"));
1706
1707         /* Go looking for workgroups by broadcasting on the local network */ 
1708
1709         if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
1710                 DEBUG(99, ("No master browsers responded\n"));
1711                 return False;
1712         }
1713
1714         for (i = 0; i < count; i++) {
1715             DEBUG(99, ("Found master browser %s\n", inet_ntoa(ip_list[i].ip)));
1716
1717             cli = get_ipc_connect_master_ip(&ip_list[i], workgroup, user_info);
1718             if (cli)
1719                     return(cli);
1720         }
1721
1722         return NULL;
1723 }