Share and NTFS Permissions
Introduction
The file server permissions must be carefully implemented to provide appropriate access to content. This involves locking down permissions on the share and physical folders.
Permissions
The following table lists permissions that were used for the file server share and folders in the Shared Hosting Setup mentioned in the Planning the Web Hosting Architecture section of the Hosting Guidance. Based on the shared hosting environment used, server administrators should develop their own custom permissions that meet their needs.
Path | Permissions | Reason |
---|---|---|
\server\share$ (share) | Domain Administrators — Full Control Domain Users — Change MachineAccounts$ — Full Control | The share permissions need to allow the administrators and site accounts to access the content. The physical path will be restricted to actual needed permissions. |
E:\Content (physical path of share) | Administrators — Full Control System — Full Control | This is the folder that is shared. It does not need permissions for any accounts aside from the built-in Administrators group and System account. |
E:\Content (the container for a specific site or user) | Administrators — Full Control System — Full Control Site Owner — List Folder Contents | This folder is used as a container for folders like the site’s home directory and its log files. The Site Owner should be able to read this folder but does not need write access. |
E:\Content \wwwroot (the IIS home directory for the site) | Administrators — Full Control System — Full Control Site Owner — Modify App Pool Username — Read | This is the root of a Web site belonging to the user account. App Pool Username is used as both the application pool identity and the anonymous username for the Web site. |
E:\Content \Logs (the container for logs) | Administrators — Full Control System — Full Control Site Owner — Read | Note that this folder for logs is stored ABOVE the root of the site, so that it is not accessible by a visitor browsing the site. It is not recommended that you put this folder in any location accessible from a Web browser, for security purposes. |
E:\Content \Logs\FailedReqLogs (the container for failed request tracing logs) | Administrators — Full Control System — Full Control App Pool Username — Full Control | This is the folder used to store Failed Request log files, which allow a site owner to diagnose problems with their Web site. These logs are written by the worker process identity, App Pool Username. |
E:\Content \Logs\W3SVCLogFiles (the container for W3SVC traffic logs) | Administrators — Full Control System — Full Control MachineAccount$ — Full Control | This is the folder used to store the log files for the Web site, which allow a site owner to see their traffic patterns. If the server administrator does not wish to share these files or wants to provide an alternate method for determining traffic, these files can be stored elsewhere. MachineAccount$ is the Web server’s machine account, as these logs are written by HTTP.SYS. |
Configuring Permissions
To configure permissions for the share
In Windows Explorer, right-click the folder you want to share, and then click Properties.
On the Sharing tab, click Advanced Sharing.
In User Account Control, click Continue to accept the prompt that Windows needs your permission to perform the action.
In the Advanced Sharing dialog box, check Share this folder.
Set the Share name and Comments as appropriate. To make the share hidden, add a $ to the end of the share name.
Hiding a share means that when you connect to \server you will not see the share unless you specifically enter the path \server\share$.
Click Permissions.
In the Permissions dialog box, remove the Everyone group, if it exists.
Add the appropriate user or group that should have access to the share.
Specify the permissions (Full Control, Change, Read) for the user or group.
Click OK twice and then click Close to close the dialog boxes.
To configure permissions for the folder structure
- In Windows Explorer, right-click the folder you want to share, and then click Properties.
- On the Security tab, click Edit.
- In the Permissions dialog box, add the appropriate users or groups that should have access at each level of the folder structure.
- Specify the permissions (Full control, Modify, Read & execute, List folder contents, Read, Write Special permissions) for the users or groups.
- Click OK twice to close the dialog boxes.
See C# and PowerShell Scripts Samples for a sample script to configure default documents. as an example of creation of a share and setting of permissions.
Windows share and permissions
Disclaimer: данный пост несёт исключительно теоретическую ценность. Никакой практической пользы от него вы не получите.
Блуждая по просторам интернетов, наткнулся на один свой пост, который уже похоронен в истории веков.
Как известно, при доступе к общим ресурсам (сетевым папкам) мы различаем 2 типа прав:
- Share Permissions
- NTFS Rights
Оба типа прав влияют на результирующие (эффективные) права пользователя при доступе к сетевому ресурсу. В общем смысле эффективные права будут являть собой наиболее ограничивающее разрешение из обоих типов прав. Например, на ресурс установлено право Share Permissions = Read, а NTFS = Full Control, то исходя из наиболее ограничивающего разрешения эффективным будет Read. Если Share Permissions = FullControl, а NTFS = Modify, то эффективным правом для пользователя будет Modify. Вот такая несложная схема. Т.е. там, где прав меньше, те и будут ваши 🙂 Как известно, эта проблема редко кого касается, т.к. обычно на уровне Share Permissions выдают FullControl на ресурс и дальше уже права регулируют за счёт NTFS. Как бы всё правильно, но если раскопать вопрос глубже, то появляются интересные моменты.
http://technet.microsoft.com/en-us/library/cc784499(WS.10).aspx – по этой ссылке можно найти сопоставление Share Permissons с NTFS Rights. Такое сопоставление удобно тем, что рассчитывать оба типа прав можно с использованием одних и тех же классов .NET, без необходимости городить отдельные библиотеки и классы для управления списками доступа ACL. Грубо говоря, фактическое сопоставление выглядит вот так (по схеме Share Permission = NTFS Right):
- Read = ReadAndExecute
- Change = Modify + DeleteSubfoldersAndFiles
- FullControl = FullControl
Но это в общем смысле. Внутри Windows это выглядит чуть сложнее, т.к. там появляется хитрое право Synchronize. Т.е. таблица уже имеет такой вид:
- Read = ReadAndExecute + Synchronize
- Change = Modify + DeleteSubfoldersAndFiles + Synchronize
- FullControl = FullControl (в обоих случаях Synchronize уже включено).
Обратите внимание на наличие DeleteSubfoldersAndFiles в Change. Windows оба этих типа прав рассчитывает через класс .NET – FileSystemRights и фактически их содержит не в текстовом виде, а в числовом. Вот как выглядят числовые сопоставления текстовым правам:
Как видно из таблички, FullControl является суммой всех перечисленных прав. Давайте разберём, что такое Modify, т.е. какие права нужно иметь для получения этого Modify:
- ListFolder — 1
- CreateFiles — 2
- Createfolders(Directories) — 4
- ReadExtendedAttributes — 8
- WriteExtendedAttributes — 16
- Traverse — 32
- ReadAttributes — 128
- WriteAttributes — 256
- Delete — 65536
- ReadPermissions – 131072
В этом легко убедиться, т.к. если мы сложим все эти цифры, то получим 197055 (как и отражено в таблице). Обратимся к ссылке: http://vpodans.spaces.live.com/blog/cns!BB1419A2CFC1E008!170.entry.
Теперь нам нужно преобразовать права доступа в класс FileSystemRights. Преобразование типа прав так же было ранее мною описано в первой части Управление ACL в PowerShell . Пара слов о том, чем отличаются права Read, Change и Full Control в контексте разрешений сетевого ресурса от контекста разрешений NTFS. Этим правам в NTFS сопоставляются Read + Execute, Modify и Full Control соответственно и плюс право Synchonize. Поэтому давайте запишем маску доступа в переменную $ace:
$ace.AccessMask = [System.Security.AccessControl.FileSystemRights]»Modify, Synchronize»
Чтобы получить Change, нам достаточно к этому числу (197055) прибавить Synchronize (1048576):
Вот это в понимании SecurityDescriptor является эквивалентом нашего Change. Но я чуть ранее просил вас обратить внимание на наличие DeleteSubfoldersAndFiles в Change. Но тут его уже всунуть просто некуда, т.к. 1245695 (это число получится, если к Modify прибавить Synchronize и DeleteSubfoldersAndFiles) не будет распознано SecurityDescriptor’ом в методе SetShareInfo, как валидное число.
Иными словами, что у нас получается:
1) Change в понимании фактических прав является суммой: Modify + DeleteSubfoldersAndDiles + Synchronize
2) Change в понимании .NET является суммой: Modify + Synchronize
И чем вызвано такое несоответствие мне неизвестно. Но в качестве теоретической справки это может быть полезным.
How permissions are handled when you copy and move files and folders
This article describes how Windows Explorer handles file and folder permissions in different situations.
Original product version: В Windows 10 — all editions, Windows Server 2012 R2
Original KB number: В 310316
Summary
In Microsoft Windows 2000, in Windows Server 2003, and in Windows XP, you have the option of using either the FAT32 file system or the NTFS file system. When you use NTFS, you can grant permissions to your folders and files to control access to those objects. When you copy or move a file or folder on an NTFS volume, how Windows Explorer handles the permissions on the object varies, depending on whether the object is copied or moved within the same NTFS volume or to a different volume.
More information
By default, an object inherits permissions from its parent object, either at the time of creation or when it is copied or moved to its parent folder. The only exception to this rule occurs when you move an object to a different folder on the same volume. In this case, the original permissions are retained.
Additionally, note the following rules:
The Everyone group is granted Allow Full Control permissions to the root of each NTFS drive.
Deny permissions always take precedence over Allow permissions.
Explicit permissions take precedence over inherited permissions.
If NTFS permissions conflict, for example, if group and user permissions are contradictory, the most liberal permissions take precedence.
Permissions are cumulative.
To preserve permissions when files and folders are copied or moved, use the Xcopy.exe utility with the /O or the /X switch.
The object’s original permissions will be added to inheritable permissions in the new location.
To add an object’s original permissions to inheritable permissions when you copy or move an object, use the Xcopy.exe utility with the -O and -X switches.
To preserve existing permissions without adding inheritable permissions from the parent folder, use the Robocopy.exe utility, which is available in the Windows 2000 Resource Kit.
You can modify how Windows Explorer handles permissions when objects are copied or moved to another NTFS volume. When you copy or move an object to another volume, the object inherits the permissions of its new folder. However, if you want to modify this behavior to preserve the original permissions, modify the registry as follows.
This section, method, or task contains steps that tell you how to modify the registry. However, serious problems might occur if you modify the registry incorrectly. Therefore, make sure that you follow these steps carefully. For added protection, back up the registry before you modify it. Then, you can restore the registry if a problem occurs. For more information about how to back up and restore the registry, see How to back up and restore the registry in Windows.
Click Start, click Run, type regedit in the Open box, and then press ENTER.
Locate and then click the registry key: HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer .
On the Edit menu, click Add Value, and then add the following registry value:
- Value name: ForceCopyAclwithFile
- Data type: DWORD
- Value data: 1
Exit Registry Editor.
You can modify how Windows Explorer handles permissions when objects are moved in the same NTFS volume. As mentioned, when an object is moved within the same volume, the object preserves its permissions by default. However, if you want to modify this behavior so that the object inherits the permissions from the parent folder, modify the registry as follows:
Click Start, click Run, type regedit, and then press ENTER.
Locate and then click the registry subkey: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer .
On the Edit menu, click Add Value, and then add the following registry value:
- Value name: MoveSecurityAttributes
- Data type: DWORD
- Value data: 0
Exit Registry Editor.
Make sure that the user account that is used to move the object has the Change Permissions permission set. If the permission is not set, grant the Change Permissions permission to the user account.
The MoveSecurityAttributes registry value only applies to Windows XP and to Windows Server 2003. The value does not affect Windows 2000.