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