如何从c ++更改ACL?

时间:2009-05-26 12:55:03

标签: c++ windows file-permissions

如何从c ++更改ACL?

任何人都可以帮助我在没有任何确认的情况下从c ++执行以下操作:

cacls c:\personal\file.txt /d everyone

3 个答案:

答案 0 :(得分:13)

使用以下代码

#include <Accctrl.h>
#include <Aclapi.h>
void SetFilePermission(LPCTSTR FileName)
{
    PSID pEveryoneSID = NULL;
    PACL pACL = NULL;
    EXPLICIT_ACCESS ea[1];
    SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY;

    // Create a well-known SID for the Everyone group.
    AllocateAndInitializeSid(&SIDAuthWorld, 1,
                     SECURITY_WORLD_RID,
                     0, 0, 0, 0, 0, 0, 0,
                     &pEveryoneSID);

    // Initialize an EXPLICIT_ACCESS structure for an ACE.
    ZeroMemory(&ea, 1 * sizeof(EXPLICIT_ACCESS));
    ea[0].grfAccessPermissions = 0xFFFFFFFF;
    ea[0].grfAccessMode = DENY_ACCESS;
    ea[0].grfInheritance= NO_INHERITANCE;
    ea[0].Trustee.TrusteeForm = TRUSTEE_IS_SID;
    ea[0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
    ea[0].Trustee.ptstrName  = (LPTSTR) pEveryoneSID;

    // Create a new ACL that contains the new ACEs.
    SetEntriesInAcl(1, ea, NULL, &pACL);

    // Initialize a security descriptor.  
    PSECURITY_DESCRIPTOR pSD = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR, 
                                SECURITY_DESCRIPTOR_MIN_LENGTH); 

    InitializeSecurityDescriptor(pSD,SECURITY_DESCRIPTOR_REVISION);

    // Add the ACL to the security descriptor. 
    SetSecurityDescriptorDacl(pSD, 
            TRUE,     // bDaclPresent flag   
            pACL, 
            FALSE);   // not a default DACL 


    //Change the security attributes
    SetFileSecurity(FileName, DACL_SECURITY_INFORMATION, pSD);

    if (pEveryoneSID) 
        FreeSid(pEveryoneSID);
    if (pACL) 
        LocalFree(pACL);
    if (pSD) 
        LocalFree(pSD);
}

答案 1 :(得分:1)

我认为你的意思是在Windows系统上?您需要使用Win32 API的NTFS部分,这是cacls使用的部分。浏览MSDN,它会在某处。例如SetSecurityInfo

答案 2 :(得分:0)

如果您不想使用API​​(即SetNamedSecurityInfo),您可以绕过提示,如下所示:

echo y|cacls filename /d everyone

由于echo是内置函数,要从程序中调用该命令行,您可能必须运行:

cmd.exe /c echo y|cacls filename /d everyone