18 #error "This file is not expected to be compiled for backend code"
29 static char *restrict_env;
32 #ifndef DISABLE_MAX_PRIVILEGE
33 #define DISABLE_MAX_PRIVILEGE 0x1
45 CreateRestrictedProcess(
char *cmd, PROCESS_INFORMATION *processInfo)
50 HANDLE restrictedToken;
51 SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY};
52 SID_AND_ATTRIBUTES dropSids[2];
54 ZeroMemory(&si,
sizeof(si));
58 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken))
60 pg_log_error(
"could not open process token: error code %lu",
66 ZeroMemory(&dropSids,
sizeof(dropSids));
67 if (!AllocateAndInitializeSid(&NtAuthority, 2,
68 SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0,
69 0, &dropSids[0].Sid) ||
70 !AllocateAndInitializeSid(&NtAuthority, 2,
71 SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0,
76 CloseHandle(origToken);
80 b = CreateRestrictedToken(origToken,
81 DISABLE_MAX_PRIVILEGE,
82 sizeof(dropSids) /
sizeof(dropSids[0]),
88 FreeSid(dropSids[1].Sid);
89 FreeSid(dropSids[0].Sid);
90 CloseHandle(origToken);
94 pg_log_error(
"could not create restricted token: error code %lu", GetLastError());
102 if (!CreateProcessAsUser(restrictedToken,
115 pg_log_error(
"could not start process for command \"%s\": error code %lu", cmd, GetLastError());
119 ResumeThread(processInfo->hThread);
120 return restrictedToken;
132 HANDLE restrictedToken;
139 if ((restrict_env = getenv(
"PG_RESTRICT_EXEC")) == NULL
140 || strcmp(restrict_env,
"1") != 0)
142 PROCESS_INFORMATION pi;
145 ZeroMemory(&pi,
sizeof(pi));
149 setenv(
"PG_RESTRICT_EXEC",
"1", 1);
151 if ((restrictedToken = CreateRestrictedProcess(cmdline, &pi)) == 0)
153 pg_log_error(
"could not re-execute with restricted token: error code %lu", GetLastError());
163 CloseHandle(restrictedToken);
164 CloseHandle(pi.hThread);
165 WaitForSingleObject(pi.hProcess, INFINITE);
167 if (!GetExitCodeProcess(pi.hProcess, &
x))
168 pg_fatal(
"could not get exit code from subprocess: error code %lu", GetLastError());
char * pg_strdup(const char *in)
#define pg_log_error(...)
void get_restricted_token(void)
BOOL AddUserToTokenDacl(HANDLE hToken)