1

在Windows 上,即使自主ACL (DACL) 为空,即没有人对文件具有权限,文件所有者也可以读写DACL(READ_CONTROLWRITE_DAC访问)。

所以我尝试执行以下操作:

  1. 在文件上设置一个空的 DACL
  2. 获取文件的句柄READ_CONTROL
  3. GetSecurityInfo使用和句柄​​获取安全描述符
  4. 检查 DACL 是否实际为空

但是,使用获取句柄CreateFileW失败并Access is denied出现错误。令人惊讶的是GetFileSecurity,相当于GetSecurityInfofor files 的 , 工作得很好。根据文档GetFileSecurity需要READ_CONTROL访问权限。

为什么CreateFileW在以下示例中失败?

import sys
import win32security
import win32con
import win32file
import ntsecuritycon
import os

path = sys.argv[1]

with open(path, "w"):
    pass  # I am the owner of the file

print("Set empty ACL")
sd = win32security.GetFileSecurity(path, win32security.DACL_SECURITY_INFORMATION)
dacl = win32security.ACL()
sd.SetSecurityDescriptorDacl(1, dacl, 0)
win32security.SetFileSecurity(path, win32security.DACL_SECURITY_INFORMATION, sd)

try:
    print("Ensure that ACL is empty with GetFileSecurity")
    sd = win32security.GetFileSecurity(path, win32security.DACL_SECURITY_INFORMATION)
    dacl = sd.GetSecurityDescriptorDacl()
    assert 0 == dacl.GetAceCount()

    print("Try to ensure that ACL is empty using handle")
    handle = win32file.CreateFileW(
        path,
        ntsecuritycon.READ_CONTROL,
        0,
        None,  # security attributes
        win32con.OPEN_EXISTING,
        0,
        None,
    )
    sd = win32security.GetSecurityInfo(handle, win32security.SE_FILE_OBJECT, win32security.DACL_SECURITY_INFORMATION)
    dacl = sd.GetSecurityDescriptorDacl()
    assert 0 == dacl.GetAceCount()
except Exception as e:
    print("FAILURE:", e)
finally:
    print("Restore inherited ACEs before removing file")
    dacl = win32security.ACL()
    win32security.SetNamedSecurityInfo(
        path, 
        win32security.SE_FILE_OBJECT, 
        win32security.DACL_SECURITY_INFORMATION,
        None,
        None,
        dacl,
        None
    )
    os.unlink(path)

输出:

> python acl-test.py file
Set empty ACL
Ensure that ACL is empty with GetFileSecurity
Try to ensure that ACL is empty using handle
FAILURE: (5, 'CreateFileW', 'Access is denied.')
Restore inherited ACEs before removing file
4

1 回答 1

2

CreateFileW内部调用NtCreateFileDesiredAccess参数为dwDesiredAccess | FILE_READ_ATTRIBUTES | SYNCHRONIZE. 因此,如果您传递dwDesiredAccessas READ_CONTROL,那么它实际上会尝试打开具有READ_CONTROL | FILE_READ_ATTRIBUTES | SYNCHRONIZE访问权限的文件。如果调用者有权访问父文件夹FILE_READ_ATTRIBUTES,则文件系统会隐式授予访问权限。FILE_LIST_DIRECTORY但是,SYNCHRONIZE如果文件具有空 DACL,则不会授予访问权限。

这里的一种解决方案是使用NtOpenFileNtCreateFile为了控制确切的请求访问。

于 2019-10-15T11:58:04.530 回答