Skip to content

Instantly share code, notes, and snippets.

@KunYi
Created June 7, 2019 04:31
Show Gist options
  • Save KunYi/bfcf5e718140bf6f8aba0e1094496f83 to your computer and use it in GitHub Desktop.
Save KunYi/bfcf5e718140bf6f8aba0e1094496f83 to your computer and use it in GitHub Desktop.
Note: Read/Write UEFI variables under Windows 7 and later
#include "stdafx.h"
void RasiePrivileges(void)
{
HANDLE hToken;
TOKEN_PRIVILEGES tkp;
if (!OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
&hToken)) {
printf("Failed OpenProcessToken\r\n");
return;
}
LookupPrivilegeValue(NULL, SE_SYSTEM_ENVIRONMENT_NAME,
&tkp.Privileges[0].Luid);
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
DWORD len;
AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, NULL, &len);
if (GetLastError() != ERROR_SUCCESS) {
printf("Failed RasiePrivileges()\r\n");
return;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
BYTE Val[4096];
DWORD dwLen = 0;
const TCHAR name[] = TEXT("BootOrder");
const TCHAR guid[] = TEXT("{8BE4DF61-93CA-11D2-AA0D-00E098032B8C}");
const TCHAR system[] = TEXT("System");
const TCHAR sys_guid[] = TEXT("{E947FCf9-DD01-4965-B808-32A7B6815657}");
const unsigned int offset_TPM = 11; // TPM On/Off offset
#if 0
const TCHAR name[] = TEXT("");
const TCHAR guid[] = TEXT("{00000000-0000-0000-0000-000000000000}");
#endif
printf("Change Boot Order\r\n");
RasiePrivileges();
dwLen = GetFirmwareEnvironmentVariable(
name, guid, Val, 4096);
if (dwLen == 0)
{
DWORD dwErr = GetLastError();
printf("Failed, GetFirmwareEnvironmentVariable(), GetLastError return %d(0x%08x)\r\n",
dwErr, dwErr);
return 1;
}
printf("Dump BootOrder variable, Len:%d(0x%02x)\r\n", dwLen, dwLen);
for(UINT32 i = 0; i < dwLen; i++) {
printf("%02x", Val[i]);
if (i%16 == 0 && i != 0) {
printf("\r\n");
} else {
putchar(' ');
}
}
printf("\r\nExchange BootOrder Item1 & Item2\r\n");
BYTE Tmp[2];
Tmp[0] = Val[0];
Tmp[1] = Val[1];
Val[0] = Val[2];
Val[1] = Val[3];
Val[2] = Tmp[0];
Val[3] = Tmp[1];
if (SetFirmwareEnvironmentVariable(name, guid, Val, dwLen) == TRUE) {
printf("Success!! SetFirmwareEnvironmentVariable\r\n");
} else {
printf("Failed!! SetFirmwareEnvironmentVariable\r\n");
}
printf("Read TPM Support state\r\n");
dwLen = GetFirmwareEnvironmentVariable(
system, sys_guid, Val, 4096);
if (dwLen == 0)
{
DWORD dwErr = GetLastError();
printf("Failed, GetFirmwareEnvironmentVariable(), GetLastError return %d(0x%08x)\r\n",
dwErr, dwErr);
return 2;
}
if (Val[offset_TPM]) {
printf("TPM Support is Enabled, will change to Disable\r\n");
} else {
printf("TPM Support is Disabled, will change to Enable\r\n");
}
Val[offset_TPM] = (Val[offset_TPM]) ? 0 : 1;
if (SetFirmwareEnvironmentVariable(system, sys_guid, Val, dwLen) == TRUE) {
printf("Success!! Change TPM Support Setting\r\n");
} else {
printf("Failed!! Can't change TPM Support Setting\r\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment