Im using this function to adjust multiple privileges for the application at the same time but I run into this warning and I dont know how to fix it. I tried to do it with the union and offsetof but it didn't work. How would I allocate more memory for that structure?
#include <Windows.h>
int main()
{
HANDLE hToken;
TOKEN_PRIVILEGES tp = { 0 };
LUID luid1, luid2;
OpenProcessToken(hProcess, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken);
LookupPrivilegeValueW(NULL, SE_DEBUG_NAME, &luid1);
LookupPrivilegeValueW(NULL, SE_SHUTDOWN_NAME, &luid2);
//the code I tried
union {
TOKEN_PRIVILEGES tp;
unsigned char storage[offsetof(TOKEN_PRIVILEGES, Privileges) sizeof(LUID_AND_ATTRIBUTES) * 2];
};
tp.PrivilegeCount = 2;
tp.Privileges[0].Luid = luid1;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
tp.Privileges[1].Luid = luid2; //the warning is here
tp.Privileges[1].Attributes = SE_PRIVILEGE_ENABLED; //and here
AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), NULL, NULL);
}
CodePudding user response:
you can use for instanse such code
union {
::TOKEN_PRIVILEGES tp;
struct {
ULONG PrivilegeCount;
LUID_AND_ATTRIBUTES Privileges[2];
};
};
PrivilegeCount = 2;
Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
Privileges[0].Luid = { SE_DEBUG_PRIVILEGE };
Privileges[1].Attributes = SE_PRIVILEGE_ENABLED;
Privileges[1].Luid = { SE_SHUTDOWN_PRIVILEGE };
AdjustTokenPrivileges(hToken, FALSE, &tp, 0, 0, 0);
also note that 4-th parameter of AdjustTokenPrivileges
BufferLength (where you pass sizeof(TOKEN_PRIVILEGES)
) related to 5-th parameter but not to 3-th (which size also not equal to sizeof(TOKEN_PRIVILEGES)
). so you need pass 0 here.
also not need use LookupPrivilegeValueW
but possible use hardcoded constants, like SE_DEBUG_PRIVILEGE
- it declared in wdm.h
also you not need TOKEN_QUERY
here - this need only if the PreviousState parameter is not NULL,
CodePudding user response:
The point of structures with trailing array of zero (or 1) size is to malloc
a larger memory block and cast it to the struct.
DWORD numPriviledges = 5;
void* buffer = malloc (sizeof(TOKEN_PRIVILEGES) sizeof(LUID_AND_ATTRIBUTES) * (numPriviledges - ANYSIZE_ARRAY));
PTOKEN_PRIVILEGES ptp = (PTOKEN_PRIVILEGES) buffer;
ptp->PrivilegeCount = numPriviledges;
...
ptp->Privileges[4] = something;
...
AdjustTokenPrivileges(hToken, FALSE, ptp, 0, NULL, 0);
ptp = NULL;
free(buffer);
buffer = NULL;
It's not meant to be allocated on stack, that's what the warning is trying to tell you. It's poor man's flexible array member from C99