Domanda

I would like to know how can I set the permissions of a windows file?
Something like chmod(), instead it's a windows.

For example:

Create the file example.exe, and set its permissions in a way that only the owner of this file can execute it.

I read that there's an ACL API for c somewhere, but I didn't quite get it.

È stato utile?

Soluzione

It's a lot more work than chmod!

I have taken the liberty of creating the file AFTER creating the security descriptor - it is safer. If you do things the other way around (create the file first) then there is a short time when the required access is not set.

Try this:

#include <windows.h>
#include <AclAPI.h>
#include <Lmcons.h>

int main()
{
    SECURITY_DESCRIPTOR sd;
    EXPLICIT_ACCESS ea[1];
    PACL pDacl;
    SECURITY_ATTRIBUTES sa;

    TCHAR UserBuffer[UNLEN+1];
    DWORD ulen = UNLEN;
    GetUserName(UserBuffer, &ulen);

    InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);

    BuildExplicitAccessWithName(&ea[0], UserBuffer, GENERIC_EXECUTE, 
                        SET_ACCESS, NO_INHERITANCE);

    SetEntriesInAcl(1, ea, NULL, &pDacl);
    SetSecurityDescriptorDacl(&sd, TRUE, pDacl, FALSE);

    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    sa.bInheritHandle = FALSE;
    sa.lpSecurityDescriptor = &sd;

    CreateFileA("c:\\temp\\example.exe", GENERIC_EXECUTE, 0, &sa,
        CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0);

    return 0;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top