{"record":{"id":"6981d9b5f962441e","repo":"peass-ng/PEASS-ng","slug":"0-openprocesstoken-failed-with-error-1","errorCode":null,"errorMessage":"{0}: OpenProcessToken failed with error: {1}","messagePattern":"(.+?): OpenProcessToken failed with error: (.+?)","errorType":"exception","errorClass":"Win32Exception","httpStatus":null,"severity":"error","filePath":"winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/ProcessContext.cs","lineNumber":130,"sourceCode":"            throw new InvalidOperationException(Resources.GetCurrentWindowsIdentityFailed);\n\n         return new WindowsPrincipal(windowsIdentity);\n      }\n\n\n      /// <summary>[AlphaFS] Retrieves the elevation type of the current process.</summary>\n      /// <returns>A <see cref=\"NativeMethods.TOKEN_ELEVATION_TYPE\"/> value.</returns>\n      [SuppressMessage(\"Microsoft.Naming\", \"CA2204:Literals should be spelled correctly\", MessageId = \"GetTokenInformation\")]\n      [SuppressMessage(\"Microsoft.Naming\", \"CA2204:Literals should be spelled correctly\", MessageId = \"OpenProcessToken\")]\n      private static NativeMethods.TOKEN_ELEVATION_TYPE GetProcessElevationType()\n      {\n         SafeTokenHandle tokenHandle;\n\n         var success = NativeMethods.OpenProcessToken(Process.GetCurrentProcess().Handle, NativeMethods.TOKEN.TOKEN_READ, out tokenHandle);\n\n         var lastError = Marshal.GetLastWin32Error();\n         if (!success)\n            throw new Win32Exception(lastError, string.Format(CultureInfo.CurrentCulture, \"{0}: OpenProcessToken failed with error: {1}\", MethodBase.GetCurrentMethod().Name, lastError.ToString(CultureInfo.CurrentCulture)));\n\n\n         using (tokenHandle)\n         using (var safeBuffer = new SafeGlobalMemoryBufferHandle(Marshal.SizeOf(Enum.GetUnderlyingType(typeof(NativeMethods.TOKEN_ELEVATION_TYPE)))))\n         {\n            uint bytesReturned;\n            success = NativeMethods.GetTokenInformation(tokenHandle, NativeMethods.TOKEN_INFORMATION_CLASS.TokenElevationType, safeBuffer, (uint) safeBuffer.Capacity, out bytesReturned);\n\n            lastError = Marshal.GetLastWin32Error();\n\n            if (!success)\n               throw new Win32Exception(lastError, string.Format(CultureInfo.CurrentCulture, \"{0}: GetTokenInformation failed with error: {1}\", MethodBase.GetCurrentMethod().Name, lastError.ToString(CultureInfo.CurrentCulture)));\n\n\n            return (NativeMethods.TOKEN_ELEVATION_TYPE) safeBuffer.ReadInt32();\n         }\n      }\n   }","sourceCodeStart":112,"sourceCodeEnd":148,"githubUrl":"https://github.com/peass-ng/PEASS-ng/blob/53fb989abc2219826385683a6fee826bd6cd38d6/winPEAS/winPEASexe/winPEAS/3rdParty/AlphaFS/Security/ProcessContext.cs#L112-L148","documentation":"GetProcessElevationType throws Win32Exception when the native OpenProcessToken call on the current process fails; the message embeds the method name and the Win32 error code ('{0}: OpenProcessToken failed with error: {1}'). This is used by IsElevatedProcess to determine if the process is elevated. Failure means the process token could not be opened with TOKEN_READ.","triggerScenarios":"Calling ProcessContext.IsElevatedProcess when OpenProcessToken fails — e.g. restricted token, hardened process mitigation policies, or sandbox limiting token access rights.","commonSituations":"Running inside a highly restricted job/appcontainer, antivirus sandboxing, or CI environments where TOKEN_READ on the own process handle is denied; corrupted or limited primary tokens.","solutions":["Inspect the embedded Win32 error code in the message (e.g. ERROR_ACCESS_DENIED) and address that condition","Run the check from a context with standard token access; avoid calling inside heavily restricted sandboxes","Fallback: check elevation via WindowsIdentity.GetCurrent().Owner vs Administrators SID or env-var comparison instead of OpenProcessToken","Catch Win32Exception around IsElevatedProcess and treat elevation as unknown"],"exampleFix":"// before\nbool elevated = ProcessContext.IsElevatedProcess();\n// after\nbool elevated;\ntry { elevated = ProcessContext.IsElevatedProcess(); }\ncatch (Win32Exception ex) { Log(\"elevation check failed: \" + ex.Message); elevated = false; }","handlingStrategy":"try-catch","validationCode":"// best-effort precheck is not possible; treat as environment check\nbool canReadToken = true; // OpenProcessToken failure only detectable at call time\n","typeGuard":null,"tryCatchPattern":"try { bool elev = ProcessContext.IsElevatedProcess(); }\ncatch (Win32Exception ex) { Log($\"elevation unknown: {ex.NativeErrorCode}\"); elev = false; }","preventionTips":["Parse the Win32 error code from the message to diagnose (access denied vs invalid handle)","Avoid running elevation checks inside sandboxes/appcontainers that block token access","Provide a non-token fallback (e.g. check Administrators group membership via WindowsPrincipal)"],"tags":["security","win32","process-token","elevation","pinvoke"],"backgroundTag":"open-process-token-failed","analyzedSha":"53fb989abc2219826385683a6fee826bd6cd38d6","analyzedAt":"2026-09-02T04:25:09.259Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-09T11:17:12.671Z"}