Fix problem reported by Tom Lee <tlee2951@gmail.com> - when calculating the share...
[Samba.git] / source3 / smbd / service.c
blobf57e57f6701fa3a5718919cef90a126a5c2fc4e7
1 /*
2 Unix SMB/CIFS implementation.
3 service (connection) opening and closing
4 Copyright (C) Andrew Tridgell 1992-1998
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
20 #include "includes.h"
21 #include "system/filesys.h"
22 #include "../lib/tsocket/tsocket.h"
23 #include "smbd/smbd.h"
24 #include "smbd/globals.h"
25 #include "../librpc/gen_ndr/netlogon.h"
26 #include "../libcli/security/security.h"
27 #include "printing/pcap.h"
28 #include "passdb/lookup_sid.h"
29 #include "auth.h"
31 extern userdom_struct current_user_info;
33 static bool canonicalize_connect_path(connection_struct *conn)
35 bool ret;
36 char *resolved_name = SMB_VFS_REALPATH(conn,conn->connectpath);
37 if (!resolved_name) {
38 return false;
40 ret = set_conn_connectpath(conn,resolved_name);
41 SAFE_FREE(resolved_name);
42 return ret;
45 /****************************************************************************
46 Ensure when setting connectpath it is a canonicalized (no ./ // or ../)
47 absolute path stating in / and not ending in /.
48 Observent people will notice a similarity between this and check_path_syntax :-).
49 ****************************************************************************/
51 bool set_conn_connectpath(connection_struct *conn, const char *connectpath)
53 char *destname;
54 char *d;
55 const char *s = connectpath;
56 bool start_of_name_component = true;
58 if (connectpath == NULL || connectpath[0] == '\0') {
59 return false;
62 /* Allocate for strlen + '\0' + possible leading '/' */
63 destname = (char *)SMB_MALLOC(strlen(connectpath) + 2);
64 if (!destname) {
65 return false;
67 d = destname;
69 *d++ = '/'; /* Always start with root. */
71 while (*s) {
72 if (*s == '/') {
73 /* Eat multiple '/' */
74 while (*s == '/') {
75 s++;
77 if ((d > destname + 1) && (*s != '\0')) {
78 *d++ = '/';
80 start_of_name_component = True;
81 continue;
84 if (start_of_name_component) {
85 if ((s[0] == '.') && (s[1] == '.') && (s[2] == '/' || s[2] == '\0')) {
86 /* Uh oh - "/../" or "/..\0" ! */
88 /* Go past the ../ or .. */
89 if (s[2] == '/') {
90 s += 3;
91 } else {
92 s += 2; /* Go past the .. */
95 /* If we just added a '/' - delete it */
96 if ((d > destname) && (*(d-1) == '/')) {
97 *(d-1) = '\0';
98 d--;
101 /* Are we at the start ? Can't go back further if so. */
102 if (d <= destname) {
103 *d++ = '/'; /* Can't delete root */
104 continue;
106 /* Go back one level... */
107 /* Decrement d first as d points to the *next* char to write into. */
108 for (d--; d > destname; d--) {
109 if (*d == '/') {
110 break;
113 /* We're still at the start of a name component, just the previous one. */
114 continue;
115 } else if ((s[0] == '.') && ((s[1] == '\0') || s[1] == '/')) {
116 /* Component of pathname can't be "." only - skip the '.' . */
117 if (s[1] == '/') {
118 s += 2;
119 } else {
120 s++;
122 continue;
126 if (!(*s & 0x80)) {
127 *d++ = *s++;
128 } else {
129 size_t siz;
130 /* Get the size of the next MB character. */
131 next_codepoint(s,&siz);
132 switch(siz) {
133 case 5:
134 *d++ = *s++;
135 /*fall through*/
136 case 4:
137 *d++ = *s++;
138 /*fall through*/
139 case 3:
140 *d++ = *s++;
141 /*fall through*/
142 case 2:
143 *d++ = *s++;
144 /*fall through*/
145 case 1:
146 *d++ = *s++;
147 break;
148 default:
149 break;
152 start_of_name_component = false;
154 *d = '\0';
156 /* And must not end in '/' */
157 if (d > destname + 1 && (*(d-1) == '/')) {
158 *(d-1) = '\0';
161 DEBUG(10,("set_conn_connectpath: service %s, connectpath = %s\n",
162 lp_servicename(SNUM(conn)), destname ));
164 string_set(&conn->connectpath, destname);
165 SAFE_FREE(destname);
166 return true;
169 /****************************************************************************
170 Load parameters specific to a connection/service.
171 ****************************************************************************/
173 bool set_current_service(connection_struct *conn, uint16 flags, bool do_chdir)
175 int snum;
177 if (!conn) {
178 last_conn = NULL;
179 return(False);
182 conn->lastused_count++;
184 snum = SNUM(conn);
186 if (do_chdir &&
187 vfs_ChDir(conn,conn->connectpath) != 0 &&
188 vfs_ChDir(conn,conn->origpath) != 0) {
189 DEBUG(((errno!=EACCES)?0:3),("chdir (%s) failed, reason: %s\n",
190 conn->connectpath, strerror(errno)));
191 return(False);
194 if ((conn == last_conn) && (last_flags == flags)) {
195 return(True);
198 last_conn = conn;
199 last_flags = flags;
201 /* Obey the client case sensitivity requests - only for clients that support it. */
202 switch (lp_casesensitive(snum)) {
203 case Auto:
205 /* We need this uglyness due to DOS/Win9x clients that lie about case insensitivity. */
206 enum remote_arch_types ra_type = get_remote_arch();
207 if ((ra_type != RA_SAMBA) && (ra_type != RA_CIFSFS)) {
208 /* Client can't support per-packet case sensitive pathnames. */
209 conn->case_sensitive = False;
210 } else {
211 conn->case_sensitive = !(flags & FLAG_CASELESS_PATHNAMES);
214 break;
215 case True:
216 conn->case_sensitive = True;
217 break;
218 default:
219 conn->case_sensitive = False;
220 break;
222 return(True);
225 static int load_registry_service(const char *servicename)
227 if (!lp_registry_shares()) {
228 return -1;
231 if ((servicename == NULL) || (*servicename == '\0')) {
232 return -1;
235 if (strequal(servicename, GLOBAL_NAME)) {
236 return -2;
239 if (!process_registry_service(servicename)) {
240 return -1;
243 return lp_servicenumber(servicename);
246 void load_registry_shares(void)
248 DEBUG(8, ("load_registry_shares()\n"));
249 if (!lp_registry_shares()) {
250 return;
253 process_registry_shares();
255 return;
258 /****************************************************************************
259 Add a home service. Returns the new service number or -1 if fail.
260 ****************************************************************************/
262 int add_home_service(const char *service, const char *username, const char *homedir)
264 int iHomeService;
266 if (!service || !homedir || homedir[0] == '\0')
267 return -1;
269 if ((iHomeService = lp_servicenumber(HOMES_NAME)) < 0) {
270 if ((iHomeService = load_registry_service(HOMES_NAME)) < 0) {
271 return -1;
276 * If this is a winbindd provided username, remove
277 * the domain component before adding the service.
278 * Log a warning if the "path=" parameter does not
279 * include any macros.
283 const char *p = strchr(service,*lp_winbind_separator());
285 /* We only want the 'user' part of the string */
286 if (p) {
287 service = p + 1;
291 if (!lp_add_home(service, iHomeService, username, homedir)) {
292 return -1;
295 return lp_servicenumber(service);
300 * Find a service entry.
302 * @param service is modified (to canonical form??)
305 int find_service(TALLOC_CTX *ctx, const char *service_in, char **p_service_out)
307 int iService;
309 if (!service_in) {
310 return -1;
313 /* First make a copy. */
314 *p_service_out = talloc_strdup(ctx, service_in);
315 if (!*p_service_out) {
316 return -1;
319 all_string_sub(*p_service_out,"\\","/",0);
321 iService = lp_servicenumber(*p_service_out);
323 /* now handle the special case of a home directory */
324 if (iService < 0) {
325 char *phome_dir = get_user_home_dir(ctx, *p_service_out);
327 if(!phome_dir) {
329 * Try mapping the servicename, it may
330 * be a Windows to unix mapped user name.
332 if(map_username(ctx, *p_service_out, p_service_out)) {
333 if (*p_service_out == NULL) {
334 /* Out of memory. */
335 return -1;
337 phome_dir = get_user_home_dir(
338 ctx, *p_service_out);
342 DEBUG(3,("checking for home directory %s gave %s\n",*p_service_out,
343 phome_dir?phome_dir:"(NULL)"));
345 iService = add_home_service(*p_service_out,*p_service_out /* 'username' */, phome_dir);
348 /* If we still don't have a service, attempt to add it as a printer. */
349 if (iService < 0) {
350 int iPrinterService;
352 if ((iPrinterService = lp_servicenumber(PRINTERS_NAME)) < 0) {
353 iPrinterService = load_registry_service(PRINTERS_NAME);
355 if (iPrinterService >= 0) {
356 DEBUG(3,("checking whether %s is a valid printer name...\n",
357 *p_service_out));
358 if (pcap_printername_ok(*p_service_out)) {
359 DEBUG(3,("%s is a valid printer name\n",
360 *p_service_out));
361 DEBUG(3,("adding %s as a printer service\n",
362 *p_service_out));
363 lp_add_printer(*p_service_out, iPrinterService);
364 iService = lp_servicenumber(*p_service_out);
365 if (iService < 0) {
366 DEBUG(0,("failed to add %s as a printer service!\n",
367 *p_service_out));
369 } else {
370 DEBUG(3,("%s is not a valid printer name\n",
371 *p_service_out));
376 /* Check for default vfs service? Unsure whether to implement this */
377 if (iService < 0) {
380 if (iService < 0) {
381 iService = load_registry_service(*p_service_out);
384 /* Is it a usershare service ? */
385 if (iService < 0 && *lp_usershare_path()) {
386 /* Ensure the name is canonicalized. */
387 strlower_m(*p_service_out);
388 iService = load_usershare_service(*p_service_out);
391 /* just possibly it's a default service? */
392 if (iService < 0) {
393 char *pdefservice = lp_defaultservice();
394 if (pdefservice &&
395 *pdefservice &&
396 !strequal(pdefservice, *p_service_out)
397 && !strstr_m(*p_service_out,"..")) {
399 * We need to do a local copy here as lp_defaultservice()
400 * returns one of the rotating lp_string buffers that
401 * could get overwritten by the recursive find_service() call
402 * below. Fix from Josef Hinteregger <joehtg@joehtg.co.at>.
404 char *defservice = talloc_strdup(ctx, pdefservice);
406 if (!defservice) {
407 goto fail;
410 /* Disallow anything except explicit share names. */
411 if (strequal(defservice,HOMES_NAME) ||
412 strequal(defservice, PRINTERS_NAME) ||
413 strequal(defservice, "IPC$")) {
414 TALLOC_FREE(defservice);
415 goto fail;
418 iService = find_service(ctx, defservice, p_service_out);
419 if (!*p_service_out) {
420 TALLOC_FREE(defservice);
421 iService = -1;
422 goto fail;
424 if (iService >= 0) {
425 all_string_sub(*p_service_out, "_","/",0);
426 iService = lp_add_service(*p_service_out, iService);
428 TALLOC_FREE(defservice);
432 if (iService >= 0) {
433 if (!VALID_SNUM(iService)) {
434 DEBUG(0,("Invalid snum %d for %s\n",iService,
435 *p_service_out));
436 iService = -1;
440 fail:
442 if (iService < 0) {
443 DEBUG(3,("find_service() failed to find service %s\n",
444 *p_service_out));
447 return (iService);
451 /****************************************************************************
452 do some basic sainity checks on the share.
453 This function modifies dev, ecode.
454 ****************************************************************************/
456 static NTSTATUS share_sanity_checks(struct client_address *client_id, int snum,
457 fstring dev)
459 if (!lp_snum_ok(snum) ||
460 !allow_access(lp_hostsdeny(snum), lp_hostsallow(snum),
461 client_id->name, client_id->addr)) {
462 return NT_STATUS_ACCESS_DENIED;
465 if (dev[0] == '?' || !dev[0]) {
466 if (lp_print_ok(snum)) {
467 fstrcpy(dev,"LPT1:");
468 } else if (strequal(lp_fstype(snum), "IPC")) {
469 fstrcpy(dev, "IPC");
470 } else {
471 fstrcpy(dev,"A:");
475 strupper_m(dev);
477 if (lp_print_ok(snum)) {
478 if (!strequal(dev, "LPT1:")) {
479 return NT_STATUS_BAD_DEVICE_TYPE;
481 } else if (strequal(lp_fstype(snum), "IPC")) {
482 if (!strequal(dev, "IPC")) {
483 return NT_STATUS_BAD_DEVICE_TYPE;
485 } else if (!strequal(dev, "A:")) {
486 return NT_STATUS_BAD_DEVICE_TYPE;
489 /* Behave as a printer if we are supposed to */
490 if (lp_print_ok(snum) && (strcmp(dev, "A:") == 0)) {
491 fstrcpy(dev, "LPT1:");
494 return NT_STATUS_OK;
498 * Go through lookup_name etc to find the force'd group.
500 * Create a new token from src_token, replacing the primary group sid with the
501 * one found.
504 static NTSTATUS find_forced_group(bool force_user,
505 int snum, const char *username,
506 struct dom_sid *pgroup_sid,
507 gid_t *pgid)
509 NTSTATUS result = NT_STATUS_NO_SUCH_GROUP;
510 TALLOC_CTX *frame = talloc_stackframe();
511 struct dom_sid group_sid;
512 enum lsa_SidType type;
513 char *groupname;
514 bool user_must_be_member = False;
515 gid_t gid;
517 groupname = talloc_strdup(talloc_tos(), lp_force_group(snum));
518 if (groupname == NULL) {
519 DEBUG(1, ("talloc_strdup failed\n"));
520 result = NT_STATUS_NO_MEMORY;
521 goto done;
524 if (groupname[0] == '+') {
525 user_must_be_member = True;
526 groupname += 1;
529 groupname = talloc_string_sub(talloc_tos(), groupname,
530 "%S", lp_servicename(snum));
531 if (groupname == NULL) {
532 DEBUG(1, ("talloc_string_sub failed\n"));
533 result = NT_STATUS_NO_MEMORY;
534 goto done;
537 if (!lookup_name_smbconf(talloc_tos(), groupname,
538 LOOKUP_NAME_ALL|LOOKUP_NAME_GROUP,
539 NULL, NULL, &group_sid, &type)) {
540 DEBUG(10, ("lookup_name_smbconf(%s) failed\n",
541 groupname));
542 goto done;
545 if ((type != SID_NAME_DOM_GRP) && (type != SID_NAME_ALIAS) &&
546 (type != SID_NAME_WKN_GRP)) {
547 DEBUG(10, ("%s is a %s, not a group\n", groupname,
548 sid_type_lookup(type)));
549 goto done;
552 if (!sid_to_gid(&group_sid, &gid)) {
553 DEBUG(10, ("sid_to_gid(%s) for %s failed\n",
554 sid_string_dbg(&group_sid), groupname));
555 goto done;
559 * If the user has been forced and the forced group starts with a '+',
560 * then we only set the group to be the forced group if the forced
561 * user is a member of that group. Otherwise, the meaning of the '+'
562 * would be ignored.
565 if (force_user && user_must_be_member) {
566 if (user_in_group_sid(username, &group_sid)) {
567 sid_copy(pgroup_sid, &group_sid);
568 *pgid = gid;
569 DEBUG(3,("Forced group %s for member %s\n",
570 groupname, username));
571 } else {
572 DEBUG(0,("find_forced_group: forced user %s is not a member "
573 "of forced group %s. Disallowing access.\n",
574 username, groupname ));
575 result = NT_STATUS_MEMBER_NOT_IN_GROUP;
576 goto done;
578 } else {
579 sid_copy(pgroup_sid, &group_sid);
580 *pgid = gid;
581 DEBUG(3,("Forced group %s\n", groupname));
584 result = NT_STATUS_OK;
585 done:
586 TALLOC_FREE(frame);
587 return result;
590 /****************************************************************************
591 Create an auth_serversupplied_info structure for a connection_struct
592 ****************************************************************************/
594 static NTSTATUS create_connection_session_info(struct smbd_server_connection *sconn,
595 TALLOC_CTX *mem_ctx, int snum,
596 struct auth_serversupplied_info *vuid_serverinfo,
597 DATA_BLOB password,
598 struct auth_serversupplied_info **presult)
600 if (lp_guest_only(snum)) {
601 return make_server_info_guest(mem_ctx, presult);
604 if (vuid_serverinfo != NULL) {
606 struct auth_serversupplied_info *result;
609 * This is the normal security != share case where we have a
610 * valid vuid from the session setup. */
612 if (vuid_serverinfo->guest) {
613 if (!lp_guest_ok(snum)) {
614 DEBUG(2, ("guest user (from session setup) "
615 "not permitted to access this share "
616 "(%s)\n", lp_servicename(snum)));
617 return NT_STATUS_ACCESS_DENIED;
619 } else {
620 if (!user_ok_token(vuid_serverinfo->unix_name,
621 vuid_serverinfo->info3->base.domain.string,
622 vuid_serverinfo->security_token, snum)) {
623 DEBUG(2, ("user '%s' (from session setup) not "
624 "permitted to access this share "
625 "(%s)\n",
626 vuid_serverinfo->unix_name,
627 lp_servicename(snum)));
628 return NT_STATUS_ACCESS_DENIED;
632 result = copy_serverinfo(mem_ctx, vuid_serverinfo);
633 if (result == NULL) {
634 return NT_STATUS_NO_MEMORY;
637 *presult = result;
638 return NT_STATUS_OK;
641 if (lp_security() == SEC_SHARE) {
643 fstring user;
644 bool guest;
646 /* add the sharename as a possible user name if we
647 are in share mode security */
649 add_session_user(sconn, lp_servicename(snum));
651 /* shall we let them in? */
653 if (!authorise_login(sconn, snum,user,password,&guest)) {
654 DEBUG( 2, ( "Invalid username/password for [%s]\n",
655 lp_servicename(snum)) );
656 return NT_STATUS_WRONG_PASSWORD;
659 return make_serverinfo_from_username(mem_ctx, user, guest,
660 presult);
663 DEBUG(0, ("invalid VUID (vuser) but not in security=share\n"));
664 return NT_STATUS_ACCESS_DENIED;
667 /****************************************************************************
668 set relavent user and group settings corresponding to force user/group
669 configuration for the given snum.
670 ****************************************************************************/
672 NTSTATUS set_conn_force_user_group(connection_struct *conn, int snum)
674 NTSTATUS status;
676 if (*lp_force_user(snum)) {
679 * Replace conn->session_info with a completely faked up one
680 * from the username we are forced into :-)
683 char *fuser;
684 struct auth_serversupplied_info *forced_serverinfo;
686 fuser = talloc_string_sub(conn, lp_force_user(snum), "%S",
687 lp_const_servicename(snum));
688 if (fuser == NULL) {
689 return NT_STATUS_NO_MEMORY;
692 status = make_serverinfo_from_username(
693 conn, fuser, conn->session_info->guest,
694 &forced_serverinfo);
695 if (!NT_STATUS_IS_OK(status)) {
696 return status;
699 TALLOC_FREE(conn->session_info);
700 conn->session_info = forced_serverinfo;
702 conn->force_user = true;
703 DEBUG(3,("Forced user %s\n", fuser));
707 * If force group is true, then override
708 * any groupid stored for the connecting user.
711 if (*lp_force_group(snum)) {
713 status = find_forced_group(
714 conn->force_user, snum, conn->session_info->unix_name,
715 &conn->session_info->security_token->sids[1],
716 &conn->session_info->utok.gid);
718 if (!NT_STATUS_IS_OK(status)) {
719 return status;
723 * We need to cache this gid, to use within
724 * change_to_user() separately from the conn->session_info
725 * struct. We only use conn->session_info directly if
726 * "force_user" was set.
728 conn->force_group_gid = conn->session_info->utok.gid;
731 return NT_STATUS_OK;
734 /****************************************************************************
735 Setup the share access mask for a connection.
736 ****************************************************************************/
738 static void create_share_access_mask(connection_struct *conn, int snum)
740 const struct security_token *token = conn->session_info->security_token;
742 share_access_check(token,
743 lp_servicename(snum),
744 MAXIMUM_ALLOWED_ACCESS,
745 &conn->share_access);
747 if (security_token_has_privilege(token, SEC_PRIV_SECURITY)) {
748 conn->share_access |= SEC_FLAG_SYSTEM_SECURITY;
750 if (security_token_has_privilege(token, SEC_PRIV_RESTORE)) {
751 conn->share_access |= (SEC_RIGHTS_PRIV_RESTORE);
753 if (security_token_has_privilege(token, SEC_PRIV_BACKUP)) {
754 conn->share_access |= (SEC_RIGHTS_PRIV_BACKUP);
756 if (security_token_has_privilege(token, SEC_PRIV_TAKE_OWNERSHIP)) {
757 conn->share_access |= (SEC_STD_WRITE_OWNER);
761 /****************************************************************************
762 Make a connection, given the snum to connect to, and the vuser of the
763 connecting user if appropriate.
764 ****************************************************************************/
766 static connection_struct *make_connection_snum(struct smbd_server_connection *sconn,
767 connection_struct *conn,
768 int snum, user_struct *vuser,
769 DATA_BLOB password,
770 const char *pdev,
771 NTSTATUS *pstatus)
773 struct smb_filename *smb_fname_cpath = NULL;
774 fstring dev;
775 int ret;
776 bool on_err_call_dis_hook = false;
777 bool claimed_connection = false;
778 uid_t effuid;
779 gid_t effgid;
780 NTSTATUS status;
782 fstrcpy(dev, pdev);
784 *pstatus = share_sanity_checks(&sconn->client_id, snum, dev);
785 if (NT_STATUS_IS_ERR(*pstatus)) {
786 goto err_root_exit;
789 conn->params->service = snum;
791 status = create_connection_session_info(sconn,
792 conn, snum, vuser ? vuser->session_info : NULL, password,
793 &conn->session_info);
795 if (!NT_STATUS_IS_OK(status)) {
796 DEBUG(1, ("create_connection_session_info failed: %s\n",
797 nt_errstr(status)));
798 *pstatus = status;
799 goto err_root_exit;
802 if ((lp_guest_only(snum)) || (lp_security() == SEC_SHARE)) {
803 conn->force_user = true;
806 add_session_user(sconn, conn->session_info->unix_name);
808 conn->num_files_open = 0;
809 conn->lastused = conn->lastused_count = time(NULL);
810 conn->used = True;
811 conn->printer = (strncmp(dev,"LPT",3) == 0);
812 conn->ipc = ( (strncmp(dev,"IPC",3) == 0) ||
813 ( lp_enable_asu_support() && strequal(dev,"ADMIN$")) );
815 /* Case options for the share. */
816 if (lp_casesensitive(snum) == Auto) {
817 /* We will be setting this per packet. Set to be case
818 * insensitive for now. */
819 conn->case_sensitive = False;
820 } else {
821 conn->case_sensitive = (bool)lp_casesensitive(snum);
824 conn->case_preserve = lp_preservecase(snum);
825 conn->short_case_preserve = lp_shortpreservecase(snum);
827 conn->encrypt_level = lp_smb_encrypt(snum);
829 conn->veto_list = NULL;
830 conn->hide_list = NULL;
831 conn->veto_oplock_list = NULL;
832 conn->aio_write_behind_list = NULL;
834 conn->read_only = lp_readonly(SNUM(conn));
836 status = set_conn_force_user_group(conn, snum);
837 if (!NT_STATUS_IS_OK(status)) {
838 *pstatus = status;
839 return NULL;
842 conn->vuid = (vuser != NULL) ? vuser->vuid : UID_FIELD_INVALID;
845 char *s = talloc_sub_advanced(talloc_tos(),
846 lp_servicename(SNUM(conn)),
847 conn->session_info->unix_name,
848 conn->connectpath,
849 conn->session_info->utok.gid,
850 conn->session_info->sanitized_username,
851 conn->session_info->info3->base.domain.string,
852 lp_pathname(snum));
853 if (!s) {
854 *pstatus = NT_STATUS_NO_MEMORY;
855 goto err_root_exit;
858 if (!set_conn_connectpath(conn,s)) {
859 TALLOC_FREE(s);
860 *pstatus = NT_STATUS_NO_MEMORY;
861 goto err_root_exit;
863 DEBUG(3,("Connect path is '%s' for service [%s]\n",s,
864 lp_servicename(snum)));
865 TALLOC_FREE(s);
869 * New code to check if there's a share security descripter
870 * added from NT server manager. This is done after the
871 * smb.conf checks are done as we need a uid and token. JRA.
875 create_share_access_mask(conn, snum);
877 if ((conn->share_access & FILE_WRITE_DATA) == 0) {
878 if ((conn->share_access & FILE_READ_DATA) == 0) {
879 /* No access, read or write. */
880 DEBUG(0,("make_connection: connection to %s "
881 "denied due to security "
882 "descriptor.\n",
883 lp_servicename(snum)));
884 *pstatus = NT_STATUS_ACCESS_DENIED;
885 goto err_root_exit;
886 } else {
887 conn->read_only = True;
890 /* Initialise VFS function pointers */
892 if (!smbd_vfs_init(conn)) {
893 DEBUG(0, ("vfs_init failed for service %s\n",
894 lp_servicename(snum)));
895 *pstatus = NT_STATUS_BAD_NETWORK_NAME;
896 goto err_root_exit;
899 /* ROOT Activities: */
900 /* explicitly check widelinks here so that we can correctly warn
901 * in the logs. */
902 widelinks_warning(snum);
905 * Enforce the max connections parameter.
908 if ((lp_max_connections(snum) > 0)
909 && (count_current_connections(lp_servicename(SNUM(conn)), True) >=
910 lp_max_connections(snum))) {
912 DEBUG(1, ("Max connections (%d) exceeded for %s\n",
913 lp_max_connections(snum), lp_servicename(snum)));
914 *pstatus = NT_STATUS_INSUFFICIENT_RESOURCES;
915 goto err_root_exit;
919 * Get us an entry in the connections db
921 if (!claim_connection(conn, lp_servicename(snum))) {
922 DEBUG(1, ("Could not store connections entry\n"));
923 *pstatus = NT_STATUS_INTERNAL_DB_ERROR;
924 goto err_root_exit;
926 claimed_connection = true;
928 /* Invoke VFS make connection hook - this must be the first
929 filesystem operation that we do. */
931 if (SMB_VFS_CONNECT(conn, lp_servicename(snum),
932 conn->session_info->unix_name) < 0) {
933 DEBUG(0,("make_connection: VFS make connection failed!\n"));
934 *pstatus = NT_STATUS_UNSUCCESSFUL;
935 goto err_root_exit;
938 /* Any error exit after here needs to call the disconnect hook. */
939 on_err_call_dis_hook = true;
941 if ((!conn->printer) && (!conn->ipc)) {
942 conn->notify_ctx = notify_init(conn,
943 sconn_server_id(sconn),
944 sconn->msg_ctx,
945 smbd_event_context(),
946 conn);
950 * Fix compatibility issue pointed out by Volker.
951 * We pass the conn->connectpath to the preexec
952 * scripts as a parameter, so attempt to canonicalize
953 * it here before calling the preexec scripts.
954 * We ignore errors here, as it is possible that
955 * the conn->connectpath doesn't exist yet and
956 * the preexec scripts will create them.
959 (void)canonicalize_connect_path(conn);
961 /* Preexecs are done here as they might make the dir we are to ChDir
962 * to below */
963 /* execute any "root preexec = " line */
964 if (*lp_rootpreexec(snum)) {
965 char *cmd = talloc_sub_advanced(talloc_tos(),
966 lp_servicename(SNUM(conn)),
967 conn->session_info->unix_name,
968 conn->connectpath,
969 conn->session_info->utok.gid,
970 conn->session_info->sanitized_username,
971 conn->session_info->info3->base.domain.string,
972 lp_rootpreexec(snum));
973 DEBUG(5,("cmd=%s\n",cmd));
974 ret = smbrun(cmd,NULL);
975 TALLOC_FREE(cmd);
976 if (ret != 0 && lp_rootpreexec_close(snum)) {
977 DEBUG(1,("root preexec gave %d - failing "
978 "connection\n", ret));
979 *pstatus = NT_STATUS_ACCESS_DENIED;
980 goto err_root_exit;
984 /* USER Activites: */
985 if (!change_to_user(conn, conn->vuid)) {
986 /* No point continuing if they fail the basic checks */
987 DEBUG(0,("Can't become connected user!\n"));
988 *pstatus = NT_STATUS_LOGON_FAILURE;
989 goto err_root_exit;
992 effuid = geteuid();
993 effgid = getegid();
995 /* Remember that a different vuid can connect later without these
996 * checks... */
998 /* Preexecs are done here as they might make the dir we are to ChDir
999 * to below */
1001 /* execute any "preexec = " line */
1002 if (*lp_preexec(snum)) {
1003 char *cmd = talloc_sub_advanced(talloc_tos(),
1004 lp_servicename(SNUM(conn)),
1005 conn->session_info->unix_name,
1006 conn->connectpath,
1007 conn->session_info->utok.gid,
1008 conn->session_info->sanitized_username,
1009 conn->session_info->info3->base.domain.string,
1010 lp_preexec(snum));
1011 ret = smbrun(cmd,NULL);
1012 TALLOC_FREE(cmd);
1013 if (ret != 0 && lp_preexec_close(snum)) {
1014 DEBUG(1,("preexec gave %d - failing connection\n",
1015 ret));
1016 *pstatus = NT_STATUS_ACCESS_DENIED;
1017 goto err_root_exit;
1021 #ifdef WITH_FAKE_KASERVER
1022 if (lp_afs_share(snum)) {
1023 afs_login(conn);
1025 #endif
1028 * we've finished with the user stuff - go back to root
1029 * so the SMB_VFS_STAT call will only fail on path errors,
1030 * not permission problems.
1032 change_to_root_user();
1033 /* ROOT Activites: */
1036 * If widelinks are disallowed we need to canonicalise the connect
1037 * path here to ensure we don't have any symlinks in the
1038 * connectpath. We will be checking all paths on this connection are
1039 * below this directory. We must do this after the VFS init as we
1040 * depend on the realpath() pointer in the vfs table. JRA.
1042 if (!lp_widelinks(snum)) {
1043 if (!canonicalize_connect_path(conn)) {
1044 DEBUG(0, ("canonicalize_connect_path failed "
1045 "for service %s, path %s\n",
1046 lp_servicename(snum),
1047 conn->connectpath));
1048 *pstatus = NT_STATUS_BAD_NETWORK_NAME;
1049 goto err_root_exit;
1053 /* Add veto/hide lists */
1054 if (!IS_IPC(conn) && !IS_PRINT(conn)) {
1055 set_namearray( &conn->veto_list, lp_veto_files(snum));
1056 set_namearray( &conn->hide_list, lp_hide_files(snum));
1057 set_namearray( &conn->veto_oplock_list, lp_veto_oplocks(snum));
1058 set_namearray( &conn->aio_write_behind_list,
1059 lp_aio_write_behind(snum));
1061 status = create_synthetic_smb_fname(talloc_tos(), conn->connectpath,
1062 NULL, NULL, &smb_fname_cpath);
1063 if (!NT_STATUS_IS_OK(status)) {
1064 *pstatus = status;
1065 goto err_root_exit;
1068 /* win2000 does not check the permissions on the directory
1069 during the tree connect, instead relying on permission
1070 check during individual operations. To match this behaviour
1071 I have disabled this chdir check (tridge) */
1072 /* the alternative is just to check the directory exists */
1074 if ((ret = SMB_VFS_STAT(conn, smb_fname_cpath)) != 0 ||
1075 !S_ISDIR(smb_fname_cpath->st.st_ex_mode)) {
1076 if (ret == 0 && !S_ISDIR(smb_fname_cpath->st.st_ex_mode)) {
1077 DEBUG(0,("'%s' is not a directory, when connecting to "
1078 "[%s]\n", conn->connectpath,
1079 lp_servicename(snum)));
1080 } else {
1081 DEBUG(0,("'%s' does not exist or permission denied "
1082 "when connecting to [%s] Error was %s\n",
1083 conn->connectpath, lp_servicename(snum),
1084 strerror(errno) ));
1086 *pstatus = NT_STATUS_BAD_NETWORK_NAME;
1087 goto err_root_exit;
1089 conn->base_share_dev = smb_fname_cpath->st.st_ex_dev;
1091 string_set(&conn->origpath,conn->connectpath);
1093 /* Figure out the characteristics of the underlying filesystem. This
1094 * assumes that all the filesystem mounted withing a share path have
1095 * the same characteristics, which is likely but not guaranteed.
1098 conn->fs_capabilities = SMB_VFS_FS_CAPABILITIES(conn, &conn->ts_res);
1101 * Print out the 'connected as' stuff here as we need
1102 * to know the effective uid and gid we will be using
1103 * (at least initially).
1106 if( DEBUGLVL( IS_IPC(conn) ? 3 : 1 ) ) {
1107 dbgtext( "%s (%s) ", get_remote_machine_name(),
1108 conn->sconn->client_id.addr );
1109 dbgtext( "%s", srv_is_signing_active(sconn) ? "signed " : "");
1110 dbgtext( "connect to service %s ", lp_servicename(snum) );
1111 dbgtext( "initially as user %s ",
1112 conn->session_info->unix_name );
1113 dbgtext( "(uid=%d, gid=%d) ", (int)effuid, (int)effgid );
1114 dbgtext( "(pid %d)\n", (int)sys_getpid() );
1117 return(conn);
1119 err_root_exit:
1120 TALLOC_FREE(smb_fname_cpath);
1121 /* We must exit this function as root. */
1122 if (geteuid() != 0) {
1123 change_to_root_user();
1125 if (on_err_call_dis_hook) {
1126 /* Call VFS disconnect hook */
1127 SMB_VFS_DISCONNECT(conn);
1129 if (claimed_connection) {
1130 yield_connection(conn, lp_servicename(snum));
1132 return NULL;
1135 /****************************************************************************
1136 Make a connection to a service from SMB1. Internal interface.
1137 ****************************************************************************/
1139 static connection_struct *make_connection_smb1(struct smbd_server_connection *sconn,
1140 int snum, user_struct *vuser,
1141 DATA_BLOB password,
1142 const char *pdev,
1143 NTSTATUS *pstatus)
1145 connection_struct *ret_conn = NULL;
1146 connection_struct *conn = conn_new(sconn);
1147 if (!conn) {
1148 DEBUG(0,("make_connection_smb1: Couldn't find free connection.\n"));
1149 *pstatus = NT_STATUS_INSUFFICIENT_RESOURCES;
1150 return NULL;
1152 ret_conn = make_connection_snum(sconn,
1153 conn,
1154 snum,
1155 vuser,
1156 password,
1157 pdev,
1158 pstatus);
1159 if (ret_conn != conn) {
1160 conn_free(conn);
1161 return NULL;
1163 return conn;
1166 /****************************************************************************
1167 Make a connection to a service from SMB2. External SMB2 interface.
1168 We must set cnum before claiming connection.
1169 ****************************************************************************/
1171 connection_struct *make_connection_smb2(struct smbd_server_connection *sconn,
1172 struct smbd_smb2_tcon *tcon,
1173 user_struct *vuser,
1174 DATA_BLOB password,
1175 const char *pdev,
1176 NTSTATUS *pstatus)
1178 connection_struct *ret_conn = NULL;
1179 connection_struct *conn = conn_new(sconn);
1180 if (!conn) {
1181 DEBUG(0,("make_connection_smb2: Couldn't find free connection.\n"));
1182 *pstatus = NT_STATUS_INSUFFICIENT_RESOURCES;
1183 return NULL;
1185 conn->cnum = tcon->tid;
1186 ret_conn = make_connection_snum(sconn,
1187 conn,
1188 tcon->snum,
1189 vuser,
1190 password,
1191 pdev,
1192 pstatus);
1193 if (ret_conn != conn) {
1194 conn_free(conn);
1195 return NULL;
1197 return conn;
1200 /****************************************************************************
1201 Make a connection to a service. External SMB1 interface.
1203 * @param service
1204 ****************************************************************************/
1206 connection_struct *make_connection(struct smbd_server_connection *sconn,
1207 const char *service_in, DATA_BLOB password,
1208 const char *pdev, uint16 vuid,
1209 NTSTATUS *status)
1211 uid_t euid;
1212 user_struct *vuser = NULL;
1213 char *service = NULL;
1214 fstring dev;
1215 int snum = -1;
1217 fstrcpy(dev, pdev);
1219 /* This must ONLY BE CALLED AS ROOT. As it exits this function as
1220 * root. */
1221 if (!non_root_mode() && (euid = geteuid()) != 0) {
1222 DEBUG(0,("make_connection: PANIC ERROR. Called as nonroot "
1223 "(%u)\n", (unsigned int)euid ));
1224 smb_panic("make_connection: PANIC ERROR. Called as nonroot\n");
1227 if (conn_num_open(sconn) > 2047) {
1228 *status = NT_STATUS_INSUFF_SERVER_RESOURCES;
1229 return NULL;
1232 if(lp_security() != SEC_SHARE) {
1233 vuser = get_valid_user_struct(sconn, vuid);
1234 if (!vuser) {
1235 DEBUG(1,("make_connection: refusing to connect with "
1236 "no session setup\n"));
1237 *status = NT_STATUS_ACCESS_DENIED;
1238 return NULL;
1242 /* Logic to try and connect to the correct [homes] share, preferably
1243 without too many getpwnam() lookups. This is particulary nasty for
1244 winbind usernames, where the share name isn't the same as unix
1245 username.
1247 The snum of the homes share is stored on the vuser at session setup
1248 time.
1251 if (strequal(service_in,HOMES_NAME)) {
1252 if(lp_security() != SEC_SHARE) {
1253 DATA_BLOB no_pw = data_blob_null;
1254 if (vuser->homes_snum == -1) {
1255 DEBUG(2, ("[homes] share not available for "
1256 "this user because it was not found "
1257 "or created at session setup "
1258 "time\n"));
1259 *status = NT_STATUS_BAD_NETWORK_NAME;
1260 return NULL;
1262 DEBUG(5, ("making a connection to [homes] service "
1263 "created at session setup time\n"));
1264 return make_connection_smb1(sconn,
1265 vuser->homes_snum,
1266 vuser, no_pw,
1267 dev, status);
1268 } else {
1269 /* Security = share. Try with
1270 * current_user_info.smb_name as the username. */
1271 if (*current_user_info.smb_name) {
1272 char *unix_username = NULL;
1273 (void)map_username(talloc_tos(),
1274 current_user_info.smb_name,
1275 &unix_username);
1276 snum = find_service(talloc_tos(),
1277 unix_username,
1278 &unix_username);
1279 if (!unix_username) {
1280 *status = NT_STATUS_NO_MEMORY;
1282 return NULL;
1284 if (snum != -1) {
1285 DEBUG(5, ("making a connection to 'homes' "
1286 "service %s based on "
1287 "security=share\n", service_in));
1288 return make_connection_smb1(sconn,
1289 snum, NULL,
1290 password,
1291 dev, status);
1294 } else if ((lp_security() != SEC_SHARE) && (vuser->homes_snum != -1)
1295 && strequal(service_in,
1296 lp_servicename(vuser->homes_snum))) {
1297 DATA_BLOB no_pw = data_blob_null;
1298 DEBUG(5, ("making a connection to 'homes' service [%s] "
1299 "created at session setup time\n", service_in));
1300 return make_connection_smb1(sconn,
1301 vuser->homes_snum,
1302 vuser, no_pw,
1303 dev, status);
1306 service = talloc_strdup(talloc_tos(), service_in);
1307 if (!service) {
1308 *status = NT_STATUS_NO_MEMORY;
1309 return NULL;
1312 strlower_m(service);
1314 snum = find_service(talloc_tos(), service, &service);
1315 if (!service) {
1316 *status = NT_STATUS_NO_MEMORY;
1317 return NULL;
1320 if (snum < 0) {
1321 if (strequal(service,"IPC$") ||
1322 (lp_enable_asu_support() && strequal(service,"ADMIN$"))) {
1323 DEBUG(3,("refusing IPC connection to %s\n", service));
1324 *status = NT_STATUS_ACCESS_DENIED;
1325 return NULL;
1328 DEBUG(3,("%s (%s) couldn't find service %s\n",
1329 get_remote_machine_name(),
1330 tsocket_address_string(
1331 sconn->remote_address, talloc_tos()),
1332 service));
1333 *status = NT_STATUS_BAD_NETWORK_NAME;
1334 return NULL;
1337 /* Handle non-Dfs clients attempting connections to msdfs proxy */
1338 if (lp_host_msdfs() && (*lp_msdfs_proxy(snum) != '\0')) {
1339 DEBUG(3, ("refusing connection to dfs proxy share '%s' "
1340 "(pointing to %s)\n",
1341 service, lp_msdfs_proxy(snum)));
1342 *status = NT_STATUS_BAD_NETWORK_NAME;
1343 return NULL;
1346 DEBUG(5, ("making a connection to 'normal' service %s\n", service));
1348 return make_connection_smb1(sconn, snum, vuser,
1349 password,
1350 dev, status);
1353 /****************************************************************************
1354 Close a cnum.
1355 ****************************************************************************/
1357 void close_cnum(connection_struct *conn, uint16 vuid)
1359 file_close_conn(conn);
1361 if (!IS_IPC(conn)) {
1362 dptr_closecnum(conn);
1365 change_to_root_user();
1367 DEBUG(IS_IPC(conn)?3:1, ("%s (%s) closed connection to service %s\n",
1368 get_remote_machine_name(),
1369 conn->sconn->client_id.addr,
1370 lp_servicename(SNUM(conn))));
1372 /* Call VFS disconnect hook */
1373 SMB_VFS_DISCONNECT(conn);
1375 yield_connection(conn, lp_servicename(SNUM(conn)));
1377 /* make sure we leave the directory available for unmount */
1378 vfs_ChDir(conn, "/");
1380 /* execute any "postexec = " line */
1381 if (*lp_postexec(SNUM(conn)) &&
1382 change_to_user(conn, vuid)) {
1383 char *cmd = talloc_sub_advanced(talloc_tos(),
1384 lp_servicename(SNUM(conn)),
1385 conn->session_info->unix_name,
1386 conn->connectpath,
1387 conn->session_info->utok.gid,
1388 conn->session_info->sanitized_username,
1389 conn->session_info->info3->base.domain.string,
1390 lp_postexec(SNUM(conn)));
1391 smbrun(cmd,NULL);
1392 TALLOC_FREE(cmd);
1393 change_to_root_user();
1396 change_to_root_user();
1397 /* execute any "root postexec = " line */
1398 if (*lp_rootpostexec(SNUM(conn))) {
1399 char *cmd = talloc_sub_advanced(talloc_tos(),
1400 lp_servicename(SNUM(conn)),
1401 conn->session_info->unix_name,
1402 conn->connectpath,
1403 conn->session_info->utok.gid,
1404 conn->session_info->sanitized_username,
1405 conn->session_info->info3->base.domain.string,
1406 lp_rootpostexec(SNUM(conn)));
1407 smbrun(cmd,NULL);
1408 TALLOC_FREE(cmd);
1411 conn_free(conn);