I want to take file ownership using win32 api, and I want my code to work on both xp and win7
anyway, here is what i came up with
Function that changes the ownership of the file
int ChangeFileOwner()
{
HANDLE token;
char *filename = "c:\\file1.txt"; //(not owned by the current user)
DWORD len;
PSECURITY_DESCRIPTOR security = NULL;
int retValue = 1;
PSID sid;
// Get the privileges you need
if (OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &token)) {
if(!SetPrivilege("SeTakeOwnershipPrivilege", 1))retValue=0;
if(!SetPrivilege("SeSecurityPrivilege", 1))retValue=0;
if(!SetPrivilege("SeBackupPrivilege", 1))retValue=0;
if(!SetPrivilege("SeRestorePrivilege", 1))retValue=0;
} else retValue = 0;
// Create the security descriptor
if (retValue) {
GetFileSecurity(filename, OWNER_SECURITY_INFORMATION, security, 0, &len);
security = (PSECURITY_DESCRIPTOR)malloc(len);
if (!InitializeSecurityDescriptor(security,SECURITY_DESCRIPTOR_REVISION))
retValue = 0;
}
// Get the sid for the username
if (retValue) {
GetLogonSID(token, &sid) ;
}
// Set the sid to be the new owner
if (retValue && !SetSecurityDescriptorOwner(security, sid, 0))
retValue = 0;
// Save the security descriptor
if (retValue)
retValue = SetFileSecurity(filename, OWNER_SECURITY_INFORMATION, security);
if (security) free(security);
return retValue;
}
Function to get the current user SID
BOOL GetLogonSID (HANDLE hToken, PSID *ppsid)
{
BOOL bSuccess = FALSE;
DWORD dwIndex;
DWORD dwLength = 0;
PTOKEN_GROUPS ptg = NULL;
// Get required buffer size and allocate the TOKEN_GROUPS buffer.
GetTokenInformation(hToken,TokenGroups,(LPVOID) ptg,0,&dwLength) ;
ptg = (PTOKEN_GROUPS)HeapAlloc(GetProcessHeap(),
HEAP_ZERO_MEMORY, dwLength);
// Get the token group information from the access token.
GetTokenInformation(hToken,TokenGroups,(LPVOID) ptg,dwLength,&dwLength) ;
// Loop through the groups to find the logon SID.
for (dwIndex = 0; dwIndex < ptg->GroupCount; dwIndex++)
if ((ptg->Groups[dwIndex].Attributes & SE_GROUP_LOGON_ID)
== SE_GROUP_LOGON_ID)
{
// Found the logon SID; make a copy of it.
dwLength = GetLengthSid(ptg->Groups[dwIndex].Sid);
*ppsid = (PSID) HeapAlloc(GetProcessHeap(),
HEAP_ZERO_MEMORY, dwLength);
CopySid(dwLength, *ppsid, ptg->Groups[dwIndex].Sid);
break;
}
return TRUE;
}
Code To Set Privilege
int SetPrivilege(char *privilege, int enable)
{
TOKEN_PRIVILEGES tp;
LUID luid;
HANDLE token;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token)) return 0;
if (!LookupPrivilegeValue(NULL, privilege, &luid)) return 0;
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
if (enable) tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
else tp.Privileges[0].Attributes = 0;
// Enable the privilege or disable all privileges.
return AdjustTokenPrivileges(token, 0, &tp, NULL, NULL, NULL);
}
Related
I have a program running on a QEMU VM. The program running inside this VM gets notified by a program on the host via interrupts and using QEMU ivshmem. The program on the host creates an eventfd and sends this file descriptor to QEMU when the VM starts. The program in the guest then opens a VFIO group device and sets an interrupt request fd on this device. We can then add the interrupt fd to epoll and epoll_wait to wait for notifications from the host.
The thing is that I want a 1-1 matching between the times the host writes to the eventfd and the number of events that are signaled in epoll_wait. For this I decided to use EFD_SEMAPHORE for the evenfds on the host and the guest. From my understanding, every time I write an 8 byte integer with value 1, the eventfd_counter is incremented by 1. Then every time the eventfd is read, the counter is decremented by 1 (different from a regular eventfd where each read clears the whole counter). For some reason, I am not getting the desired behaviour, so I was wondering if either eventfds with the EFD_SEMAPHORE flags are not properly supported by VFIO or QEMUs ivshmem.
Below is a simplified version of the parts I think are relevant and how I setup the notification system. I hope the code below is not too verbose. I tried to reduce the number of irrelevant parts (there is too much other code in the middle that is not particularly relevant to the problem) but not 100% sure what might be relevant or not.
Code host uses to signal guest
int ivshmem_uxsocket_send_int(int fd, int64_t i)
{
int n;
struct iovec iov = {
.iov_base = &i,
.iov_len = sizeof(i),
};
struct msghdr msg = {
.msg_name = NULL,
.msg_namelen = 0,
.msg_iov = &iov,
.msg_iovlen = 1,
.msg_control = NULL,
.msg_controllen = 0,
.msg_flags = 0,
};
if ((n = sendmsg(fd, &msg, 0)) != sizeof(int64_t))
{
return -1;
}
return n;
}
int ivshmem_uxsocket_sendfd(int uxfd, int fd, int64_t i)
{
int n;
struct cmsghdr *chdr;
/* Need to pass at least one byte of data to send control data */
struct iovec iov = {
.iov_base = &i,
.iov_len = sizeof(i),
};
/* Allocate a char array but use a union to ensure that it
is aligned properly */
union {
char buf[CMSG_SPACE(sizeof(fd))];
struct cmsghdr align;
} cmsg;
memset(&cmsg, 0, sizeof(cmsg));
/* Add control data (file descriptor) to msg */
struct msghdr msg = {
.msg_name = NULL,
.msg_namelen = 0,
.msg_iov = &iov,
.msg_iovlen = 1,
.msg_control = &cmsg,
.msg_controllen = sizeof(cmsg),
.msg_flags = 0,
};
/* Set message header to describe ancillary data */
chdr = CMSG_FIRSTHDR(&msg);
chdr->cmsg_level = SOL_SOCKET;
chdr->cmsg_type = SCM_RIGHTS;
chdr->cmsg_len = CMSG_LEN(sizeof(int));
memcpy(CMSG_DATA(chdr), &fd, sizeof(fd));
if ((n = sendmsg(uxfd, &msg, 0)) != sizeof(i))
{
return -1;
}
return n;
}
/* SETUP IVSHMEM WITH QEMU AND PASS THE EVENTFD USED TO
NOTIFY THE GUEST */
int ivshmem_uxsocket_accept()
{
int ret;
int cfd, ifd, nfd;
int64_t version = IVSHMEM_PROTOCOL_VERSION;
uint64_t hostid = HOST_PEERID;
int vmid = 0
/* Accept connection from qemu ivshmem */
if ((cfd = accept(uxfd, NULL, NULL)) < 0)
{
return -1;
}
/* Send protocol version as required by qemu ivshmem */
ret = ivshmem_uxsocket_send_int(cfd, version);
if (ret < 0)
{
return -1;
}
/* Send vm id to qemu */
ret = ivshmem_uxsocket_send_int(cfd, vmid);
if (ret < 0)
{
return -1;
}
/* Send shared memory fd to qemu */
ret = ivshmem_uxsocket_sendfd(cfd, shm_fd, -1);
if (ret < 0)
{
return -1;
}
/* Eventfd used by guest to notify host */
if ((nfd = eventfd(0, EFD_SEMAPHORE | EFD_NONBLOCK)) < 0)
{
return -1;
}
/* Ivshmem protocol requires to send host id
with the notify fd */
ret = ivshmem_uxsocket_sendfd(cfd, nfd, hostid);
if (ret < 0)
{
return -1;
}
/* THIS IS THE EVENTFD OF INTEREST TO US: USED BY HOST
TO NOTIFY GUEST */
if ((ifd = eventfd(0, EFD_SEMAPHORE | EFD_NONBLOCK)) < 0)
{
return -1;
}
ret = ivshmem_uxsocket_sendfd(cfd, ifd, vmid);
if (ret < 0)
{
return -1;
}
if (epoll_ctl(epfd, EPOLL_CTL_ADD, cfd, &ev) < 0)
{
return -1;
}
return 0;
}
/* NOW EVERY TIME WE WANT TO NOTIFY THE GUEST
WE CALL THE FOLLOWING FUNCTION */
int notify_guest(int fd)
{
int ret;
uint64_t buf = 1;
ret = write(fd, &buf, sizeof(uint64_t));
if (ret < sizeof(uint64_t))
{
return -1;
}
return 0;
}
Code guest uses to receive notifications from host
/* THIS FUNCTION SETS THE IRQ THAT RECEIVES THE
NOTIFICATIONS FROM THE HOST */
int vfio_set_irq(int dev)
{
int fd;
struct vfio_irq_set *irq_set;
char buf[sizeof(struct vfio_irq_set) + sizeof(int)];
if ((fd = eventfd(0, EFD_SEMAPHORE | EFD_NONBLOCK)) < 0)
{
return -1;
}
irq_set = (struct vfio_irq_set *) buf;
irq_set->argsz = sizeof(buf);
irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER;
irq_set->index = 2;
irq_set->start = 0;
irq_set->count = 1;
memcpy(&irq_set->data, &fd, sizeof(int));
if (ioctl(dev, VFIO_DEVICE_SET_IRQS, irq_set) < 0)
{
return -1;
}
return irq_fd;
}
/* The guest sets up the ivshmem region from QEMU and sets the
interrupt request. */
int vfio_init()
{
int cont, group, irq_fd;
struct epoll_event ev;
struct vfio_group_status g_status = { .argsz = sizeof(g_status) };
struct vfio_device_info device_info = { .argsz = sizeof(device_info) };
/* Create vfio container */
if ((cont = open("/dev/vfio/vfio", O_RDWR)) < 0)
{
return -1;
}
/* Check API version of container */
if (ioctl(cont, VFIO_GET_API_VERSION) != VFIO_API_VERSION)
{
return -1;
}
if (!ioctl(cont, VFIO_CHECK_EXTENSION, VFIO_NOIOMMU_IOMMU))
{
return -1;
}
/* Open the vfio group */
if((group = open(VFIO_GROUP, O_RDWR)) < 0)
{
return -1;
}
/* Test if group is viable and available */
ioctl(group, VFIO_GROUP_GET_STATUS, &g_status);
if (!(g_status.flags & VFIO_GROUP_FLAGS_VIABLE))
{
return -1;
}
/* Add group to container */
if (ioctl(group, VFIO_GROUP_SET_CONTAINER, &cont) < 0)
{
return -1;
}
/* Enable desired IOMMU model */
if (ioctl(cont, VFIO_SET_IOMMU, VFIO_NOIOMMU_IOMMU) < 0)
{
return -1;
}
/* Get file descriptor for device */
if ((dev = ioctl(group, VFIO_GROUP_GET_DEVICE_FD, VFIO_PCI_DEV)) < 0)
{
return -1;
}
/* Get device info */
if (ioctl(dev, VFIO_DEVICE_GET_INFO, &device_info) < 0)
{
return -1;
}
/* Set interrupt request fd */
if ((irq_fd = vfio_set_irq(dev)) < 0)
{
return -1
}
/* Add interrupt request fd to interest list */
if (vfio_subscribe_irq() < 0)
{
return -1;
}
/* Do other shm setup stuff not related to the interrupt
request */
ev.events = EPOLLIN;
ev.data.ptr = EP_NOTIFY;
ev.data.fd = irq_fd;
if (epoll_ctl(epfd, EPOLL_CTL_ADD, irq_fd, &ev) != 0)
{
return -1;
}
return 0;
}
int ivshmem_drain_evfd(int fd)
{
int ret;
uint64_t buf;
ret = read(fd, &buf, sizeof(uint64_t));
if (ret == 0)
{
return -1;
}
return ret;
}
/* I should get every notification from the host here,
but it seems that not all notifications are going
through. The number of calls to notify_guest does not
match the number of events received from epoll_wait
here */
int notify_poll()
{
int i, n;
struct epoll_event evs[32];
n = epoll_wait(epfd, evs, 32, 0);
for (i = 0; i < n; i++)
{
if (evs[i].events & EPOLLIN)
{
/* Drain evfd */
drain_evfd(irq_fd);
/* Handle notification ... */
handle();
}
}
}
I am trying to capture output from cmd.exe when running commands. I am trying to capture Unicode output to support other languages. My code works right now for getting unicode back from built in commands to cmd.exe. Such as Dir. But if I try to run external commands such as "net user" or "ipconfig" it does not output unicode.
I did reading and found out it is due to my pipes being file pipes. Ipconfig.exe determines if it is printing to the console or not. If it is printing to console, it uses WriteFileW and outputs unicode. Else it just prints ANSI and I get ???????? for anything Unicode.
#include <winsock.h>
#include <Windows.h>
#include <stdio.h>
void ExecCmd() {
HANDLE hPipeRead;
HANDLE hPipeWrite;
SECURITY_ATTRIBUTES saAttr = { sizeof(SECURITY_ATTRIBUTES) };
STARTUPINFO si = { sizeof(STARTUPINFO) };
PROCESS_INFORMATION pi = { 0 };
BOOL fSuccess;
BOOL bProcessEnded = FALSE;
size_t total = 0;
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
if (!CreatePipe(&hPipeRead, &hPipeWrite, &saAttr, 0)) {
return;
}
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
si.hStdOutput = hPipeWrite;
si.hStdError = hPipeWrite;
si.wShowWindow = SW_HIDE;
WCHAR k[] = L"cmd.exe /u /c net user";
fSuccess = CreateProcessW(NULL, k, NULL, NULL, TRUE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi);
if (!fSuccess) {
CloseHandle(hPipeWrite);
CloseHandle(hPipeRead);
return;
}
for (; !bProcessEnded;) {
bProcessEnded = WaitForSingleObject(pi.hProcess, 50) == WAIT_OBJECT_0;
while (TRUE) {
DWORD dwRead = 0;
DWORD dwAvail = 0;
WCHAR *buffer = NULL;
if (!PeekNamedPipe(hPipeRead, NULL, NULL, NULL, &dwAvail, NULL)) {
break;
}
if (!dwAvail) {
break;
}
buffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (dwAvail + 2));
if (buffer == NULL) {
break;
}
if (!ReadFile(hPipeRead, buffer, dwAvail, &dwRead, NULL) || !dwRead) {
break;
}
total += dwRead;
}
}
CloseHandle(hPipeWrite);
CloseHandle(hPipeRead);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return;
}
int main() {
ExecCmd();
return 0;
}
My question is how can I change the way my pipes are getting information back from external commands like ipconfig so that it will support unicode.
I want to list all executed runs of custom task of the Task Scheduler in C/C++. Therefore I access the Event Log and try to extract the TaskScheduler log entries, like so (removed all error handling for simplicity):
HANDLE hEv = OpenEventLogA(NULL, "Microsoft-Windows-TaskScheduler/Operational");
DWORD nrRead = 0x10000, status = ERROR_SUCCESS, nrMin = 0, nrDone;
PBYTE buf = (PBYTE) malloc(nrRead);
while (status == ERROR_SUCCESS) {
if (!ReadEventLog(hEv, EVENTLOG_SEQUENTIAL_READ | EVENTLOG_BACKWARDS_READ,
0, buf, nrRead, &nrDone, &nrMin)) status = GetLastError();
for (PBYTE pRec = buf, pEnd = buf + nrRead; pRec < pEnd;) {
(void) (pRec + sizeof(EVENTLOGRECORD)); // Store record
pRec += ((PEVENTLOGRECORD) pRec)->Length;
if (((PEVENTLOGRECORD) pRec)->Length == 0) break; // Avoid endless loop
}
}
Actually I am able to read events from the log (e.g. the WiFi log). But I cannot open the TaskScheduler log. It then does as described in the documentation and falls back to the Application log.
I tried different strings for the log's name:
Protocol name from the Event Log
Path to the protocol separated by slashes
English and localized names
None of it seems to work. So how can I open the TaskScheduler log? Is the log name localized and needs to be adjusted according to the current Operating System language? Is there another way to retrieve the TaskScheduler executions?
I have tried your code, seem like OpenEventLog can only open some log that frequently-used(not sure). However, there is another way to list TaskScheduler event:
use EvtSubscribe() to add the callback function, When a record is queried, print it out in XML format. Here is the code example:
#include <windows.h>
#include <sddl.h>
#include <stdio.h>
#include <winevt.h>
#pragma comment(lib, "wevtapi.lib")
const int SIZE_DATA = 4096;
TCHAR XMLDataCurrent[SIZE_DATA];
TCHAR XMLDataUser[SIZE_DATA];
#define ARRAY_SIZE 10
#define TIMEOUT 1000 // 1 second; Set and use in place of INFINITE in EvtNext call
DWORD PrintEvent(EVT_HANDLE hEvent); // Shown in the Rendering Events topic
DWORD WINAPI SubscriptionCallback(EVT_SUBSCRIBE_NOTIFY_ACTION action, PVOID pContext, EVT_HANDLE hEvent);
void main(void)
{
DWORD status = ERROR_SUCCESS;
EVT_HANDLE hResults = NULL;
//hResults = EvtQuery(NULL, pwsPath, pwsQuery, EvtQueryChannelPath );// EvtQueryReverseDirection);
hResults = EvtSubscribe(NULL, NULL, L"Microsoft-Windows-TaskScheduler/Operational", NULL, NULL, NULL, (EVT_SUBSCRIBE_CALLBACK)SubscriptionCallback, EvtSubscribeStartAtOldestRecord);
if (NULL == hResults)
{
status = GetLastError();
if (ERROR_EVT_CHANNEL_NOT_FOUND == status)
wprintf(L"The channel was not found.\n");
else if (ERROR_EVT_INVALID_QUERY == status)
// You can call the EvtGetExtendedStatus function to try to get
// additional information as to what is wrong with the query.
wprintf(L"The query is not valid.\n");
else
wprintf(L"EvtQuery failed with %lu.\n", status);
}
Sleep(1000);
cleanup:
if (hResults)
EvtClose(hResults);
}
// The callback that receives the events that match the query criteria.
DWORD WINAPI SubscriptionCallback(EVT_SUBSCRIBE_NOTIFY_ACTION action, PVOID pContext, EVT_HANDLE hEvent)
{
UNREFERENCED_PARAMETER(pContext);
DWORD status = ERROR_SUCCESS;
switch (action)
{
// You should only get the EvtSubscribeActionError action if your subscription flags
// includes EvtSubscribeStrict and the channel contains missing event records.
case EvtSubscribeActionError:
if (ERROR_EVT_QUERY_RESULT_STALE == (DWORD)hEvent)
{
wprintf(L"The subscription callback was notified that event records are missing.\n");
// Handle if this is an issue for your application.
}
else
{
wprintf(L"The subscription callback received the following Win32 error: %lu\n", (DWORD)hEvent);
}
break;
case EvtSubscribeActionDeliver:
if (ERROR_SUCCESS != (status = PrintEvent(hEvent)))
{
goto cleanup;
}
break;
default:
wprintf(L"SubscriptionCallback: Unknown action.\n");
}
cleanup:
if (ERROR_SUCCESS != status)
{
// End subscription - Use some kind of IPC mechanism to signal
// your application to close the subscription handle.
}
return status; // The service ignores the returned status.
}
DWORD PrintEvent(EVT_HANDLE hEvent)
{
DWORD status = ERROR_SUCCESS;
DWORD dwBufferSize = 0;
DWORD dwBufferUsed = 0;
DWORD dwPropertyCount = 0;
LPWSTR pRenderedContent = NULL;
if (!EvtRender(NULL, hEvent, EvtRenderEventXml, dwBufferSize, pRenderedContent, &dwBufferUsed, &dwPropertyCount))
{
if (ERROR_INSUFFICIENT_BUFFER == (status = GetLastError()))
{
dwBufferSize = dwBufferUsed;
pRenderedContent = (LPWSTR)malloc(dwBufferSize);
if (pRenderedContent)
{
EvtRender(NULL, hEvent, EvtRenderEventXml, dwBufferSize, pRenderedContent, &dwBufferUsed, &dwPropertyCount);
}
else
{
wprintf(L"malloc failed\n");
status = ERROR_OUTOFMEMORY;
goto cleanup;
}
}
if (ERROR_SUCCESS != (status = GetLastError()))
{
wprintf(L"EvtRender failed with %d\n", status);
goto cleanup;
}
}
ZeroMemory(XMLDataCurrent, SIZE_DATA);
lstrcpyW(XMLDataCurrent, pRenderedContent);
wprintf(L"EvtRender data %s\n", XMLDataCurrent);
cleanup:
if (pRenderedContent)
free(pRenderedContent);
return status;
}
Hope it could help you!
Thank you #zett42 for pointing me in the right direction and #Drake Wu for the detailed code example. But as I don't need any future event or asynchronous retrieval, I now implemented a simple synchronous function:
#define EVT_SIZE 10
int GetEvents(LPCWSTR query) {
DWORD xmlLen = 0;
LPCWSTR xml = NULL;
EVT_HANDLE hQuery = EvtQuery(NULL, NULL, query, EvtQueryChannelPath | EvtQueryTolerateQueryErrors));
while (true) {
EVT_HANDLE hEv[EVT_SIZE];
DWORD dwReturned = 0;
if (!EvtNext(hQuery, EVT_SIZE, hEv, INFINITE, 0, &dwReturned)) return 0;
// Loop over all events
for (DWORD i = 0; i < dwReturned; i++) {
DWORD nrRead = 0, nrProps = 0;
if (!EvtRender(NULL, hEv[i], EvtRenderEventXml, xmlLen, xml, &nrRead, &nrProps)) {
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
xmlLen = nrRead;
xml = (LPWSTR) realloc(xml, xmlLen);
if (xml) {
EvtRender(NULL, hEv[i], EvtRenderEventXml, xmlLen, xml, &nrRead, &nrProps);
} else {
return -1;
}
}
if (GetLastError() != ERROR_SUCCESS) return -1;
}
// Store event data
EvtClose(hEv[i]);
hEv[i] = NULL;
}
}
return 0;
}
Again I removed most error handling for simplifying the example. The Evt* functions indeed work for the retrieval of the TaskScheduler data (independently from the language).
I want to use large pages in my app like this:
VirtualAlloc(NULL, n_bytes, MEM_RESERVE | MEM_COMMIT | MEM_LARGE_PAGES, PAGE_READWRITE, PAGE_READWRITE);
I plan to enable large pages for the current user during installation, while having elevated admin rights. Does anyone have code for enabling large pages programmatically?
I'm posting what I've gathered.
The general idea:
Enable large pages for the current user account. (Requires admin rights).
Enable large pages for the current process token. (Requires admin rights).
Allocate the memory (granular to large page size, 2Mb, in fact).
If you have UAC properly disabled, you need to execute step 1 only once with admin rights. If you have UAC enabled, you always have to execute it all with admin rights.
#define UNICODE
#define _UNICODE
#include <windows.h>
#include <ntsecapi.h>
#include <ntstatus.h>
#include <Sddl.h>
void InitLsaString(PLSA_UNICODE_STRING LsaString, LPWSTR String)
{
DWORD StringLength;
if (String == NULL) {
LsaString->Buffer = NULL;
LsaString->Length = 0;
LsaString->MaximumLength = 0;
return;
}
StringLength = wcslen(String);
LsaString->Buffer = String;
LsaString->Length = (USHORT)StringLength * sizeof(WCHAR);
LsaString->MaximumLength = (USHORT)(StringLength + 1) * sizeof(WCHAR);
}
NTSTATUS OpenPolicy(LPWSTR ServerName, DWORD DesiredAccess, PLSA_HANDLE PolicyHandle)
{
LSA_OBJECT_ATTRIBUTES ObjectAttributes;
LSA_UNICODE_STRING ServerString;
PLSA_UNICODE_STRING Server = NULL;
//
// Always initialize the object attributes to all zeroes.
//
ZeroMemory(&ObjectAttributes, sizeof(ObjectAttributes));
if (ServerName != NULL) {
//
// Make a LSA_UNICODE_STRING out of the LPWSTR passed in
//
InitLsaString(&ServerString, ServerName);
Server = &ServerString;
}
//
// Attempt to open the policy.
//
return LsaOpenPolicy(
Server,
&ObjectAttributes,
DesiredAccess,
PolicyHandle
);
}
NTSTATUS SetPrivilegeOnAccount(LSA_HANDLE PolicyHandle, PSID AccountSid, LPWSTR PrivilegeName, BOOL bEnable)
{
LSA_UNICODE_STRING PrivilegeString;
//
// Create a LSA_UNICODE_STRING for the privilege name.
//
InitLsaString(&PrivilegeString, PrivilegeName);
//
// grant or revoke the privilege, accordingly
//
if (bEnable) {
return LsaAddAccountRights(
PolicyHandle, // open policy handle
AccountSid, // target SID
&PrivilegeString, // privileges
1 // privilege count
);
}
else {
return LsaRemoveAccountRights(
PolicyHandle, // open policy handle
AccountSid, // target SID
FALSE, // do not disable all rights
&PrivilegeString, // privileges
1 // privilege count
);
}
}
void main()
{
HANDLE hToken = NULL;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
{
applog(LOG_INFO, "OpenProcessToken failed. GetLastError returned: %d\n", GetLastError());
return -1;
}
DWORD dwBufferSize = 0;
// Probe the buffer size reqired for PTOKEN_USER structure
if (!GetTokenInformation(hToken, TokenUser, NULL, 0, &dwBufferSize) &&
(GetLastError() != ERROR_INSUFFICIENT_BUFFER))
{
applog(LOG_INFO, "GetTokenInformation failed. GetLastError returned: %d\n", GetLastError());
// Cleanup
CloseHandle(hToken);
hToken = NULL;
return -1;
}
PTOKEN_USER pTokenUser = (PTOKEN_USER) malloc(dwBufferSize);
// Retrieve the token information in a TOKEN_USER structure
if (!GetTokenInformation(
hToken,
TokenUser,
pTokenUser,
dwBufferSize,
&dwBufferSize))
{
applog(LOG_INFO, "GetTokenInformation failed. GetLastError returned: %d\n", GetLastError());
// Cleanup
CloseHandle(hToken);
hToken = NULL;
return -1;
}
// Print SID string
LPWSTR strsid;
ConvertSidToStringSid(pTokenUser->User.Sid, &strsid);
applog(LOG_INFO, "User SID: %S\n", strsid);
// Cleanup
CloseHandle(hToken);
hToken = NULL;
NTSTATUS status;
LSA_HANDLE policyHandle;
if (status = OpenPolicy(NULL, POLICY_CREATE_ACCOUNT | POLICY_LOOKUP_NAMES, &policyHandle))
{
applog(LOG_INFO, "OpenPolicy %d", status);
}
// Add new privelege to the account
if (status = SetPrivilegeOnAccount(policyHandle, pTokenUser->User.Sid, SE_LOCK_MEMORY_NAME, TRUE))
{
applog(LOG_INFO, "OpenPSetPrivilegeOnAccountolicy %d", status);
}
// Enable this priveledge for the current process
hToken = NULL;
TOKEN_PRIVILEGES tp;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES, &hToken))
{
applog(LOG_INFO, "OpenProcessToken #2 failed. GetLastError returned: %d\n", GetLastError());
return -1;
}
tp.PrivilegeCount = 1;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (!LookupPrivilegeValue(NULL, SE_LOCK_MEMORY_NAME, &tp.Privileges[0].Luid))
{
applog(LOG_INFO, "LookupPrivilegeValue failed. GetLastError returned: %d\n", GetLastError());
return -1;
}
BOOL result = AdjustTokenPrivileges(hToken, FALSE, &tp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
DWORD error = GetLastError();
if (!result || (error != ERROR_SUCCESS))
{
applog(LOG_INFO, "AdjustTokenPrivileges failed. GetLastError returned: %d\n", error);
return -1;
}
// Cleanup
CloseHandle(hToken);
hToken = NULL;
SIZE_T pageSize = GetLargePageMinimum();
// Finally allocate the memory
char *largeBuffer = VirtualAlloc(NULL, pageSize * N_PAGES_TO_ALLOC, MEM_RESERVE | MEM_COMMIT | MEM_LARGE_PAGES, PAGE_READWRITE);
if (largeBuffer)
{
applog(LOG_INFO, "VirtualAlloc failed, error 0x%x", GetLastError());
}
}
I am trying to decrypt WEP profile's key using CryptUnprotectData. The way I fetched the profile key is by exporting the profile using netsh.
netsh wlan export profile name="MyWEP" folder="./"
For now, I manually copied the key material from the .xml file generated by the netsh command to my program. And the way, I am decrypting is -
DATA_BLOB DataOut, DataVerify;
DataOut.cbData = encryptData.length();
DataOut.pbData = (BYTE*)("I_Manually_Copy_The_WEP_Key_Here");
if (CryptUnprotectData( &DataOut,
NULL,
NULL,
NULL,
NULL,
0,
&DataVerify))
{
printf("The decrypted data is: %s\n", DataVerify.pbData);
}
else
{
printf("Failed. Error Code: %d", GetLastError());
}
But I am getting the error code 13 citing Invalid Data. What am I doing wrong ? On Win 7 and later, I can directly use WlanGetProfile with the parameter WLAN_PROFILE_GET_PLAINTEXT_KEY . But I have NO option on Vista than to use the CryptUnprotectData function. I have seen similar posts here, here but didn't get much useful information. Also, I am using the same system with same user log on credentials. Could any one please suggest me how to proceed ?
PS: I have posted the same question on Windows Desktop SDK forums, but haven't got response yet. Trying my luck on SO.
I like questions about Windows Security. So if I occasionally see such one I try to solve it.
In your case you did already the first step by the usage of netsh.exe wlan export profile ... to export the data from the WLAN profile in XML file. The file contains <keyMaterial> element. The data inside of the element are binary data encoded as the Hex: (something like 01000000D08C9DDF0115D1118C7A00C0...).
So what you need to do first of all is to decode the string to binary data. You can use CryptStringToBinary with CRYPT_STRING_HEX parameter to decode the string to binary.
The next step will be to fill DATA_BLOB with the binary data and call CryptUnprotectData to get the result, but... There are small problem. How you can read in the documentation of WlanGetProfile the following
By default, the keyMaterial element returned in the profile pointed to
by the pstrProfileXml is encrypted. If your process runs in the
context of the LocalSystem account on the same computer, then you can
unencrypt key material by calling the CryptUnprotectData function.
Windows Server 2008 and Windows Vista: The keyMaterial element
returned in the profile schema pointed to by the pstrProfileXml is
always encrypted. If your process runs in the context of the
LocalSystem account, then you can unencrypt key material by calling
the CryptUnprotectData function.
So to be able to unencrypt the key we have to call CryptUnprotectData in LocalSystem security context. If your program already run under LocalSystem context you can do this directly. If it's not so, but you have administrative rights or you have at least Debug privilege, you can "to borrow" the LocalSystem token from some other process running on the computer. For example one can get the process token of "winlogon.exe" process and impersonate it.
The following demo program enumerate processes using NtQuerySystemInformation method (see my old answer) which I personally prefer. One can use EnumProcesses or other well-known ways to do the same. Here is the code which worked at me
#include <Windows.h>
#include <tchar.h>
#include <stdio.h>
#pragma comment (lib, "Crypt32.lib")
#define STATUS_SUCCESS ((NTSTATUS)0x00000000L)
#define STATUS_INFO_LENGTH_MISMATCH ((NTSTATUS)0xC0000004L)
typedef enum _SYSTEM_INFORMATION_CLASS {
SystemProcessInformation = 5
} SYSTEM_INFORMATION_CLASS;
typedef struct _UNICODE_STRING {
USHORT Length;
USHORT MaximumLength;
PWSTR Buffer;
} UNICODE_STRING;
typedef LONG KPRIORITY; // Thread priority
typedef struct _SYSTEM_PROCESS_INFORMATION_DETAILD {
ULONG NextEntryOffset;
ULONG NumberOfThreads;
LARGE_INTEGER SpareLi1;
LARGE_INTEGER SpareLi2;
LARGE_INTEGER SpareLi3;
LARGE_INTEGER CreateTime;
LARGE_INTEGER UserTime;
LARGE_INTEGER KernelTime;
UNICODE_STRING ImageName;
KPRIORITY BasePriority;
HANDLE UniqueProcessId;
ULONG InheritedFromUniqueProcessId;
ULONG HandleCount;
BYTE Reserved4[4];
PVOID Reserved5[11];
SIZE_T PeakPagefileUsage;
SIZE_T PrivatePageCount;
LARGE_INTEGER Reserved6[6];
} SYSTEM_PROCESS_INFORMATION_DETAILD, *PSYSTEM_PROCESS_INFORMATION_DETAILD;
typedef NTSTATUS (WINAPI *PFN_NT_QUERY_SYSTEM_INFORMATION)(
IN SYSTEM_INFORMATION_CLASS SystemInformationClass,
IN OUT PVOID SystemInformation,
IN ULONG SystemInformationLength,
OUT OPTIONAL PULONG ReturnLength
);
//
// The function changes a privilege named pszPrivilege for
// the current process. If bEnablePrivilege is FALSE, the privilege
// will be disabled, otherwise it will be enabled.
//
BOOL SetCurrentPrivilege (LPCTSTR pszPrivilege, // Privilege to enable/disable
BOOL bEnablePrivilege) // to enable or disable privilege
{
HANDLE hToken;
TOKEN_PRIVILEGES tp;
LUID luid;
TOKEN_PRIVILEGES tpPrevious;
DWORD cbPrevious = sizeof(TOKEN_PRIVILEGES);
BOOL bSuccess = FALSE;
if (!LookupPrivilegeValue(NULL, pszPrivilege, &luid)) return FALSE;
if (!OpenProcessToken (GetCurrentProcess(),
TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
&hToken
)) return FALSE;
//
// first pass. get current privilege setting
//
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = 0;
AdjustTokenPrivileges(
hToken,
FALSE,
&tp,
sizeof(TOKEN_PRIVILEGES),
&tpPrevious,
&cbPrevious);
if (GetLastError() == ERROR_SUCCESS) {
//
// second pass. set privilege based on previous setting
//
tpPrevious.PrivilegeCount = 1;
tpPrevious.Privileges[0].Luid = luid;
if(bEnablePrivilege)
tpPrevious.Privileges[0].Attributes |= (SE_PRIVILEGE_ENABLED);
else
tpPrevious.Privileges[0].Attributes ^= (SE_PRIVILEGE_ENABLED &
tpPrevious.Privileges[0].Attributes);
AdjustTokenPrivileges(
hToken,
FALSE,
&tpPrevious,
cbPrevious,
NULL,
NULL);
if (GetLastError() == ERROR_SUCCESS) bSuccess=TRUE;
CloseHandle(hToken);
}
else {
DWORD dwErrorCode = GetLastError();
CloseHandle(hToken);
SetLastError(dwErrorCode);
}
return bSuccess;
}
DWORD GetProcessIdByProcessName (LPCWSTR pszProcessName)
{
SIZE_T bufferSize = 1024*sizeof(SYSTEM_PROCESS_INFORMATION_DETAILD);
PSYSTEM_PROCESS_INFORMATION_DETAILD pspid = NULL;
HANDLE hHeap = GetProcessHeap();
PBYTE pBuffer = NULL;
ULONG ReturnLength;
PFN_NT_QUERY_SYSTEM_INFORMATION pfnNtQuerySystemInformation = (PFN_NT_QUERY_SYSTEM_INFORMATION)
GetProcAddress (GetModuleHandle(TEXT("ntdll.dll")), "NtQuerySystemInformation");
NTSTATUS status;
int uLen = lstrlenW(pszProcessName)*sizeof(WCHAR);
__try {
pBuffer = (PBYTE) HeapAlloc (hHeap, 0, bufferSize);
#pragma warning(disable: 4127)
while (TRUE) {
#pragma warning(default: 4127)
status = pfnNtQuerySystemInformation (SystemProcessInformation, (PVOID)pBuffer,
bufferSize, &ReturnLength);
if (status == STATUS_SUCCESS)
break;
else if (status != STATUS_INFO_LENGTH_MISMATCH) { // 0xC0000004L
_tprintf (TEXT("ERROR 0x%X\n"), status);
return 1; // error
}
bufferSize *= 2;
pBuffer = (PBYTE) HeapReAlloc (hHeap, 0, (PVOID)pBuffer, bufferSize);
}
for (pspid = (PSYSTEM_PROCESS_INFORMATION_DETAILD)pBuffer; ;
pspid = (PSYSTEM_PROCESS_INFORMATION_DETAILD)(pspid->NextEntryOffset + (PBYTE)pspid)) {
if (pspid->ImageName.Length == uLen && lstrcmpiW(pspid->ImageName.Buffer, pszProcessName) == 0)
return (DWORD)pspid->UniqueProcessId;
if (pspid->NextEntryOffset == 0) break;
}
}
__finally {
pBuffer = (PBYTE) HeapFree (hHeap, 0, pBuffer);
}
return 0;
}
int _tmain()
{
BOOL bIsSuccess, bImpersonated = FALSE;
HANDLE hProcess = NULL, hProcessToken = NULL;
DATA_BLOB DataOut, DataVerify;
// !!! in the next line you should copy the string from <keyMaterial>
WCHAR szKey[] = L"01000000D08C9DDF0115D1118C7....";
BYTE byKey[1024];
DWORD cbBinary, dwFlags, dwSkip;
DWORD dwProcessId = GetProcessIdByProcessName(L"winlogon.exe");
if (dwProcessId == 0) return 1;
bIsSuccess = SetCurrentPrivilege(SE_DEBUG_NAME, TRUE);
if (!bIsSuccess) return GetLastError();
__try {
hProcess = OpenProcess(MAXIMUM_ALLOWED, FALSE, dwProcessId);
if (!hProcess) __leave;
bIsSuccess = OpenProcessToken (hProcess, MAXIMUM_ALLOWED, &hProcessToken);
if (!bIsSuccess) __leave;
bIsSuccess = ImpersonateLoggedOnUser(hProcessToken);
if (!bIsSuccess) __leave;
bImpersonated = TRUE;
cbBinary = sizeof(byKey);
bIsSuccess = CryptStringToBinary (szKey, lstrlenW(szKey), CRYPT_STRING_HEX, // CRYPT_STRING_HEX_ANY
byKey, &cbBinary, &dwSkip, &dwFlags);
if (!bIsSuccess) __leave;
DataOut.cbData = cbBinary;
DataOut.pbData = (BYTE*)byKey;
if (CryptUnprotectData (&DataOut, NULL, NULL, NULL, NULL, 0, &DataVerify)) {
_tprintf(TEXT("The decrypted data is: %hs\n"), DataVerify.pbData);
}
}
__finally {
if (bImpersonated)
RevertToSelf();
if (hProcess)
CloseHandle(hProcess);
if (hProcessToken)
CloseHandle(hProcessToken);
}
return 0;
}