是否可以使文件仅可用于某些进程



因此,我试图使文件仅对特定进程可访问,首先通过以下函数找到它:

bool GetProcessSid(PSID* pSID)
{
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (Process32First(snapshot, &entry) == TRUE)
{
while(Process32Next(snapshot, &entry) == TRUE)
{
const char* process_name = "testfileaccess2.exe";
std::string t(process_name);
std::wstring w_process_name(t.begin(), t.end());
if (w_process_name.compare(entry.szExeFile)== 0)
{
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID);
//...
GetSecurityInfo(hProcess,SE_KERNEL_OBJECT, OWNER_SECURITY_INFORMATION,pSID,NULL,NULL,NULL,NULL);

//getsecurityinfo(hprocess,SE_SERVICE) for service
CloseHandle(hProcess);
return TRUE;
}
}
}
return FALSE;
}

工作正常,总是在进程处于活动状态时找到它并返回pSID。然后我创建这样的文件:

PACL pNewDACL = NULL;
PSID process_with_access = NULL;
PSID current_user = NULL;
DWORD sid_size = SECURITY_MAX_SID_SIZE;
SID everyone_sid;
DWORD dwRes;
if (CreateWellKnownSid(WinWorldSid, NULL, &everyone_sid, &sid_size) ==
FALSE) {
throw std::runtime_error("CreateWellKnownSid() failed: " +
std::to_string(GetLastError()));
}
GetProcessSid(&process_with_access);
GetCurrentUserSid(&current_user);
EXPLICIT_ACCESSA ea[2];
ZeroMemory(&ea, 2 * sizeof(EXPLICIT_ACCESSA));
ea[0].grfAccessPermissions = ACCESS_SYSTEM_SECURITY | READ_CONTROL | WRITE_DAC | GENERIC_ALL;
ea[0].grfAccessMode = DENY_ACCESS;
ea[0].grfInheritance = NO_INHERITANCE;
ea[0].Trustee.TrusteeForm = TRUSTEE_IS_SID;
ea[0].Trustee.ptstrName = reinterpret_cast<char*>(process_with_access);
ea[1].grfAccessPermissions = ACCESS_SYSTEM_SECURITY | READ_CONTROL | WRITE_DAC | GENERIC_ALL;
ea[1].grfAccessMode = GRANT_ACCESS;
ea[1].grfInheritance = NO_INHERITANCE;
ea[1].Trustee.TrusteeForm = TRUSTEE_IS_SID;
ea[1].Trustee.ptstrName = reinterpret_cast<char*>(current_user);
dwRes = SetEntriesInAclA(2, ea, NULL, &pNewDACL);
if (ERROR_SUCCESS != dwRes) {
printf("SetEntriesInAcl Error %un", dwRes);
//TODO: goto Cleanup;
}
PSECURITY_DESCRIPTOR pSD = NULL;
// Initialize a security descriptor.  
pSD = (PSECURITY_DESCRIPTOR)LocalAlloc(LPTR,
SECURITY_DESCRIPTOR_MIN_LENGTH);
if (NULL == pSD)
{
printf("error");
}
if (!InitializeSecurityDescriptor(pSD,
SECURITY_DESCRIPTOR_REVISION))
{

printf("error");
}
// Add the ACL to the security descriptor. 
if (!SetSecurityDescriptorDacl(pSD,
TRUE,     // bDaclPresent flag   
pNewDACL,
FALSE))   // not a default DACL
{
printf("error");
}
SECURITY_ATTRIBUTES sa;
// Initialize a security attributes structure.
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = pSD;
sa.bInheritHandle = FALSE;
HANDLE hFile = CreateFileA(filename, GENERIC_ALL, 0, &sa, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
CloseHandle(hFile);

目前,它只为进程的父进程设置访问权限,而不是进程本身。那么,我想要实现的目标是否可能呢?

否,Windows的安全性基于用户/组访问列表。可以设置一个进程,使其以某个特定用户的身份运行,然后限制对该用户的访问,但任何以管理员或本地系统身份运行的程序都可以绕过该保护。

针对此类程序,你能做的最好的事情就是防止意外访问,而不是恶意访问。

最新更新