s3: fix bug #6073: prevent ads_connect() from using SSL unless explicitly requested
[metze/samba/wip.git] / source3 / libsmb / libsmb_server.c
1 /* 
2    Unix SMB/Netbios implementation.
3    SMB client library implementation
4    Copyright (C) Andrew Tridgell 1998
5    Copyright (C) Richard Sharpe 2000, 2002
6    Copyright (C) John Terpstra 2000
7    Copyright (C) Tom Jansen (Ninja ISD) 2002 
8    Copyright (C) Derrell Lipman 2003-2008
9    Copyright (C) Jeremy Allison 2007, 2008
10
11    This program is free software; you can redistribute it and/or modify
12    it under the terms of the GNU General Public License as published by
13    the Free Software Foundation; either version 3 of the License, or
14    (at your option) any later version.
15
16    This program is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20
21    You should have received a copy of the GNU General Public License
22    along with this program.  If not, see <http://www.gnu.org/licenses/>.
23 */
24
25 #include "includes.h"
26 #include "libsmbclient.h"
27 #include "libsmb_internal.h"
28
29
30 /* 
31  * Check a server for being alive and well.
32  * returns 0 if the server is in shape. Returns 1 on error 
33  * 
34  * Also useable outside libsmbclient to enable external cache
35  * to do some checks too.
36  */
37 int
38 SMBC_check_server(SMBCCTX * context,
39                   SMBCSRV * server) 
40 {
41         socklen_t size;
42         struct sockaddr addr;
43
44         size = sizeof(addr);
45         return (getpeername(server->cli->fd, &addr, &size) == -1);
46 }
47
48 /* 
49  * Remove a server from the cached server list it's unused.
50  * On success, 0 is returned. 1 is returned if the server could not be removed.
51  * 
52  * Also useable outside libsmbclient
53  */
54 int
55 SMBC_remove_unused_server(SMBCCTX * context,
56                           SMBCSRV * srv)
57 {
58         SMBCFILE * file;
59
60         /* are we being fooled ? */
61         if (!context || !context->internal->initialized || !srv) {
62                 return 1;
63         }
64
65         /* Check all open files/directories for a relation with this server */
66         for (file = context->internal->files; file; file = file->next) {
67                 if (file->srv == srv) {
68                         /* Still used */
69                         DEBUG(3, ("smbc_remove_usused_server: "
70                                   "%p still used by %p.\n",
71                                   srv, file));
72                         return 1;
73                 }
74         }
75
76         DLIST_REMOVE(context->internal->servers, srv);
77
78         cli_shutdown(srv->cli);
79         srv->cli = NULL;
80
81         DEBUG(3, ("smbc_remove_usused_server: %p removed.\n", srv));
82
83         smbc_getFunctionRemoveCachedServer(context)(context, srv);
84
85         SAFE_FREE(srv);
86         return 0;
87 }
88
89 /****************************************************************
90  * Call the auth_fn with fixed size (fstring) buffers.
91  ***************************************************************/
92 void
93 SMBC_call_auth_fn(TALLOC_CTX *ctx,
94                   SMBCCTX *context,
95                   const char *server,
96                   const char *share,
97                   char **pp_workgroup,
98                   char **pp_username,
99                   char **pp_password)
100 {
101         fstring workgroup;
102         fstring username;
103         fstring password;
104         smbc_get_auth_data_with_context_fn auth_with_context_fn;
105
106         strlcpy(workgroup, *pp_workgroup, sizeof(workgroup));
107         strlcpy(username, *pp_username, sizeof(username));
108         strlcpy(password, *pp_password, sizeof(password));
109
110         /* See if there's an authentication with context function provided */
111         auth_with_context_fn = smbc_getFunctionAuthDataWithContext(context);
112         if (auth_with_context_fn)
113         {
114             (* auth_with_context_fn)(context,
115                                      server, share,
116                                      workgroup, sizeof(workgroup),
117                                      username, sizeof(username),
118                                      password, sizeof(password));
119         }
120         else
121         {
122             smbc_getFunctionAuthData(context)(server, share,
123                                               workgroup, sizeof(workgroup),
124                                               username, sizeof(username),
125                                               password, sizeof(password));
126         }
127
128         TALLOC_FREE(*pp_workgroup);
129         TALLOC_FREE(*pp_username);
130         TALLOC_FREE(*pp_password);
131
132         *pp_workgroup = talloc_strdup(ctx, workgroup);
133         *pp_username = talloc_strdup(ctx, username);
134         *pp_password = talloc_strdup(ctx, password);
135 }
136
137
138 void
139 SMBC_get_auth_data(const char *server, const char *share,
140                    char *workgroup_buf, int workgroup_buf_len,
141                    char *username_buf, int username_buf_len,
142                    char *password_buf, int password_buf_len)
143 {
144         /* Default function just uses provided data.  Nothing to do. */
145 }
146
147
148
149 SMBCSRV *
150 SMBC_find_server(TALLOC_CTX *ctx,
151                  SMBCCTX *context,
152                  const char *server,
153                  const char *share,
154                  char **pp_workgroup,
155                  char **pp_username,
156                  char **pp_password)
157 {
158         SMBCSRV *srv;
159         int auth_called = 0;
160
161         if (!pp_workgroup || !pp_username || !pp_password) {
162                 return NULL;
163         }
164
165 check_server_cache:
166
167         srv = smbc_getFunctionGetCachedServer(context)(context,
168                                                        server, share,
169                                                        *pp_workgroup,
170                                                        *pp_username);
171
172         if (!auth_called && !srv && (!*pp_username || !(*pp_username)[0] ||
173                                      !*pp_password || !(*pp_password)[0])) {
174                 SMBC_call_auth_fn(ctx, context, server, share,
175                                   pp_workgroup, pp_username, pp_password);
176
177                 /*
178                  * However, smbc_auth_fn may have picked up info relating to
179                  * an existing connection, so try for an existing connection
180                  * again ...
181                  */
182                 auth_called = 1;
183                 goto check_server_cache;
184
185         }
186
187         if (srv) {
188                 if (smbc_getFunctionCheckServer(context)(context, srv)) {
189                         /*
190                          * This server is no good anymore
191                          * Try to remove it and check for more possible
192                          * servers in the cache
193                          */
194                         if (smbc_getFunctionRemoveUnusedServer(context)(context,
195                                                                         srv)) { 
196                                 /*
197                                  * We could not remove the server completely,
198                                  * remove it from the cache so we will not get
199                                  * it again. It will be removed when the last
200                                  * file/dir is closed.
201                                  */
202                                 smbc_getFunctionRemoveCachedServer(context)(context,
203                                                                             srv);
204                         }
205
206                         /*
207                          * Maybe there are more cached connections to this
208                          * server
209                          */
210                         goto check_server_cache;
211                 }
212
213                 return srv;
214         }
215
216         return NULL;
217 }
218
219 /*
220  * Connect to a server, possibly on an existing connection
221  *
222  * Here, what we want to do is: If the server and username
223  * match an existing connection, reuse that, otherwise, establish a
224  * new connection.
225  *
226  * If we have to create a new connection, call the auth_fn to get the
227  * info we need, unless the username and password were passed in.
228  */
229
230 SMBCSRV *
231 SMBC_server(TALLOC_CTX *ctx,
232             SMBCCTX *context,
233             bool connect_if_not_found,
234             const char *server,
235             const char *share,
236             char **pp_workgroup,
237             char **pp_username,
238             char **pp_password)
239 {
240         SMBCSRV *srv=NULL;
241         struct cli_state *c;
242         struct nmb_name called, calling;
243         const char *server_n = server;
244         struct sockaddr_storage ss;
245         int tried_reverse = 0;
246         int port_try_first;
247         int port_try_next;
248         int is_ipc = (share != NULL && strcmp(share, "IPC$") == 0);
249         uint32 fs_attrs = 0;
250         const char *username_used;
251         NTSTATUS status;
252
253         zero_sockaddr(&ss);
254         ZERO_STRUCT(c);
255
256         if (server[0] == 0) {
257                 errno = EPERM;
258                 return NULL;
259         }
260
261         /* Look for a cached connection */
262         srv = SMBC_find_server(ctx, context, server, share,
263                                pp_workgroup, pp_username, pp_password);
264
265         /*
266          * If we found a connection and we're only allowed one share per
267          * server...
268          */
269         if (srv &&
270             *share != '\0' &&
271             smbc_getOptionOneSharePerServer(context)) {
272
273                 /*
274                  * ... then if there's no current connection to the share,
275                  * connect to it.  SMBC_find_server(), or rather the function
276                  * pointed to by context->get_cached_srv_fn which
277                  * was called by SMBC_find_server(), will have issued a tree
278                  * disconnect if the requested share is not the same as the
279                  * one that was already connected.
280                  */
281                 if (srv->cli->cnum == (uint16) -1) {
282                         /* Ensure we have accurate auth info */
283                         SMBC_call_auth_fn(ctx, context, server, share,
284                                           pp_workgroup,
285                                           pp_username,
286                                           pp_password);
287
288                         if (!*pp_workgroup || !*pp_username || !*pp_password) {
289                                 errno = ENOMEM;
290                                 cli_shutdown(srv->cli);
291                                 srv->cli = NULL;
292                                 smbc_getFunctionRemoveCachedServer(context)(context,
293                                                                             srv);
294                                 return NULL;
295                         }
296
297                         /*
298                          * We don't need to renegotiate encryption
299                          * here as the encryption context is not per
300                          * tid.
301                          */
302
303                         if (!cli_send_tconX(srv->cli, share, "?????",
304                                             *pp_password,
305                                             strlen(*pp_password)+1)) {
306
307                                 errno = SMBC_errno(context, srv->cli);
308                                 cli_shutdown(srv->cli);
309                                 srv->cli = NULL;
310                                 smbc_getFunctionRemoveCachedServer(context)(context,
311                                                                             srv);
312                                 srv = NULL;
313                         }
314
315                         /* Determine if this share supports case sensitivity */
316                         if (is_ipc) {
317                                 DEBUG(4,
318                                       ("IPC$ so ignore case sensitivity\n"));
319                         } else if (!cli_get_fs_attr_info(c, &fs_attrs)) {
320                                 DEBUG(4, ("Could not retrieve "
321                                           "case sensitivity flag: %s.\n",
322                                           cli_errstr(c)));
323
324                                 /*
325                                  * We can't determine the case sensitivity of
326                                  * the share. We have no choice but to use the
327                                  * user-specified case sensitivity setting.
328                                  */
329                                 if (smbc_getOptionCaseSensitive(context)) {
330                                         cli_set_case_sensitive(c, True);
331                                 } else {
332                                         cli_set_case_sensitive(c, False);
333                                 }
334                         } else {
335                                 DEBUG(4,
336                                       ("Case sensitive: %s\n",
337                                        (fs_attrs & FILE_CASE_SENSITIVE_SEARCH
338                                         ? "True"
339                                         : "False")));
340                                 cli_set_case_sensitive(
341                                         c,
342                                         (fs_attrs & FILE_CASE_SENSITIVE_SEARCH
343                                          ? True
344                                          : False));
345                         }
346
347                         /*
348                          * Regenerate the dev value since it's based on both
349                          * server and share
350                          */
351                         if (srv) {
352                                 srv->dev = (dev_t)(str_checksum(server) ^
353                                                    str_checksum(share));
354                         }
355                 }
356         }
357
358         /* If we have a connection... */
359         if (srv) {
360
361                 /* ... then we're done here.  Give 'em what they came for. */
362                 return srv;
363         }
364
365         /* If we're not asked to connect when a connection doesn't exist... */
366         if (! connect_if_not_found) {
367                 /* ... then we're done here. */
368                 return NULL;
369         }
370
371         if (!*pp_workgroup || !*pp_username || !*pp_password) {
372                 errno = ENOMEM;
373                 return NULL;
374         }
375
376         make_nmb_name(&calling, smbc_getNetbiosName(context), 0x0);
377         make_nmb_name(&called , server, 0x20);
378
379         DEBUG(4,("SMBC_server: server_n=[%s] server=[%s]\n", server_n, server));
380
381         DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
382
383 again:
384
385         zero_sockaddr(&ss);
386
387         /* have to open a new connection */
388         if ((c = cli_initialise()) == NULL) {
389                 errno = ENOMEM;
390                 return NULL;
391         }
392
393         if (smbc_getOptionUseKerberos(context)) {
394                 c->use_kerberos = True;
395         }
396
397         if (smbc_getOptionFallbackAfterKerberos(context)) {
398                 c->fallback_after_kerberos = True;
399         }
400
401         c->timeout = smbc_getTimeout(context);
402
403         /*
404          * Force use of port 139 for first try if share is $IPC, empty, or
405          * null, so browse lists can work
406          */
407         if (share == NULL || *share == '\0' || is_ipc) {
408                 port_try_first = 139;
409                 port_try_next = 445;
410         } else {
411                 port_try_first = 445;
412                 port_try_next = 139;
413         }
414
415         c->port = port_try_first;
416
417         status = cli_connect(c, server_n, &ss);
418         if (!NT_STATUS_IS_OK(status)) {
419
420                 /* First connection attempt failed.  Try alternate port. */
421                 c->port = port_try_next;
422
423                 status = cli_connect(c, server_n, &ss);
424                 if (!NT_STATUS_IS_OK(status)) {
425                         cli_shutdown(c);
426                         errno = ETIMEDOUT;
427                         return NULL;
428                 }
429         }
430
431         if (!cli_session_request(c, &calling, &called)) {
432                 cli_shutdown(c);
433                 if (strcmp(called.name, "*SMBSERVER")) {
434                         make_nmb_name(&called , "*SMBSERVER", 0x20);
435                         goto again;
436                 } else {  /* Try one more time, but ensure we don't loop */
437
438                         /* Only try this if server is an IP address ... */
439
440                         if (is_ipaddress(server) && !tried_reverse) {
441                                 fstring remote_name;
442                                 struct sockaddr_storage rem_ss;
443
444                                 if (!interpret_string_addr(&rem_ss, server,
445                                                            NI_NUMERICHOST)) {
446                                         DEBUG(4, ("Could not convert IP address "
447                                                   "%s to struct sockaddr_storage\n",
448                                                   server));
449                                         errno = ETIMEDOUT;
450                                         return NULL;
451                                 }
452
453                                 tried_reverse++; /* Yuck */
454
455                                 if (name_status_find("*", 0, 0,
456                                                      &rem_ss, remote_name)) {
457                                         make_nmb_name(&called,
458                                                       remote_name,
459                                                       0x20);
460                                         goto again;
461                                 }
462                         }
463                 }
464                 errno = ETIMEDOUT;
465                 return NULL;
466         }
467
468         DEBUG(4,(" session request ok\n"));
469
470         status = cli_negprot(c);
471
472         if (!NT_STATUS_IS_OK(status)) {
473                 cli_shutdown(c);
474                 errno = ETIMEDOUT;
475                 return NULL;
476         }
477
478         username_used = *pp_username;
479
480         if (!NT_STATUS_IS_OK(cli_session_setup(c, username_used,
481                                                *pp_password,
482                                                strlen(*pp_password),
483                                                *pp_password,
484                                                strlen(*pp_password),
485                                                *pp_workgroup))) {
486
487                 /* Failed.  Try an anonymous login, if allowed by flags. */
488                 username_used = "";
489
490                 if (smbc_getOptionNoAutoAnonymousLogin(context) ||
491                     !NT_STATUS_IS_OK(cli_session_setup(c, username_used,
492                                                        *pp_password, 1,
493                                                        *pp_password, 0,
494                                                        *pp_workgroup))) {
495
496                         cli_shutdown(c);
497                         errno = EPERM;
498                         return NULL;
499                 }
500         }
501
502         DEBUG(4,(" session setup ok\n"));
503
504         if (!cli_send_tconX(c, share, "?????",
505                             *pp_password, strlen(*pp_password)+1)) {
506                 errno = SMBC_errno(context, c);
507                 cli_shutdown(c);
508                 return NULL;
509         }
510
511         DEBUG(4,(" tconx ok\n"));
512
513         /* Determine if this share supports case sensitivity */
514         if (is_ipc) {
515                 DEBUG(4, ("IPC$ so ignore case sensitivity\n"));
516         } else if (!cli_get_fs_attr_info(c, &fs_attrs)) {
517                 DEBUG(4, ("Could not retrieve case sensitivity flag: %s.\n",
518                           cli_errstr(c)));
519
520                 /*
521                  * We can't determine the case sensitivity of the share. We
522                  * have no choice but to use the user-specified case
523                  * sensitivity setting.
524                  */
525                 if (smbc_getOptionCaseSensitive(context)) {
526                         cli_set_case_sensitive(c, True);
527                 } else {
528                         cli_set_case_sensitive(c, False);
529                 }
530         } else {
531                 DEBUG(4, ("Case sensitive: %s\n",
532                           (fs_attrs & FILE_CASE_SENSITIVE_SEARCH
533                            ? "True"
534                            : "False")));
535                 cli_set_case_sensitive(c,
536                                        (fs_attrs & FILE_CASE_SENSITIVE_SEARCH
537                                         ? True
538                                         : False));
539         }
540
541         if (context->internal->smb_encryption_level) {
542                 /* Attempt UNIX smb encryption. */
543                 if (!NT_STATUS_IS_OK(cli_force_encryption(c,
544                                                           username_used,
545                                                           *pp_password,
546                                                           *pp_workgroup))) {
547
548                         /*
549                          * context->smb_encryption_level == 1
550                          * means don't fail if encryption can't be negotiated,
551                          * == 2 means fail if encryption can't be negotiated.
552                          */
553
554                         DEBUG(4,(" SMB encrypt failed\n"));
555
556                         if (context->internal->smb_encryption_level == 2) {
557                                 cli_shutdown(c);
558                                 errno = EPERM;
559                                 return NULL;
560                         }
561                 }
562                 DEBUG(4,(" SMB encrypt ok\n"));
563         }
564
565         /*
566          * Ok, we have got a nice connection
567          * Let's allocate a server structure.
568          */
569
570         srv = SMB_MALLOC_P(SMBCSRV);
571         if (!srv) {
572                 errno = ENOMEM;
573                 goto failed;
574         }
575
576         ZERO_STRUCTP(srv);
577         srv->cli = c;
578         srv->dev = (dev_t)(str_checksum(server) ^ str_checksum(share));
579         srv->no_pathinfo = False;
580         srv->no_pathinfo2 = False;
581         srv->no_nt_session = False;
582
583         /* now add it to the cache (internal or external)  */
584         /* Let the cache function set errno if it wants to */
585         errno = 0;
586         if (smbc_getFunctionAddCachedServer(context)(context, srv,
587                                                      server, share,
588                                                      *pp_workgroup,
589                                                      *pp_username)) {
590                 int saved_errno = errno;
591                 DEBUG(3, (" Failed to add server to cache\n"));
592                 errno = saved_errno;
593                 if (errno == 0) {
594                         errno = ENOMEM;
595                 }
596                 goto failed;
597         }
598
599         DEBUG(2, ("Server connect ok: //%s/%s: %p\n",
600                   server, share, srv));
601
602         DLIST_ADD(context->internal->servers, srv);
603         return srv;
604
605 failed:
606         cli_shutdown(c);
607         if (!srv) {
608                 return NULL;
609         }
610
611         SAFE_FREE(srv);
612         return NULL;
613 }
614
615 /*
616  * Connect to a server for getting/setting attributes, possibly on an existing
617  * connection.  This works similarly to SMBC_server().
618  */
619 SMBCSRV *
620 SMBC_attr_server(TALLOC_CTX *ctx,
621                  SMBCCTX *context,
622                  const char *server,
623                  const char *share,
624                  char **pp_workgroup,
625                  char **pp_username,
626                  char **pp_password)
627 {
628         int flags;
629         struct sockaddr_storage ss;
630         struct cli_state *ipc_cli;
631         struct rpc_pipe_client *pipe_hnd;
632         NTSTATUS nt_status;
633         SMBCSRV *ipc_srv=NULL;
634
635         /*
636          * See if we've already created this special connection.  Reference
637          * our "special" share name '*IPC$', which is an impossible real share
638          * name due to the leading asterisk.
639          */
640         ipc_srv = SMBC_find_server(ctx, context, server, "*IPC$",
641                                    pp_workgroup, pp_username, pp_password);
642         if (!ipc_srv) {
643
644                 /* We didn't find a cached connection.  Get the password */
645                 if (!*pp_password || (*pp_password)[0] == '\0') {
646                         /* ... then retrieve it now. */
647                         SMBC_call_auth_fn(ctx, context, server, share,
648                                           pp_workgroup,
649                                           pp_username,
650                                           pp_password);
651                         if (!*pp_workgroup || !*pp_username || !*pp_password) {
652                                 errno = ENOMEM;
653                                 return NULL;
654                         }
655                 }
656
657                 flags = 0;
658                 if (smbc_getOptionUseKerberos(context)) {
659                         flags |= CLI_FULL_CONNECTION_USE_KERBEROS;
660                 }
661
662                 zero_sockaddr(&ss);
663                 nt_status = cli_full_connection(&ipc_cli,
664                                                 global_myname(), server,
665                                                 &ss, 0, "IPC$", "?????",
666                                                 *pp_username,
667                                                 *pp_workgroup,
668                                                 *pp_password,
669                                                 flags,
670                                                 Undefined, NULL);
671                 if (! NT_STATUS_IS_OK(nt_status)) {
672                         DEBUG(1,("cli_full_connection failed! (%s)\n",
673                                  nt_errstr(nt_status)));
674                         errno = ENOTSUP;
675                         return NULL;
676                 }
677
678                 if (context->internal->smb_encryption_level) {
679                         /* Attempt UNIX smb encryption. */
680                         if (!NT_STATUS_IS_OK(cli_force_encryption(ipc_cli,
681                                                                   *pp_username,
682                                                                   *pp_password,
683                                                                   *pp_workgroup))) {
684
685                                 /*
686                                  * context->smb_encryption_level ==
687                                  * 1 means don't fail if encryption can't be
688                                  * negotiated, == 2 means fail if encryption
689                                  * can't be negotiated.
690                                  */
691
692                                 DEBUG(4,(" SMB encrypt failed on IPC$\n"));
693
694                                 if (context->internal->smb_encryption_level == 2) {
695                                         cli_shutdown(ipc_cli);
696                                         errno = EPERM;
697                                         return NULL;
698                                 }
699                         }
700                         DEBUG(4,(" SMB encrypt ok on IPC$\n"));
701                 }
702
703                 ipc_srv = SMB_MALLOC_P(SMBCSRV);
704                 if (!ipc_srv) {
705                         errno = ENOMEM;
706                         cli_shutdown(ipc_cli);
707                         return NULL;
708                 }
709
710                 ZERO_STRUCTP(ipc_srv);
711                 ipc_srv->cli = ipc_cli;
712
713                 nt_status = cli_rpc_pipe_open_noauth(
714                         ipc_srv->cli, &ndr_table_lsarpc.syntax_id, &pipe_hnd);
715                 if (!NT_STATUS_IS_OK(nt_status)) {
716                         DEBUG(1, ("cli_nt_session_open fail!\n"));
717                         errno = ENOTSUP;
718                         cli_shutdown(ipc_srv->cli);
719                         free(ipc_srv);
720                         return NULL;
721                 }
722
723                 /*
724                  * Some systems don't support
725                  * SEC_RIGHTS_MAXIMUM_ALLOWED, but NT sends 0x2000000
726                  * so we might as well do it too.
727                  */
728
729                 nt_status = rpccli_lsa_open_policy(
730                         pipe_hnd,
731                         talloc_tos(),
732                         True,
733                         GENERIC_EXECUTE_ACCESS,
734                         &ipc_srv->pol);
735
736                 if (!NT_STATUS_IS_OK(nt_status)) {
737                         errno = SMBC_errno(context, ipc_srv->cli);
738                         cli_shutdown(ipc_srv->cli);
739                         return NULL;
740                 }
741
742                 /* now add it to the cache (internal or external) */
743
744                 errno = 0;      /* let cache function set errno if it likes */
745                 if (smbc_getFunctionAddCachedServer(context)(context, ipc_srv,
746                                                              server,
747                                                              "*IPC$",
748                                                              *pp_workgroup,
749                                                              *pp_username)) {
750                         DEBUG(3, (" Failed to add server to cache\n"));
751                         if (errno == 0) {
752                                 errno = ENOMEM;
753                         }
754                         cli_shutdown(ipc_srv->cli);
755                         free(ipc_srv);
756                         return NULL;
757                 }
758
759                 DLIST_ADD(context->internal->servers, ipc_srv);
760         }
761
762         return ipc_srv;
763 }