how to change the ACLs from c++?

13,044

Solution 1

Use following code

#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);
}

Solution 2

I assume you mean on a Windows system? You need to use the NTFS part of the Win32 API, which is what cacls uses. Browse through MSDN, it'll be in there somewhere. Eg SetSecurityInfo

Share:
13,044
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    How to change the ACLs from c++?

    Can anyone help me to do the following from c++ without any confirmations:

    cacls c:\personal\file.txt /d everyone
    
  • Wyatt O'Day
    Wyatt O'Day over 12 years
    Just note: this code comes from the MSDN article "Creating a Security Descriptor for a New Object in C++".
  • Robert Basler
    Robert Basler over 10 years
    Comment says "The ACE will allow read access to the key" but grfAccessPermissions defines the permissions, so setting it to 0xFFFFFFFF gives EVERYTHING.
  • Nathan Kidd
    Nathan Kidd about 6 years
    @RobertBasler I removed the contradictory code comment.