CVE-2015-5296: s3:libsmb: force signing when requiring encryption in do_connect()
[samba.git] / source3 / libsmb / clidfs.c
1 /*
2    Unix SMB/CIFS implementation.
3    client connect/disconnect routines
4    Copyright (C) Andrew Tridgell                  1994-1998
5    Copyright (C) Gerald (Jerry) Carter            2004
6    Copyright (C) Jeremy Allison                   2007-2009
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23 #include "libsmb/libsmb.h"
24 #include "libsmb/clirap.h"
25 #include "msdfs.h"
26 #include "trans2.h"
27 #include "libsmb/nmblib.h"
28 #include "../libcli/smb/smbXcli_base.h"
29
30 /********************************************************************
31  Important point.
32
33  DFS paths are *always* of the form \server\share\<pathname> (the \ characters
34  are not C escaped here).
35
36  - but if we're using POSIX paths then <pathname> may contain
37    '/' separators, not '\\' separators. So cope with '\\' or '/'
38    as a separator when looking at the pathname part.... JRA.
39 ********************************************************************/
40
41 /********************************************************************
42  Ensure a connection is encrypted.
43 ********************************************************************/
44
45 NTSTATUS cli_cm_force_encryption(struct cli_state *c,
46                         const char *username,
47                         const char *password,
48                         const char *domain,
49                         const char *sharename)
50 {
51         NTSTATUS status;
52
53         if (smbXcli_conn_protocol(c->conn) >= PROTOCOL_SMB2_02) {
54                 status = smb2cli_session_encryption_on(c->smb2.session);
55                 if (NT_STATUS_EQUAL(status,NT_STATUS_NOT_SUPPORTED)) {
56                         d_printf("Encryption required and "
57                                 "server doesn't support "
58                                 "SMB3 encryption - failing connect\n");
59                 } else if (!NT_STATUS_IS_OK(status)) {
60                         d_printf("Encryption required and "
61                                 "setup failed with error %s.\n",
62                                 nt_errstr(status));
63                 }
64                 return status;
65         }
66
67         status = cli_force_encryption(c,
68                                         username,
69                                         password,
70                                         domain);
71
72         if (NT_STATUS_EQUAL(status,NT_STATUS_NOT_SUPPORTED)) {
73                 d_printf("Encryption required and "
74                         "server that doesn't support "
75                         "UNIX extensions - failing connect\n");
76         } else if (NT_STATUS_EQUAL(status,NT_STATUS_UNKNOWN_REVISION)) {
77                 d_printf("Encryption required and "
78                         "can't get UNIX CIFS extensions "
79                         "version from server.\n");
80         } else if (NT_STATUS_EQUAL(status,NT_STATUS_UNSUPPORTED_COMPRESSION)) {
81                 d_printf("Encryption required and "
82                         "share %s doesn't support "
83                         "encryption.\n", sharename);
84         } else if (!NT_STATUS_IS_OK(status)) {
85                 d_printf("Encryption required and "
86                         "setup failed with error %s.\n",
87                         nt_errstr(status));
88         }
89
90         return status;
91 }
92
93 /********************************************************************
94  Return a connection to a server.
95 ********************************************************************/
96
97 static NTSTATUS do_connect(TALLOC_CTX *ctx,
98                                         const char *server,
99                                         const char *share,
100                                         const struct user_auth_info *auth_info,
101                                         bool show_sessetup,
102                                         bool force_encrypt,
103                                         int max_protocol,
104                                         int port,
105                                         int name_type,
106                                         struct cli_state **pcli)
107 {
108         struct cli_state *c = NULL;
109         char *servicename;
110         char *sharename;
111         char *newserver, *newshare;
112         const char *username;
113         const char *password;
114         const char *domain;
115         NTSTATUS status;
116         int flags = 0;
117         int signing_state = get_cmdline_auth_info_signing_state(auth_info);
118
119         if (force_encrypt) {
120                 signing_state = SMB_SIGNING_REQUIRED;
121         }
122
123         /* make a copy so we don't modify the global string 'service' */
124         servicename = talloc_strdup(ctx,share);
125         if (!servicename) {
126                 return NT_STATUS_NO_MEMORY;
127         }
128         sharename = servicename;
129         if (*sharename == '\\') {
130                 sharename += 2;
131                 if (server == NULL) {
132                         server = sharename;
133                 }
134                 sharename = strchr_m(sharename,'\\');
135                 if (!sharename) {
136                         return NT_STATUS_NO_MEMORY;
137                 }
138                 *sharename = 0;
139                 sharename++;
140         }
141         if (server == NULL) {
142                 return NT_STATUS_INVALID_PARAMETER;
143         }
144
145         if (get_cmdline_auth_info_use_kerberos(auth_info)) {
146                 flags |= CLI_FULL_CONNECTION_USE_KERBEROS;
147         }
148         if (get_cmdline_auth_info_fallback_after_kerberos(auth_info)) {
149                 flags |= CLI_FULL_CONNECTION_FALLBACK_AFTER_KERBEROS;
150         }
151         if (get_cmdline_auth_info_use_ccache(auth_info)) {
152                 flags |= CLI_FULL_CONNECTION_USE_CCACHE;
153         }
154         if (get_cmdline_auth_info_use_pw_nt_hash(auth_info)) {
155                 flags |= CLI_FULL_CONNECTION_USE_NT_HASH;
156         }
157
158         status = cli_connect_nb(
159                 server, NULL, port, name_type, NULL,
160                 signing_state,
161                 flags, &c);
162
163         if (!NT_STATUS_IS_OK(status)) {
164                 d_printf("Connection to %s failed (Error %s)\n",
165                                 server,
166                                 nt_errstr(status));
167                 return status;
168         }
169
170         if (max_protocol == 0) {
171                 max_protocol = PROTOCOL_NT1;
172         }
173         DEBUG(4,(" session request ok\n"));
174
175         status = smbXcli_negprot(c->conn, c->timeout,
176                                  lp_cli_minprotocol(),
177                                  max_protocol);
178
179         if (!NT_STATUS_IS_OK(status)) {
180                 d_printf("protocol negotiation failed: %s\n",
181                          nt_errstr(status));
182                 cli_shutdown(c);
183                 return status;
184         }
185
186         if (smbXcli_conn_protocol(c->conn) >= PROTOCOL_SMB2_02) {
187                 /* Ensure we ask for some initial credits. */
188                 smb2cli_conn_set_max_credits(c->conn, DEFAULT_SMB2_MAX_CREDITS);
189         }
190
191         username = get_cmdline_auth_info_username(auth_info);
192         password = get_cmdline_auth_info_password(auth_info);
193         domain = get_cmdline_auth_info_domain(auth_info);
194         if ((domain == NULL) || (domain[0] == '\0')) {
195                 domain = lp_workgroup();
196         }
197
198         status = cli_session_setup(c, username,
199                                    password, strlen(password),
200                                    password, strlen(password),
201                                    domain);
202         if (!NT_STATUS_IS_OK(status)) {
203                 /* If a password was not supplied then
204                  * try again with a null username. */
205                 if (password[0] || !username[0] ||
206                         get_cmdline_auth_info_use_kerberos(auth_info) ||
207                         !NT_STATUS_IS_OK(status = cli_session_setup(c, "",
208                                                 "", 0,
209                                                 "", 0,
210                                                lp_workgroup()))) {
211                         d_printf("session setup failed: %s\n",
212                                  nt_errstr(status));
213                         if (NT_STATUS_EQUAL(status,
214                                             NT_STATUS_MORE_PROCESSING_REQUIRED))
215                                 d_printf("did you forget to run kinit?\n");
216                         cli_shutdown(c);
217                         return status;
218                 }
219                 d_printf("Anonymous login successful\n");
220                 status = cli_init_creds(c, "", lp_workgroup(), "");
221         } else {
222                 status = cli_init_creds(c, username, domain, password);
223         }
224
225         if (!NT_STATUS_IS_OK(status)) {
226                 DEBUG(10,("cli_init_creds() failed: %s\n", nt_errstr(status)));
227                 cli_shutdown(c);
228                 return status;
229         }
230
231         if ( show_sessetup ) {
232                 if (*c->server_domain) {
233                         DEBUG(0,("Domain=[%s] OS=[%s] Server=[%s]\n",
234                                 c->server_domain,c->server_os,c->server_type));
235                 } else if (*c->server_os || *c->server_type) {
236                         DEBUG(0,("OS=[%s] Server=[%s]\n",
237                                  c->server_os,c->server_type));
238                 }
239         }
240         DEBUG(4,(" session setup ok\n"));
241
242         /* here's the fun part....to support 'msdfs proxy' shares
243            (on Samba or windows) we have to issues a TRANS_GET_DFS_REFERRAL
244            here before trying to connect to the original share.
245            cli_check_msdfs_proxy() will fail if it is a normal share. */
246
247         if (smbXcli_conn_dfs_supported(c->conn) &&
248                         cli_check_msdfs_proxy(ctx, c, sharename,
249                                 &newserver, &newshare,
250                                 force_encrypt,
251                                 username,
252                                 password,
253                                 domain)) {
254                 cli_shutdown(c);
255                 return do_connect(ctx, newserver,
256                                 newshare, auth_info, false,
257                                 force_encrypt, max_protocol,
258                                 port, name_type, pcli);
259         }
260
261         /* must be a normal share */
262
263         status = cli_tree_connect(c, sharename, "?????",
264                                   password, strlen(password)+1);
265         if (!NT_STATUS_IS_OK(status)) {
266                 d_printf("tree connect failed: %s\n", nt_errstr(status));
267                 cli_shutdown(c);
268                 return status;
269         }
270
271         if (force_encrypt) {
272                 status = cli_cm_force_encryption(c,
273                                         username,
274                                         password,
275                                         domain,
276                                         sharename);
277                 if (!NT_STATUS_IS_OK(status)) {
278                         cli_shutdown(c);
279                         return status;
280                 }
281         }
282
283         DEBUG(4,(" tconx ok\n"));
284         *pcli = c;
285         return NT_STATUS_OK;
286 }
287
288 /****************************************************************************
289 ****************************************************************************/
290
291 static void cli_set_mntpoint(struct cli_state *cli, const char *mnt)
292 {
293         TALLOC_CTX *frame = talloc_stackframe();
294         char *name = clean_name(frame, mnt);
295         if (!name) {
296                 TALLOC_FREE(frame);
297                 return;
298         }
299         TALLOC_FREE(cli->dfs_mountpoint);
300         cli->dfs_mountpoint = talloc_strdup(cli, name);
301         TALLOC_FREE(frame);
302 }
303
304 /********************************************************************
305  Add a new connection to the list.
306  referring_cli == NULL means a new initial connection.
307 ********************************************************************/
308
309 static NTSTATUS cli_cm_connect(TALLOC_CTX *ctx,
310                                struct cli_state *referring_cli,
311                                const char *server,
312                                const char *share,
313                                const struct user_auth_info *auth_info,
314                                bool show_hdr,
315                                bool force_encrypt,
316                                int max_protocol,
317                                int port,
318                                int name_type,
319                                struct cli_state **pcli)
320 {
321         struct cli_state *cli;
322         NTSTATUS status;
323
324         status = do_connect(ctx, server, share,
325                                 auth_info,
326                                 show_hdr, force_encrypt, max_protocol,
327                                 port, name_type, &cli);
328
329         if (!NT_STATUS_IS_OK(status)) {
330                 return status;
331         }
332
333         /* Enter into the list. */
334         if (referring_cli) {
335                 DLIST_ADD_END(referring_cli, cli, struct cli_state *);
336         }
337
338         if (referring_cli && referring_cli->requested_posix_capabilities) {
339                 uint16 major, minor;
340                 uint32 caplow, caphigh;
341                 status = cli_unix_extensions_version(cli, &major, &minor,
342                                                      &caplow, &caphigh);
343                 if (NT_STATUS_IS_OK(status)) {
344                         cli_set_unix_extensions_capabilities(cli,
345                                         major, minor,
346                                         caplow, caphigh);
347                 }
348         }
349
350         *pcli = cli;
351         return NT_STATUS_OK;
352 }
353
354 /********************************************************************
355  Return a connection to a server on a particular share.
356 ********************************************************************/
357
358 static struct cli_state *cli_cm_find(struct cli_state *cli,
359                                 const char *server,
360                                 const char *share)
361 {
362         struct cli_state *p;
363
364         if (cli == NULL) {
365                 return NULL;
366         }
367
368         /* Search to the start of the list. */
369         for (p = cli; p; p = DLIST_PREV(p)) {
370                 const char *remote_name =
371                         smbXcli_conn_remote_name(p->conn);
372
373                 if (strequal(server, remote_name) &&
374                                 strequal(share,p->share)) {
375                         return p;
376                 }
377         }
378
379         /* Search to the end of the list. */
380         for (p = cli->next; p; p = p->next) {
381                 const char *remote_name =
382                         smbXcli_conn_remote_name(p->conn);
383
384                 if (strequal(server, remote_name) &&
385                                 strequal(share,p->share)) {
386                         return p;
387                 }
388         }
389
390         return NULL;
391 }
392
393 /****************************************************************************
394  Open a client connection to a \\server\share.
395 ****************************************************************************/
396
397 NTSTATUS cli_cm_open(TALLOC_CTX *ctx,
398                                 struct cli_state *referring_cli,
399                                 const char *server,
400                                 const char *share,
401                                 const struct user_auth_info *auth_info,
402                                 bool show_hdr,
403                                 bool force_encrypt,
404                                 int max_protocol,
405                                 int port,
406                                 int name_type,
407                                 struct cli_state **pcli)
408 {
409         /* Try to reuse an existing connection in this list. */
410         struct cli_state *c = cli_cm_find(referring_cli, server, share);
411         NTSTATUS status;
412
413         if (c) {
414                 *pcli = c;
415                 return NT_STATUS_OK;
416         }
417
418         if (auth_info == NULL) {
419                 /* Can't do a new connection
420                  * without auth info. */
421                 d_printf("cli_cm_open() Unable to open connection [\\%s\\%s] "
422                         "without auth info\n",
423                         server, share );
424                 return NT_STATUS_INVALID_PARAMETER;
425         }
426
427         status = cli_cm_connect(ctx,
428                                 referring_cli,
429                                 server,
430                                 share,
431                                 auth_info,
432                                 show_hdr,
433                                 force_encrypt,
434                                 max_protocol,
435                                 port,
436                                 name_type,
437                                 &c);
438         if (!NT_STATUS_IS_OK(status)) {
439                 return status;
440         }
441         *pcli = c;
442         return NT_STATUS_OK;
443 }
444
445 /****************************************************************************
446 ****************************************************************************/
447
448 void cli_cm_display(struct cli_state *cli)
449 {
450         int i;
451
452         for (i=0; cli; cli = cli->next,i++ ) {
453                 d_printf("%d:\tserver=%s, share=%s\n",
454                         i, smbXcli_conn_remote_name(cli->conn), cli->share);
455         }
456 }
457
458 /****************************************************************************
459 ****************************************************************************/
460
461 /****************************************************************************
462 ****************************************************************************/
463
464 #if 0
465 void cli_cm_set_credentials(struct user_auth_info *auth_info)
466 {
467         SAFE_FREE(cm_creds.username);
468         cm_creds.username = SMB_STRDUP(get_cmdline_auth_info_username(
469                                                auth_info));
470
471         if (get_cmdline_auth_info_got_pass(auth_info)) {
472                 cm_set_password(get_cmdline_auth_info_password(auth_info));
473         }
474
475         cm_creds.use_kerberos = get_cmdline_auth_info_use_kerberos(auth_info);
476         cm_creds.fallback_after_kerberos = false;
477         cm_creds.signing_state = get_cmdline_auth_info_signing_state(auth_info);
478 }
479 #endif
480
481 /**********************************************************************
482  split a dfs path into the server, share name, and extrapath components
483 **********************************************************************/
484
485 static bool split_dfs_path(TALLOC_CTX *ctx,
486                                 const char *nodepath,
487                                 char **pp_server,
488                                 char **pp_share,
489                                 char **pp_extrapath)
490 {
491         char *p, *q;
492         char *path;
493
494         *pp_server = NULL;
495         *pp_share = NULL;
496         *pp_extrapath = NULL;
497
498         path = talloc_strdup(ctx, nodepath);
499         if (!path) {
500                 goto fail;
501         }
502
503         if ( path[0] != '\\' ) {
504                 goto fail;
505         }
506
507         p = strchr_m( path + 1, '\\' );
508         if ( !p ) {
509                 goto fail;
510         }
511
512         *p = '\0';
513         p++;
514
515         /* Look for any extra/deep path */
516         q = strchr_m(p, '\\');
517         if (q != NULL) {
518                 *q = '\0';
519                 q++;
520                 *pp_extrapath = talloc_strdup(ctx, q);
521         } else {
522                 *pp_extrapath = talloc_strdup(ctx, "");
523         }
524         if (*pp_extrapath == NULL) {
525                 goto fail;
526         }
527
528         *pp_share = talloc_strdup(ctx, p);
529         if (*pp_share == NULL) {
530                 goto fail;
531         }
532
533         *pp_server = talloc_strdup(ctx, &path[1]);
534         if (*pp_server == NULL) {
535                 goto fail;
536         }
537
538         TALLOC_FREE(path);
539         return true;
540
541 fail:
542         TALLOC_FREE(*pp_share);
543         TALLOC_FREE(*pp_extrapath);
544         TALLOC_FREE(path);
545         return false;
546 }
547
548 /****************************************************************************
549  Return the original path truncated at the directory component before
550  the first wildcard character. Trust the caller to provide a NULL
551  terminated string
552 ****************************************************************************/
553
554 static char *clean_path(TALLOC_CTX *ctx, const char *path)
555 {
556         size_t len;
557         char *p1, *p2, *p;
558         char *path_out;
559
560         /* No absolute paths. */
561         while (IS_DIRECTORY_SEP(*path)) {
562                 path++;
563         }
564
565         path_out = talloc_strdup(ctx, path);
566         if (!path_out) {
567                 return NULL;
568         }
569
570         p1 = strchr_m(path_out, '*');
571         p2 = strchr_m(path_out, '?');
572
573         if (p1 || p2) {
574                 if (p1 && p2) {
575                         p = MIN(p1,p2);
576                 } else if (!p1) {
577                         p = p2;
578                 } else {
579                         p = p1;
580                 }
581                 *p = '\0';
582
583                 /* Now go back to the start of this component. */
584                 p1 = strrchr_m(path_out, '/');
585                 p2 = strrchr_m(path_out, '\\');
586                 p = MAX(p1,p2);
587                 if (p) {
588                         *p = '\0';
589                 }
590         }
591
592         /* Strip any trailing separator */
593
594         len = strlen(path_out);
595         if ( (len > 0) && IS_DIRECTORY_SEP(path_out[len-1])) {
596                 path_out[len-1] = '\0';
597         }
598
599         return path_out;
600 }
601
602 /****************************************************************************
603 ****************************************************************************/
604
605 static char *cli_dfs_make_full_path(TALLOC_CTX *ctx,
606                                         struct cli_state *cli,
607                                         const char *dir)
608 {
609         char path_sep = '\\';
610
611         /* Ensure the extrapath doesn't start with a separator. */
612         while (IS_DIRECTORY_SEP(*dir)) {
613                 dir++;
614         }
615
616         if (cli->requested_posix_capabilities & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
617                 path_sep = '/';
618         }
619         return talloc_asprintf(ctx, "%c%s%c%s%c%s",
620                         path_sep,
621                         smbXcli_conn_remote_name(cli->conn),
622                         path_sep,
623                         cli->share,
624                         path_sep,
625                         dir);
626 }
627
628 /********************************************************************
629  check for dfs referral
630 ********************************************************************/
631
632 static bool cli_dfs_check_error(struct cli_state *cli, NTSTATUS expected,
633                                 NTSTATUS status)
634 {
635         /* only deal with DS when we negotiated NT_STATUS codes and UNICODE */
636
637         if (!(smbXcli_conn_use_unicode(cli->conn))) {
638                 return false;
639         }
640         if (!(smb1cli_conn_capabilities(cli->conn) & CAP_STATUS32)) {
641                 return false;
642         }
643         if (NT_STATUS_EQUAL(status, expected)) {
644                 return true;
645         }
646         return false;
647 }
648
649 /********************************************************************
650  Get the dfs referral link.
651 ********************************************************************/
652
653 NTSTATUS cli_dfs_get_referral(TALLOC_CTX *ctx,
654                         struct cli_state *cli,
655                         const char *path,
656                         struct client_dfs_referral **refs,
657                         size_t *num_refs,
658                         size_t *consumed)
659 {
660         unsigned int param_len = 0;
661         uint16_t recv_flags2;
662         uint8_t *param = NULL;
663         uint8_t *rdata = NULL;
664         char *p;
665         char *endp;
666         smb_ucs2_t *path_ucs;
667         char *consumed_path = NULL;
668         uint16_t consumed_ucs;
669         uint16 num_referrals;
670         struct client_dfs_referral *referrals = NULL;
671         NTSTATUS status;
672         TALLOC_CTX *frame = talloc_stackframe();
673
674         *num_refs = 0;
675         *refs = NULL;
676
677         param = talloc_array(talloc_tos(), uint8_t, 2);
678         if (!param) {
679                 status = NT_STATUS_NO_MEMORY;
680                 goto out;
681         }
682         SSVAL(param, 0, 0x03);  /* max referral level */
683
684         param = trans2_bytes_push_str(param, smbXcli_conn_use_unicode(cli->conn),
685                                       path, strlen(path)+1,
686                                       NULL);
687         if (!param) {
688                 status = NT_STATUS_NO_MEMORY;
689                 goto out;
690         }
691         param_len = talloc_get_size(param);
692         path_ucs = (smb_ucs2_t *)&param[2];
693
694         if (smbXcli_conn_protocol(cli->conn) >= PROTOCOL_SMB2_02) {
695                 DATA_BLOB in_input_buffer;
696                 DATA_BLOB in_output_buffer = data_blob_null;
697                 DATA_BLOB out_input_buffer = data_blob_null;
698                 DATA_BLOB out_output_buffer = data_blob_null;
699
700                 in_input_buffer.data = param;
701                 in_input_buffer.length = param_len;
702
703                 status = smb2cli_ioctl(cli->conn,
704                                        cli->timeout,
705                                        cli->smb2.session,
706                                        cli->smb2.tcon,
707                                        UINT64_MAX, /* in_fid_persistent */
708                                        UINT64_MAX, /* in_fid_volatile */
709                                        FSCTL_DFS_GET_REFERRALS,
710                                        0, /* in_max_input_length */
711                                        &in_input_buffer,
712                                        CLI_BUFFER_SIZE, /* in_max_output_length */
713                                        &in_output_buffer,
714                                        SMB2_IOCTL_FLAG_IS_FSCTL,
715                                        talloc_tos(),
716                                        &out_input_buffer,
717                                        &out_output_buffer);
718                 if (!NT_STATUS_IS_OK(status)) {
719                         goto out;
720                 }
721
722                 if (out_output_buffer.length < 4) {
723                         status = NT_STATUS_INVALID_NETWORK_RESPONSE;
724                         goto out;
725                 }
726
727                 recv_flags2 = FLAGS2_UNICODE_STRINGS;
728                 rdata = out_output_buffer.data;
729                 endp = (char *)rdata + out_output_buffer.length;
730         } else {
731                 unsigned int data_len = 0;
732                 uint16_t setup[1];
733
734                 SSVAL(setup, 0, TRANSACT2_GET_DFS_REFERRAL);
735
736                 status = cli_trans(talloc_tos(), cli, SMBtrans2,
737                                    NULL, 0xffff, 0, 0,
738                                    setup, 1, 0,
739                                    param, param_len, 2,
740                                    NULL, 0, CLI_BUFFER_SIZE,
741                                    &recv_flags2,
742                                    NULL, 0, NULL, /* rsetup */
743                                    NULL, 0, NULL,
744                                    &rdata, 4, &data_len);
745                 if (!NT_STATUS_IS_OK(status)) {
746                         goto out;
747                 }
748
749                 endp = (char *)rdata + data_len;
750         }
751
752         consumed_ucs  = SVAL(rdata, 0);
753         num_referrals = SVAL(rdata, 2);
754
755         /* consumed_ucs is the number of bytes
756          * of the UCS2 path consumed not counting any
757          * terminating null. We need to convert
758          * back to unix charset and count again
759          * to get the number of bytes consumed from
760          * the incoming path. */
761
762         errno = 0;
763         if (pull_string_talloc(talloc_tos(),
764                         NULL,
765                         0,
766                         &consumed_path,
767                         path_ucs,
768                         consumed_ucs,
769                         STR_UNICODE) == 0) {
770                 if (errno != 0) {
771                         status = map_nt_error_from_unix(errno);
772                 } else {
773                         status = NT_STATUS_INVALID_NETWORK_RESPONSE;
774                 }
775                 goto out;
776         }
777         if (consumed_path == NULL) {
778                 status = map_nt_error_from_unix(errno);
779                 goto out;
780         }
781         *consumed = strlen(consumed_path);
782
783         if (num_referrals != 0) {
784                 uint16 ref_version;
785                 uint16 ref_size;
786                 int i;
787                 uint16 node_offset;
788
789                 referrals = talloc_array(ctx, struct client_dfs_referral,
790                                          num_referrals);
791
792                 if (!referrals) {
793                         status = NT_STATUS_NO_MEMORY;
794                         goto out;
795                 }
796                 /* start at the referrals array */
797
798                 p = (char *)rdata+8;
799                 for (i=0; i<num_referrals && p < endp; i++) {
800                         if (p + 18 > endp) {
801                                 goto out;
802                         }
803                         ref_version = SVAL(p, 0);
804                         ref_size    = SVAL(p, 2);
805                         node_offset = SVAL(p, 16);
806
807                         if (ref_version != 3) {
808                                 p += ref_size;
809                                 continue;
810                         }
811
812                         referrals[i].proximity = SVAL(p, 8);
813                         referrals[i].ttl       = SVAL(p, 10);
814
815                         if (p + node_offset > endp) {
816                                 status = NT_STATUS_INVALID_NETWORK_RESPONSE;
817                                 goto out;
818                         }
819                         clistr_pull_talloc(referrals,
820                                            (const char *)rdata,
821                                            recv_flags2,
822                                            &referrals[i].dfspath,
823                                            p+node_offset,
824                                            PTR_DIFF(endp, p+node_offset),
825                                            STR_TERMINATE|STR_UNICODE);
826
827                         if (!referrals[i].dfspath) {
828                                 status = map_nt_error_from_unix(errno);
829                                 goto out;
830                         }
831                         p += ref_size;
832                 }
833                 if (i < num_referrals) {
834                         status = NT_STATUS_INVALID_NETWORK_RESPONSE;
835                         goto out;
836                 }
837         }
838
839         *num_refs = num_referrals;
840         *refs = referrals;
841
842   out:
843
844         TALLOC_FREE(frame);
845         return status;
846 }
847
848 /********************************************************************
849 ********************************************************************/
850 struct cli_dfs_path_split {
851         char *server;
852         char *share;
853         char *extrapath;
854 };
855
856 NTSTATUS cli_resolve_path(TALLOC_CTX *ctx,
857                           const char *mountpt,
858                           const struct user_auth_info *dfs_auth_info,
859                           struct cli_state *rootcli,
860                           const char *path,
861                           struct cli_state **targetcli,
862                           char **pp_targetpath)
863 {
864         struct client_dfs_referral *refs = NULL;
865         size_t num_refs = 0;
866         size_t consumed = 0;
867         struct cli_state *cli_ipc = NULL;
868         char *dfs_path = NULL;
869         char *cleanpath = NULL;
870         char *extrapath = NULL;
871         int pathlen;
872         struct cli_state *newcli = NULL;
873         struct cli_state *ccli = NULL;
874         int count = 0;
875         char *newpath = NULL;
876         char *newmount = NULL;
877         char *ppath = NULL;
878         SMB_STRUCT_STAT sbuf;
879         uint32 attributes;
880         NTSTATUS status;
881         struct smbXcli_tcon *root_tcon = NULL;
882         struct smbXcli_tcon *target_tcon = NULL;
883         struct cli_dfs_path_split *dfs_refs = NULL;
884
885         if ( !rootcli || !path || !targetcli ) {
886                 return NT_STATUS_INVALID_PARAMETER;
887         }
888
889         /* Don't do anything if this is not a DFS root. */
890
891         if (smbXcli_conn_protocol(rootcli->conn) >= PROTOCOL_SMB2_02) {
892                 root_tcon = rootcli->smb2.tcon;
893         } else {
894                 root_tcon = rootcli->smb1.tcon;
895         }
896
897         if (!smbXcli_tcon_is_dfs_share(root_tcon)) {
898                 *targetcli = rootcli;
899                 *pp_targetpath = talloc_strdup(ctx, path);
900                 if (!*pp_targetpath) {
901                         return NT_STATUS_NO_MEMORY;
902                 }
903                 return NT_STATUS_OK;
904         }
905
906         *targetcli = NULL;
907
908         /* Send a trans2_query_path_info to check for a referral. */
909
910         cleanpath = clean_path(ctx, path);
911         if (!cleanpath) {
912                 return NT_STATUS_NO_MEMORY;
913         }
914
915         dfs_path = cli_dfs_make_full_path(ctx, rootcli, cleanpath);
916         if (!dfs_path) {
917                 return NT_STATUS_NO_MEMORY;
918         }
919
920         status = cli_qpathinfo_basic( rootcli, dfs_path, &sbuf, &attributes);
921         if (NT_STATUS_IS_OK(status)) {
922                 /* This is an ordinary path, just return it. */
923                 *targetcli = rootcli;
924                 *pp_targetpath = talloc_strdup(ctx, path);
925                 if (!*pp_targetpath) {
926                         return NT_STATUS_NO_MEMORY;
927                 }
928                 goto done;
929         }
930
931         /* Special case where client asked for a path that does not exist */
932
933         if (cli_dfs_check_error(rootcli, NT_STATUS_OBJECT_NAME_NOT_FOUND,
934                                 status)) {
935                 *targetcli = rootcli;
936                 *pp_targetpath = talloc_strdup(ctx, path);
937                 if (!*pp_targetpath) {
938                         return NT_STATUS_NO_MEMORY;
939                 }
940                 goto done;
941         }
942
943         /* We got an error, check for DFS referral. */
944
945         if (!cli_dfs_check_error(rootcli, NT_STATUS_PATH_NOT_COVERED,
946                                  status)) {
947                 return status;
948         }
949
950         /* Check for the referral. */
951
952         status = cli_cm_open(ctx,
953                              rootcli,
954                              smbXcli_conn_remote_name(rootcli->conn),
955                              "IPC$",
956                              dfs_auth_info,
957                              false,
958                              smb1cli_conn_encryption_on(rootcli->conn),
959                              smbXcli_conn_protocol(rootcli->conn),
960                              0,
961                              0x20,
962                              &cli_ipc);
963         if (!NT_STATUS_IS_OK(status)) {
964                 return status;
965         }
966
967         status = cli_dfs_get_referral(ctx, cli_ipc, dfs_path, &refs,
968                                       &num_refs, &consumed);
969         if (!NT_STATUS_IS_OK(status) || !num_refs) {
970                 return status;
971         }
972
973         if (!refs[0].dfspath) {
974                 return NT_STATUS_NOT_FOUND;
975         }
976
977         /*
978          * Bug#10123 - DFS referal entries can be provided in a random order,
979          * so check the connection cache for each item to avoid unnecessary
980          * reconnections.
981          */
982         dfs_refs = talloc_array(ctx, struct cli_dfs_path_split, num_refs);
983         if (dfs_refs == NULL) {
984                 return NT_STATUS_NO_MEMORY;
985         }
986
987         for (count = 0; count < num_refs; count++) {
988                 if (!split_dfs_path(dfs_refs, refs[count].dfspath,
989                                     &dfs_refs[count].server,
990                                     &dfs_refs[count].share,
991                                     &dfs_refs[count].extrapath)) {
992                         TALLOC_FREE(dfs_refs);
993                         return NT_STATUS_NOT_FOUND;
994                 }
995
996                 ccli = cli_cm_find(rootcli, dfs_refs[count].server,
997                                    dfs_refs[count].share);
998                 if (ccli != NULL) {
999                         extrapath = dfs_refs[count].extrapath;
1000                         *targetcli = ccli;
1001                         break;
1002                 }
1003         }
1004
1005         /*
1006          * If no cached connection was found, then connect to the first live
1007          * referral server in the list.
1008          */
1009         for (count = 0; (ccli == NULL) && (count < num_refs); count++) {
1010                 /* Connect to the target server & share */
1011                 status = cli_cm_connect(ctx, rootcli,
1012                                 dfs_refs[count].server,
1013                                 dfs_refs[count].share,
1014                                 dfs_auth_info,
1015                                 false,
1016                                 smb1cli_conn_encryption_on(rootcli->conn),
1017                                 smbXcli_conn_protocol(rootcli->conn),
1018                                 0,
1019                                 0x20,
1020                                 targetcli);
1021                 if (!NT_STATUS_IS_OK(status)) {
1022                         d_printf("Unable to follow dfs referral [\\%s\\%s]\n",
1023                                  dfs_refs[count].server,
1024                                  dfs_refs[count].share);
1025                         continue;
1026                 } else {
1027                         extrapath = dfs_refs[count].extrapath;
1028                         break;
1029                 }
1030         }
1031
1032         /* No available referral server for the connection */
1033         if (*targetcli == NULL) {
1034                 TALLOC_FREE(dfs_refs);
1035                 return status;
1036         }
1037
1038         /* Make sure to recreate the original string including any wildcards. */
1039
1040         dfs_path = cli_dfs_make_full_path(ctx, rootcli, path);
1041         if (!dfs_path) {
1042                 TALLOC_FREE(dfs_refs);
1043                 return NT_STATUS_NO_MEMORY;
1044         }
1045         pathlen = strlen(dfs_path);
1046         consumed = MIN(pathlen, consumed);
1047         *pp_targetpath = talloc_strdup(ctx, &dfs_path[consumed]);
1048         if (!*pp_targetpath) {
1049                 TALLOC_FREE(dfs_refs);
1050                 return NT_STATUS_NO_MEMORY;
1051         }
1052         dfs_path[consumed] = '\0';
1053
1054         /*
1055          * *pp_targetpath is now the unconsumed part of the path.
1056          * dfs_path is now the consumed part of the path
1057          * (in \server\share\path format).
1058          */
1059
1060         if (extrapath && strlen(extrapath) > 0) {
1061                 /* EMC Celerra NAS version 5.6.50 (at least) doesn't appear to */
1062                 /* put the trailing \ on the path, so to be save we put one in if needed */
1063                 if (extrapath[strlen(extrapath)-1] != '\\' && **pp_targetpath != '\\') {
1064                         *pp_targetpath = talloc_asprintf(ctx,
1065                                                   "%s\\%s",
1066                                                   extrapath,
1067                                                   *pp_targetpath);
1068                 } else {
1069                         *pp_targetpath = talloc_asprintf(ctx,
1070                                                   "%s%s",
1071                                                   extrapath,
1072                                                   *pp_targetpath);
1073                 }
1074                 if (!*pp_targetpath) {
1075                         TALLOC_FREE(dfs_refs);
1076                         return NT_STATUS_NO_MEMORY;
1077                 }
1078         }
1079
1080         /* parse out the consumed mount path */
1081         /* trim off the \server\share\ */
1082
1083         ppath = dfs_path;
1084
1085         if (*ppath != '\\') {
1086                 d_printf("cli_resolve_path: "
1087                         "dfs_path (%s) not in correct format.\n",
1088                         dfs_path );
1089                 TALLOC_FREE(dfs_refs);
1090                 return NT_STATUS_NOT_FOUND;
1091         }
1092
1093         ppath++; /* Now pointing at start of server name. */
1094
1095         if ((ppath = strchr_m( dfs_path, '\\' )) == NULL) {
1096                 TALLOC_FREE(dfs_refs);
1097                 return NT_STATUS_NOT_FOUND;
1098         }
1099
1100         ppath++; /* Now pointing at start of share name. */
1101
1102         if ((ppath = strchr_m( ppath+1, '\\' )) == NULL) {
1103                 TALLOC_FREE(dfs_refs);
1104                 return NT_STATUS_NOT_FOUND;
1105         }
1106
1107         ppath++; /* Now pointing at path component. */
1108
1109         newmount = talloc_asprintf(ctx, "%s\\%s", mountpt, ppath );
1110         if (!newmount) {
1111                 TALLOC_FREE(dfs_refs);
1112                 return NT_STATUS_NOT_FOUND;
1113         }
1114
1115         cli_set_mntpoint(*targetcli, newmount);
1116
1117         /* Check for another dfs referral, note that we are not
1118            checking for loops here. */
1119
1120         if (!strequal(*pp_targetpath, "\\") && !strequal(*pp_targetpath, "/")) {
1121                 status = cli_resolve_path(ctx,
1122                                           newmount,
1123                                           dfs_auth_info,
1124                                           *targetcli,
1125                                           *pp_targetpath,
1126                                           &newcli,
1127                                           &newpath);
1128                 if (NT_STATUS_IS_OK(status)) {
1129                         /*
1130                          * When cli_resolve_path returns true here it's always
1131                          * returning the complete path in newpath, so we're done
1132                          * here.
1133                          */
1134                         *targetcli = newcli;
1135                         *pp_targetpath = newpath;
1136                         TALLOC_FREE(dfs_refs);
1137                         return status;
1138                 }
1139         }
1140
1141   done:
1142
1143         if (smbXcli_conn_protocol((*targetcli)->conn) >= PROTOCOL_SMB2_02) {
1144                 target_tcon = (*targetcli)->smb2.tcon;
1145         } else {
1146                 target_tcon = (*targetcli)->smb1.tcon;
1147         }
1148
1149         /* If returning true ensure we return a dfs root full path. */
1150         if (smbXcli_tcon_is_dfs_share(target_tcon)) {
1151                 dfs_path = talloc_strdup(ctx, *pp_targetpath);
1152                 if (!dfs_path) {
1153                         TALLOC_FREE(dfs_refs);
1154                         return NT_STATUS_NO_MEMORY;
1155                 }
1156                 *pp_targetpath = cli_dfs_make_full_path(ctx, *targetcli, dfs_path);
1157                 if (*pp_targetpath == NULL) {
1158                         TALLOC_FREE(dfs_refs);
1159                         return NT_STATUS_NO_MEMORY;
1160                 }
1161         }
1162
1163         TALLOC_FREE(dfs_refs);
1164         return NT_STATUS_OK;
1165 }
1166
1167 /********************************************************************
1168 ********************************************************************/
1169
1170 bool cli_check_msdfs_proxy(TALLOC_CTX *ctx,
1171                                 struct cli_state *cli,
1172                                 const char *sharename,
1173                                 char **pp_newserver,
1174                                 char **pp_newshare,
1175                                 bool force_encrypt,
1176                                 const char *username,
1177                                 const char *password,
1178                                 const char *domain)
1179 {
1180         struct client_dfs_referral *refs = NULL;
1181         size_t num_refs = 0;
1182         size_t consumed = 0;
1183         char *fullpath = NULL;
1184         bool res;
1185         uint16 cnum;
1186         char *newextrapath = NULL;
1187         NTSTATUS status;
1188         const char *remote_name;
1189
1190         if (!cli || !sharename) {
1191                 return false;
1192         }
1193
1194         remote_name = smbXcli_conn_remote_name(cli->conn);
1195         cnum = cli_state_get_tid(cli);
1196
1197         /* special case.  never check for a referral on the IPC$ share */
1198
1199         if (strequal(sharename, "IPC$")) {
1200                 return false;
1201         }
1202
1203         /* send a trans2_query_path_info to check for a referral */
1204
1205         fullpath = talloc_asprintf(ctx, "\\%s\\%s", remote_name, sharename);
1206         if (!fullpath) {
1207                 return false;
1208         }
1209
1210         /* check for the referral */
1211
1212         if (!NT_STATUS_IS_OK(cli_tree_connect(cli, "IPC$", "IPC", NULL, 0))) {
1213                 return false;
1214         }
1215
1216         if (force_encrypt) {
1217                 status = cli_cm_force_encryption(cli,
1218                                         username,
1219                                         password,
1220                                         domain,
1221                                         "IPC$");
1222                 if (!NT_STATUS_IS_OK(status)) {
1223                         return false;
1224                 }
1225         }
1226
1227         status = cli_dfs_get_referral(ctx, cli, fullpath, &refs,
1228                                       &num_refs, &consumed);
1229         res = NT_STATUS_IS_OK(status);
1230
1231         status = cli_tdis(cli);
1232         if (!NT_STATUS_IS_OK(status)) {
1233                 return false;
1234         }
1235
1236         cli_state_set_tid(cli, cnum);
1237
1238         if (!res || !num_refs) {
1239                 return false;
1240         }
1241
1242         if (!refs[0].dfspath) {
1243                 return false;
1244         }
1245
1246         if (!split_dfs_path(ctx, refs[0].dfspath, pp_newserver,
1247                             pp_newshare, &newextrapath)) {
1248                 return false;
1249         }
1250
1251         /* check that this is not a self-referral */
1252
1253         if (strequal(remote_name, *pp_newserver) &&
1254                         strequal(sharename, *pp_newshare)) {
1255                 return false;
1256         }
1257
1258         return true;
1259 }