2 * The PCI Library -- Access to i386 I/O ports on Windows
4 * Copyright (c) 2004 Alexander Stock <stock.alexander@gmx.de>
5 * Copyright (c) 2006 Martin Mares <mj@ucw.cz>
6 * Copyright (c) 2021 Pali Rohár <pali@kernel.org>
8 * Can be freely distributed and used under the terms of the GNU GPL v2+
10 * SPDX-License-Identifier: GPL-2.0-or-later
16 #include "i386-io-access.h"
19 * Define __readeflags() for MSVC and GCC compilers.
20 * MSVC since version 14.00 included in WDK 6001 and since version 15.00
21 * included in VS 2008 provides __readeflags() intrinsic for both 32 and 64-bit
22 * modes. WDK 6001 defines macro __BUILDMACHINE__ to value WinDDK. VS 2008 does
23 * not define this macro at all. MSVC throws error if name of user defined
24 * function conflicts with some MSVC intrinsic.
25 * MSVC supports inline assembly via __asm keyword in 32-bit mode only.
26 * GCC version 4.9.0 and higher provides __builtin_ia32_readeflags_uXX()
27 * builtin for XX-mode. This builtin is also available as __readeflags()
28 * function indirectly via <x86intrin.h> header file.
30 #if defined(_MSC_VER) && (_MSC_VER >= 1500 || (_MSC_VER >= 1400 && defined(__BUILDMACHINE__)))
31 #pragma intrinsic(__readeflags)
32 #elif defined(__GNUC__) && ((__GNUC__ == 4 && __GNUC_MINOR__ >= 9) || (__GNUC__ > 4))
33 #include <x86intrin.h>
34 #elif defined(_MSC_VER) && defined(_M_IX86)
43 #elif defined(__GNUC__)
44 static inline unsigned
56 asm volatile ("pushf\n\tpop %0\n" : "=r" (eflags));
60 #error "Unsupported compiler"
63 /* Read IOPL of the current process, IOPL is stored in eflag bits [13:12]. */
64 #define read_iopl() ((__readeflags() >> 12) & 0x3)
66 /* Unfortunately i586-mingw32msvc toolchain does not provide this constant. */
67 #ifndef PROCESS_QUERY_LIMITED_INFORMATION
68 #define PROCESS_QUERY_LIMITED_INFORMATION 0x1000
71 /* Unfortunately some toolchains do not provide this constant. */
72 #ifndef SE_IMPERSONATE_NAME
73 #define SE_IMPERSONATE_NAME TEXT("SeImpersonatePrivilege")
77 * These psapi functions are available in kernel32.dll library with K32 prefix
78 * on Windows 7 and higher systems. On older Windows systems these functions are
79 * available in psapi.dll libary without K32 prefix. So resolve pointers to
80 * these functions dynamically at runtime from the available system library.
81 * Function GetProcessImageFileNameW() is not available on Windows 2000 and
84 typedef BOOL (WINAPI *EnumProcessesProt)(DWORD *lpidProcess, DWORD cb, DWORD *cbNeeded);
85 typedef DWORD (WINAPI *GetProcessImageFileNameWProt)(HANDLE hProcess, LPWSTR lpImageFileName, DWORD nSize);
86 typedef DWORD (WINAPI *GetModuleFileNameExWProt)(HANDLE hProcess, HMODULE hModule, LPWSTR lpImageFileName, DWORD nSize);
89 * These aclapi functions are available in advapi.dll library on Windows NT 4.0
92 typedef DWORD (WINAPI *GetSecurityInfoProt)(HANDLE handle, SE_OBJECT_TYPE ObjectType, SECURITY_INFORMATION SecurityInfo, PSID *ppsidOwner, PSID *ppsidGroup, PACL *ppDacl, PACL *ppSacl, PSECURITY_DESCRIPTOR *ppSecurityDescriptor);
93 typedef DWORD (WINAPI *SetSecurityInfoProt)(HANDLE handle, SE_OBJECT_TYPE ObjectType, SECURITY_INFORMATION SecurityInfo, PSID psidOwner, PSID psidGroup, PACL pDacl, PACL pSacl);
94 typedef DWORD (WINAPI *SetEntriesInAclProt)(ULONG cCountOfExplicitEntries, PEXPLICIT_ACCESS pListOfExplicitEntries, PACL OldAcl, PACL *NewAcl);
97 * This errhandlingapi function is available in kernel32.dll library on
98 * Windows 7 and higher systems.
100 typedef BOOL (WINAPI *SetThreadErrorModeProt)(DWORD dwNewMode, LPDWORD lpOldMode);
103 * Unfortunately NtSetInformationProcess() function, ProcessUserModeIOPL
104 * constant and all other helpers for its usage are not specified in any
105 * standard WinAPI header file. So define all of required constants and types.
106 * Function NtSetInformationProcess() is available in ntdll.dll library on all
107 * Windows systems but marked as it can be removed in some future version.
110 #define NTSTATUS LONG
112 #ifndef STATUS_NOT_IMPLEMENTED
113 #define STATUS_NOT_IMPLEMENTED (NTSTATUS)0xC0000002
115 #ifndef STATUS_PRIVILEGE_NOT_HELD
116 #define STATUS_PRIVILEGE_NOT_HELD (NTSTATUS)0xC0000061
118 #ifndef PROCESSINFOCLASS
119 #define PROCESSINFOCLASS DWORD
121 #ifndef ProcessUserModeIOPL
122 #define ProcessUserModeIOPL 16
124 typedef NTSTATUS (NTAPI *NtSetInformationProcessProt)(HANDLE ProcessHandle, PROCESSINFOCLASS ProcessInformationClass, PVOID ProcessInformation, ULONG ProcessInformationLength);
127 * Check if the current thread has particular privilege in current active access
128 * token. Case when it not possible to determinate it (e.g. current thread does
129 * not have permission to open its own current active access token) is evaluated
130 * as thread does not have that privilege.
133 have_privilege(LUID luid_privilege)
140 * If the current thread does not have active access token then thread
141 * uses primary process access token for all permission checks.
143 if (!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &token) &&
144 (GetLastError() != ERROR_NO_TOKEN ||
145 !OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)))
148 priv.PrivilegeCount = 1;
149 priv.Control = PRIVILEGE_SET_ALL_NECESSARY;
150 priv.Privilege[0].Luid = luid_privilege;
151 priv.Privilege[0].Attributes = SE_PRIVILEGE_ENABLED;
153 if (!PrivilegeCheck(token, &priv, &ret))
160 * Enable or disable particular privilege in specified access token.
162 * Note that it is not possible to disable privilege in access token with
163 * SE_PRIVILEGE_ENABLED_BY_DEFAULT attribute. This function does not check
164 * this case and incorrectly returns no error even when disabling failed.
165 * Rationale for this decision: Simplification of this function as WinAPI
166 * call AdjustTokenPrivileges() does not signal error in this case too.
169 set_privilege(HANDLE token, LUID luid_privilege, BOOL enable)
171 TOKEN_PRIVILEGES token_privileges;
173 token_privileges.PrivilegeCount = 1;
174 token_privileges.Privileges[0].Luid = luid_privilege;
175 token_privileges.Privileges[0].Attributes = enable ? SE_PRIVILEGE_ENABLED : 0;
178 * WinAPI function AdjustTokenPrivileges() success also when not all
179 * privileges were enabled. It is always required to check for failure
180 * via GetLastError() call. AdjustTokenPrivileges() always sets error
181 * also when it success, as opposite to other WinAPI functions.
183 if (!AdjustTokenPrivileges(token, FALSE, &token_privileges, sizeof(token_privileges), NULL, NULL) ||
184 GetLastError() != ERROR_SUCCESS)
191 * Change access token for the current thread to new specified access token.
192 * Previously active access token is stored in old_token variable and can be
193 * used for reverting to this access token. It is set to NULL if the current
194 * thread previously used primary process access token.
197 change_token(HANDLE new_token, HANDLE *old_token)
201 if (!OpenThreadToken(GetCurrentThread(), TOKEN_IMPERSONATE, TRUE, &token))
203 if (GetLastError() != ERROR_NO_TOKEN)
208 if (!ImpersonateLoggedOnUser(new_token))
220 * Change access token for the current thread to the primary process access
221 * token. This function fails also when the current thread already uses primary
222 * process access token.
225 change_token_to_primary(HANDLE *old_token)
229 if (!OpenThreadToken(GetCurrentThread(), TOKEN_IMPERSONATE, TRUE, &token))
239 * Revert to the specified access token for the current thread. When access
240 * token is specified as NULL then revert to the primary process access token.
241 * Use to revert after change_token() or change_token_to_primary() call.
244 revert_to_token(HANDLE token)
247 * If SetThreadToken() call fails then there is no option to revert to
248 * the specified previous thread access token. So in this case revert to
249 * the primary process access token.
251 if (!token || !SetThreadToken(NULL, token))
258 * Enable particular privilege for the current thread. And set method how to
259 * revert this privilege (if to revert whole token or only privilege).
262 enable_privilege(LUID luid_privilege, HANDLE *revert_token, BOOL *revert_only_privilege)
267 if (OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES, TRUE, &thread_token))
269 if (set_privilege(thread_token, luid_privilege, TRUE))
272 * Indicate that correct revert method is just to
273 * disable privilege in access token.
275 if (revert_token && revert_only_privilege)
277 *revert_token = thread_token;
278 *revert_only_privilege = TRUE;
282 CloseHandle(thread_token);
286 CloseHandle(thread_token);
288 * If enabling privilege failed then try to enable it via
289 * primary process access token.
294 * If the current thread has already active thread access token then
295 * open it with just impersonate right as it would be used only for
298 if (revert_token && revert_only_privilege)
300 if (!OpenThreadToken(GetCurrentThread(), TOKEN_IMPERSONATE, TRUE, &thread_token))
302 if (GetLastError() != ERROR_NO_TOKEN)
308 * If current thread has no access token (and uses primary
309 * process access token) or it does not have permission to
310 * adjust privileges or it does not have specified privilege
311 * then create a copy of the primary process access token,
312 * assign it for the current thread (= impersonate self)
313 * and then try adjusting privilege again.
315 if (!ImpersonateSelf(SecurityImpersonation))
318 CloseHandle(thread_token);
323 if (!OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES, TRUE, &new_token))
325 /* thread_token is set only when we were asked for revert method. */
326 if (revert_token && revert_only_privilege)
327 revert_to_token(thread_token);
331 if (!set_privilege(new_token, luid_privilege, TRUE))
333 CloseHandle(new_token);
334 /* thread_token is set only when we were asked for revert method. */
335 if (revert_token && revert_only_privilege)
336 revert_to_token(thread_token);
341 * Indicate that correct revert method is to change to the previous
342 * access token. Either to the primary process access token or to the
343 * previous thread access token.
345 if (revert_token && revert_only_privilege)
347 *revert_token = thread_token;
348 *revert_only_privilege = FALSE;
354 * Revert particular privilege for the current thread was previously enabled by
355 * enable_privilege() call. Either disable privilege in specified access token
356 * or revert to previous access token.
359 revert_privilege(LUID luid_privilege, HANDLE revert_token, BOOL revert_only_privilege)
361 if (revert_only_privilege)
363 set_privilege(revert_token, luid_privilege, FALSE);
364 CloseHandle(revert_token);
368 revert_to_token(revert_token);
373 * Return owner of the access token used by the current thread. Buffer for
374 * returned owner needs to be released by LocalFree() call.
377 get_current_token_owner(VOID)
384 * If the current thread does not have active access token then thread
385 * uses primary process access token for all permission checks.
387 if (!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &token) &&
388 (GetLastError() != ERROR_NO_TOKEN ||
389 !OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)))
392 if (!GetTokenInformation(token, TokenOwner, NULL, 0, &length) &&
393 GetLastError() != ERROR_INSUFFICIENT_BUFFER)
400 owner = (TOKEN_OWNER *)LocalAlloc(LPTR, length);
407 if (!GetTokenInformation(token, TokenOwner, owner, length, &length))
410 * Length of token owner (SID) buffer between two get calls may
411 * changes (e.g. by another thread of process), so retry.
413 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
428 * Grant particular permissions in the primary access token of the specified
429 * process for the owner of current thread token and set old DACL of the
430 * process access token for reverting permissions. Security descriptor is
431 * just memory buffer for old DACL.
434 grant_process_token_dacl_permissions(HANDLE process, DWORD permissions, HANDLE *token, PACL *old_dacl, PSECURITY_DESCRIPTOR *security_descriptor)
436 GetSecurityInfoProt MyGetSecurityInfo;
437 SetSecurityInfoProt MySetSecurityInfo;
438 SetEntriesInAclProt MySetEntriesInAcl;
439 EXPLICIT_ACCESS explicit_access;
445 * This source file already uses advapi32.dll library, so it is
446 * linked to executable and automatically loaded when starting
447 * current running process.
449 advapi32 = GetModuleHandle(TEXT("advapi32.dll"));
454 * It does not matter if SetEntriesInAclA() or SetEntriesInAclW() is
455 * called as no string is passed to SetEntriesInAcl function.
457 MyGetSecurityInfo = (GetSecurityInfoProt)(LPVOID)GetProcAddress(advapi32, "GetSecurityInfo");
458 MySetSecurityInfo = (SetSecurityInfoProt)(LPVOID)GetProcAddress(advapi32, "SetSecurityInfo");
459 MySetEntriesInAcl = (SetEntriesInAclProt)(LPVOID)GetProcAddress(advapi32, "SetEntriesInAclA");
460 if (!MyGetSecurityInfo || !MySetSecurityInfo || !MySetEntriesInAcl)
463 owner = get_current_token_owner();
468 * READ_CONTROL is required for GetSecurityInfo(DACL_SECURITY_INFORMATION)
469 * and WRITE_DAC is required for SetSecurityInfo(DACL_SECURITY_INFORMATION).
471 if (!OpenProcessToken(process, READ_CONTROL | WRITE_DAC, token))
477 if (MyGetSecurityInfo(*token, SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, old_dacl, NULL, security_descriptor) != ERROR_SUCCESS)
485 * Set new explicit access for the owner of the current thread access
486 * token with non-inherited granting access to specified permissions.
488 explicit_access.grfAccessPermissions = permissions;
489 explicit_access.grfAccessMode = GRANT_ACCESS;
490 explicit_access.grfInheritance = NO_PROPAGATE_INHERIT_ACE;
491 explicit_access.Trustee.pMultipleTrustee = NULL;
492 explicit_access.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
493 explicit_access.Trustee.TrusteeForm = TRUSTEE_IS_SID;
494 explicit_access.Trustee.TrusteeType = TRUSTEE_IS_USER;
496 * Unfortunately i586-mingw32msvc toolchain does not have pSid pointer
497 * member in Trustee union. So assign owner SID to ptstrName pointer
498 * member which aliases with pSid pointer member in the same union.
500 explicit_access.Trustee.ptstrName = (PVOID)owner->Owner;
502 if (MySetEntriesInAcl(1, &explicit_access, *old_dacl, &new_dacl) != ERROR_SUCCESS)
504 LocalFree(*security_descriptor);
510 if (MySetSecurityInfo(*token, SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, new_dacl, NULL) != ERROR_SUCCESS)
513 LocalFree(*security_descriptor);
525 * Revert particular granted permissions in specified access token done by
526 * grant_process_token_dacl_permissions() call.
529 revert_token_dacl_permissions(HANDLE token, PACL old_dacl, PSECURITY_DESCRIPTOR security_descriptor)
531 SetSecurityInfoProt MySetSecurityInfo;
535 * This source file already uses advapi32.dll library, so it is
536 * linked to executable and automatically loaded when starting
537 * current running process.
539 advapi32 = GetModuleHandle(TEXT("advapi32.dll"));
542 MySetSecurityInfo = (SetSecurityInfoProt)(LPVOID)GetProcAddress(advapi32, "SetSecurityInfo");
543 MySetSecurityInfo(token, SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, old_dacl, NULL);
546 LocalFree(security_descriptor);
551 * Change error mode of the current thread. If it is not possible then change
552 * error mode of the whole process. Always returns previous error mode.
555 change_error_mode(UINT new_mode)
557 SetThreadErrorModeProt MySetThreadErrorMode = NULL;
562 * Function SetThreadErrorMode() was introduced in Windows 7, so use
563 * GetProcAddress() for compatibility with older systems.
565 kernel32 = GetModuleHandle(TEXT("kernel32.dll"));
567 MySetThreadErrorMode = (SetThreadErrorModeProt)(LPVOID)GetProcAddress(kernel32, "SetThreadErrorMode");
569 if (MySetThreadErrorMode &&
570 MySetThreadErrorMode(new_mode, &old_mode))
574 * Fallback to function SetErrorMode() which modifies error mode of the
575 * whole process and returns old mode.
577 return SetErrorMode(new_mode);
581 * Open process handle specified by the process id with the query right and
582 * optionally also with vm read right.
585 open_process_for_query(DWORD pid, BOOL with_vm_read)
587 BOOL revert_only_privilege;
588 LUID luid_debug_privilege;
589 OSVERSIONINFO version;
595 * Some processes on Windows Vista and higher systems can be opened only
596 * with PROCESS_QUERY_LIMITED_INFORMATION right. This right is enough
597 * for accessing primary process token. But this right is not supported
598 * on older pre-Vista systems. When the current thread on these older
599 * systems does not have Debug privilege then OpenProcess() fails with
600 * ERROR_ACCESS_DENIED. If the current thread has Debug privilege then
601 * OpenProcess() success and returns handle to requested process.
602 * Problem is that this handle does not have PROCESS_QUERY_INFORMATION
603 * right and so cannot be used for accessing primary process token
604 * on those older systems. Moreover it has zero rights and therefore
605 * such handle is fully useless. So never try to use open process with
606 * PROCESS_QUERY_LIMITED_INFORMATION right on older systems than
607 * Windows Vista (NT 6.0).
609 version.dwOSVersionInfoSize = sizeof(version);
610 if (GetVersionEx(&version) &&
611 version.dwPlatformId == VER_PLATFORM_WIN32_NT &&
612 version.dwMajorVersion >= 6)
613 process_right = PROCESS_QUERY_LIMITED_INFORMATION;
615 process_right = PROCESS_QUERY_INFORMATION;
618 process_right |= PROCESS_VM_READ;
620 process = OpenProcess(process_right, FALSE, pid);
625 * It is possible to open only processes to which owner of the current
626 * thread access token has permissions. For opening other processing it
627 * is required to have Debug privilege enabled. By default local
628 * administrators have this privilege, but it is disabled. So try to
629 * enable it and then try to open process again.
632 if (!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid_debug_privilege))
635 if (!enable_privilege(luid_debug_privilege, &revert_token, &revert_only_privilege))
638 process = OpenProcess(process_right, FALSE, pid);
640 revert_privilege(luid_debug_privilege, revert_token, revert_only_privilege);
646 * Check if process image path name (wide string) matches exe file name
647 * (7-bit ASCII string). Do case-insensitive string comparison. Process
648 * image path name can be in any namespace format (DOS, Win32, UNC, ...).
651 check_process_name(LPCWSTR path, DWORD path_length, LPCSTR exe_file)
653 DWORD exe_file_length;
659 while (exe_file[exe_file_length] != '\0')
662 /* Path must have backslash before exe file name. */
663 if (exe_file_length >= path_length ||
664 path[path_length-exe_file_length-1] != L'\\')
667 for (i = 0; i < exe_file_length; i++)
669 c1 = path[path_length-exe_file_length+i];
672 * Input string for comparison is 7-bit ASCII and file name part
673 * of path must not contain backslash as it is path separator.
675 if (c1 >= 0x80 || c2 >= 0x80 || c1 == L'\\')
677 if (c1 >= L'a' && c1 <= L'z')
679 if (c2 >= 'a' && c2 <= 'z')
688 /* Open process handle with the query right specified by process exe file. */
690 find_and_open_process_for_query(LPCSTR exe_file)
692 GetProcessImageFileNameWProt MyGetProcessImageFileNameW;
693 GetModuleFileNameExWProt MyGetModuleFileNameExW;
694 EnumProcessesProt MyEnumProcesses;
695 HMODULE kernel32, psapi;
696 UINT prev_error_mode;
708 kernel32 = GetModuleHandle(TEXT("kernel32.dll"));
713 * On Windows 7 and higher systems these functions are available in
714 * kernel32.dll library with K32 prefix.
716 MyGetModuleFileNameExW = NULL;
717 MyGetProcessImageFileNameW = (GetProcessImageFileNameWProt)(LPVOID)GetProcAddress(kernel32, "K32GetProcessImageFileNameW");
718 MyEnumProcesses = (EnumProcessesProt)(LPVOID)GetProcAddress(kernel32, "K32EnumProcesses");
719 if (!MyGetProcessImageFileNameW || !MyEnumProcesses)
722 * On older NT-based systems these functions are available in
723 * psapi.dll library without K32 prefix.
725 prev_error_mode = change_error_mode(SEM_FAILCRITICALERRORS);
726 psapi = LoadLibrary(TEXT("psapi.dll"));
727 change_error_mode(prev_error_mode);
733 * Function GetProcessImageFileNameW() is available in
734 * Windows XP and higher systems. On older versions is
735 * available function GetModuleFileNameExW().
737 MyGetProcessImageFileNameW = (GetProcessImageFileNameWProt)(LPVOID)GetProcAddress(psapi, "GetProcessImageFileNameW");
738 MyGetModuleFileNameExW = (GetModuleFileNameExWProt)(LPVOID)GetProcAddress(psapi, "GetModuleFileNameExW");
739 MyEnumProcesses = (EnumProcessesProt)(LPVOID)GetProcAddress(psapi, "EnumProcesses");
740 if ((!MyGetProcessImageFileNameW && !MyGetModuleFileNameExW) || !MyEnumProcesses)
747 /* Make initial buffer size for 1024 processes. */
748 size = 1024 * sizeof(*processes);
751 processes = (DWORD *)LocalAlloc(LPTR, size);
759 if (!MyEnumProcesses(processes, size, &length))
761 LocalFree(processes);
766 else if (size == length)
769 * There is no indication given when the buffer is too small to
770 * store all process identifiers. Therefore if returned length
771 * is same as buffer size there can be more processes. Call
772 * again with larger buffer.
774 LocalFree(processes);
780 count = length / sizeof(*processes);
782 for (i = 0; i < count; i++)
784 /* Skip System Idle Process. */
785 if (processes[i] == 0)
789 * Function GetModuleFileNameExW() requires additional
790 * PROCESS_VM_READ right as opposite to function
791 * GetProcessImageFileNameW() which does not need it.
793 process = open_process_for_query(processes[i], MyGetProcessImageFileNameW ? FALSE : TRUE);
798 * Set initial buffer size to 256 (wide) characters.
799 * Final path length on the modern NT-based systems can be also larger.
802 found_process = FALSE;
806 path = (LPWSTR)LocalAlloc(LPTR, size * sizeof(*path));
810 if (MyGetProcessImageFileNameW)
811 length = MyGetProcessImageFileNameW(process, path, size);
813 length = MyGetModuleFileNameExW(process, NULL, path, size);
815 error = GetLastError();
818 * GetModuleFileNameEx() returns zero and signal error ERROR_PARTIAL_COPY
819 * when remote process is in the middle of updating its module table.
820 * Sleep 10 ms and try again, max 10 attempts.
822 if (!MyGetProcessImageFileNameW)
824 if (length == 0 && error == ERROR_PARTIAL_COPY && partial_retry++ < 10)
833 * When buffer is too small then function GetModuleFileNameEx() returns
834 * its size argument on older systems (Windows XP) or its size minus
835 * argument one on new systems (Windows 10) without signalling any error.
836 * Function GetProcessImageFileNameW() on the other hand returns zero
837 * value and signals error ERROR_INSUFFICIENT_BUFFER. So in all these
838 * cases call function again with larger buffer.
841 if (MyGetProcessImageFileNameW && length == 0 && error != ERROR_INSUFFICIENT_BUFFER)
844 if ((MyGetProcessImageFileNameW && length == 0) ||
845 (!MyGetProcessImageFileNameW && (length == size || length == size-1)))
852 if (length && check_process_name(path, length, exe_file))
853 found_process = TRUE;
865 CloseHandle(process);
869 LocalFree(processes);
878 * Try to open primary access token of the particular process with specified
879 * rights. Before opening access token try to adjust DACL permissions of the
880 * primary process access token, so following open does not fail on error
881 * related to no open permissions. Revert DACL permissions after open attempt.
882 * As following steps are not atomic, try to execute them more times in case
883 * of possible race conditions caused by other threads or processes.
886 try_grant_permissions_and_open_process_token(HANDLE process, DWORD rights)
888 PSECURITY_DESCRIPTOR security_descriptor;
896 * This code is not atomic. Between grant and open calls can other
897 * thread or process change or revert permissions. So try to execute
900 for (retry = 0; retry < 10; retry++)
902 if (!grant_process_token_dacl_permissions(process, rights, &grant_token, &old_dacl, &security_descriptor))
904 if (!OpenProcessToken(process, rights, &token))
907 error = GetLastError();
909 revert_token_dacl_permissions(grant_token, old_dacl, security_descriptor);
912 else if (error != ERROR_ACCESS_DENIED)
920 * Open primary access token of particular process handle with specified rights.
921 * If permissions for specified rights are missing then try to grant them.
924 open_process_token_with_rights(HANDLE process, DWORD rights)
929 /* First try to open primary access token of process handle directly. */
930 if (OpenProcessToken(process, rights, &token))
934 * If opening failed then it means that owner of the current thread
935 * access token does not have permission for it. Try it again with
936 * primary process access token.
938 if (change_token_to_primary(&old_token))
940 if (!OpenProcessToken(process, rights, &token))
942 revert_to_token(old_token);
948 * If opening is still failing then try to grant specified permissions
949 * for the current thread and try to open it again.
951 token = try_grant_permissions_and_open_process_token(process, rights);
956 * And if it is still failing then try it again with granting
957 * permissions for the primary process token of the current process.
959 if (change_token_to_primary(&old_token))
961 token = try_grant_permissions_and_open_process_token(process, rights);
962 revert_to_token(old_token);
968 * TODO: Sorry, no other option for now...
969 * It could be possible to use Take Ownership Name privilege to
970 * temporary change token owner of specified process to the owner of
971 * the current thread token, grant permissions for current thread in
972 * that process token, change ownership back to original one, open
973 * that process token and revert granted permissions. But this is
974 * not implemented yet.
980 * Set x86 I/O Privilege Level to 3 for the whole current NT process. Do it via
981 * NtSetInformationProcess() call with ProcessUserModeIOPL information class,
982 * which is supported by 32-bit Windows NT kernel versions and requires Tcb
986 SetProcessUserModeIOPL(VOID)
988 NtSetInformationProcessProt MyNtSetInformationProcess;
990 LUID luid_tcb_privilege;
991 LUID luid_impersonate_privilege;
993 HANDLE revert_token_tcb_privilege;
994 BOOL revert_only_tcb_privilege;
996 HANDLE revert_token_impersonate_privilege;
997 BOOL revert_only_impersonate_privilege;
999 BOOL impersonate_privilege_enabled;
1001 BOOL revert_to_old_token;
1004 HANDLE lsass_process;
1007 UINT prev_error_mode;
1012 impersonate_privilege_enabled = FALSE;
1013 revert_to_old_token = FALSE;
1017 /* Fast path when ProcessUserModeIOPL was already called. */
1018 if (read_iopl() == 3)
1022 * Load ntdll.dll library with disabled critical-error-handler message box.
1023 * It means that NT kernel does not show unwanted GUI message box to user
1024 * when LoadLibrary() function fails.
1026 prev_error_mode = change_error_mode(SEM_FAILCRITICALERRORS);
1027 ntdll = LoadLibrary(TEXT("ntdll.dll"));
1028 change_error_mode(prev_error_mode);
1030 goto err_not_implemented;
1032 /* Retrieve pointer to NtSetInformationProcess() function. */
1033 MyNtSetInformationProcess = (NtSetInformationProcessProt)(LPVOID)GetProcAddress(ntdll, "NtSetInformationProcess");
1034 if (!MyNtSetInformationProcess)
1035 goto err_not_implemented;
1038 * ProcessUserModeIOPL is syscall for NT kernel to change x86 IOPL
1039 * of the current running process to 3.
1041 * Process handle argument for ProcessUserModeIOPL is ignored and
1042 * IOPL is always changed for the current running process. So pass
1043 * GetCurrentProcess() handle for documentation purpose. Process
1044 * information buffer and length are unused for ProcessUserModeIOPL.
1046 * ProcessUserModeIOPL may success (return value >= 0) or may fail
1047 * because it is not implemented or because of missing privilege.
1048 * Other errors are not defined, so handle them as unknown.
1050 nt_status = MyNtSetInformationProcess(GetCurrentProcess(), ProcessUserModeIOPL, NULL, 0);
1053 else if (nt_status == STATUS_NOT_IMPLEMENTED)
1054 goto err_not_implemented;
1055 else if (nt_status != STATUS_PRIVILEGE_NOT_HELD)
1059 * If ProcessUserModeIOPL call failed with STATUS_PRIVILEGE_NOT_HELD
1060 * error then it means that the current thread token does not have
1061 * Tcb privilege enabled. Try to enable it.
1064 if (!LookupPrivilegeValue(NULL, SE_TCB_NAME, &luid_tcb_privilege))
1065 goto err_privilege_not_held;
1068 * If the current thread has already Tcb privilege enabled then there
1069 * is some additional unhanded restriction.
1071 if (have_privilege(luid_tcb_privilege))
1072 goto err_privilege_not_held;
1074 /* Try to enable Tcb privilege and try ProcessUserModeIOPL call again. */
1075 if (enable_privilege(luid_tcb_privilege, &revert_token_tcb_privilege, &revert_only_tcb_privilege))
1077 nt_status = MyNtSetInformationProcess(GetCurrentProcess(), ProcessUserModeIOPL, NULL, 0);
1078 revert_privilege(luid_tcb_privilege, revert_token_tcb_privilege, revert_only_tcb_privilege);
1081 else if (nt_status == STATUS_NOT_IMPLEMENTED)
1082 goto err_not_implemented;
1083 else if (nt_status == STATUS_PRIVILEGE_NOT_HELD)
1084 goto err_privilege_not_held;
1090 * If enabling of Tcb privilege failed then it means that current thread
1091 * does not this privilege. But current process may have it. So try it
1092 * again with primary process access token.
1096 * If system supports Impersonate privilege (Windows 2000 SP4 or higher) then
1097 * all future actions in this function require this Impersonate privilege.
1098 * So try to enable it in case it is currently disabled.
1100 if (LookupPrivilegeValue(NULL, SE_IMPERSONATE_NAME, &luid_impersonate_privilege) &&
1101 !have_privilege(luid_impersonate_privilege))
1104 * If current thread does not have Impersonate privilege enabled
1105 * then first try to enable it just for the current thread. If
1106 * it is not possible to enable it just for the current thread
1107 * then try it to enable globally for whole process (which
1108 * affects all process threads). Both actions will be reverted
1109 * at the end of this function.
1111 if (enable_privilege(luid_impersonate_privilege, &revert_token_impersonate_privilege, &revert_only_impersonate_privilege))
1113 impersonate_privilege_enabled = TRUE;
1115 else if (enable_privilege(luid_impersonate_privilege, NULL, NULL))
1117 impersonate_privilege_enabled = TRUE;
1118 revert_token_impersonate_privilege = NULL;
1119 revert_only_impersonate_privilege = TRUE;
1123 goto err_privilege_not_held;
1127 * Now when Impersonate privilege is enabled, try to enable Tcb
1128 * privilege again. Enabling other privileges for the current
1129 * thread requires Impersonate privilege, so enabling Tcb again
1132 if (enable_privilege(luid_tcb_privilege, &revert_token_tcb_privilege, &revert_only_tcb_privilege))
1134 nt_status = MyNtSetInformationProcess(GetCurrentProcess(), ProcessUserModeIOPL, NULL, 0);
1135 revert_privilege(luid_tcb_privilege, revert_token_tcb_privilege, revert_only_tcb_privilege);
1138 else if (nt_status == STATUS_NOT_IMPLEMENTED)
1139 goto err_not_implemented;
1140 else if (nt_status == STATUS_PRIVILEGE_NOT_HELD)
1141 goto err_privilege_not_held;
1148 * If enabling Tcb privilege failed then it means that the current
1149 * thread access token does not have this privilege or does not
1150 * have permission to adjust privileges.
1152 * Try to use more privileged token from Local Security Authority
1153 * Subsystem Service process (lsass.exe) which has Tcb privilege.
1154 * Retrieving this more privileged token is possible for local
1155 * administrators (unless it was disabled by local administrators).
1158 lsass_process = find_and_open_process_for_query("lsass.exe");
1160 goto err_privilege_not_held;
1163 * Open primary lsass.exe process access token with query and duplicate
1164 * rights. Just these two rights are required for impersonating other
1165 * primary process token (impersonate right is really not required!).
1167 lsass_token = open_process_token_with_rights(lsass_process, TOKEN_QUERY | TOKEN_DUPLICATE);
1169 CloseHandle(lsass_process);
1172 goto err_privilege_not_held;
1175 * After successful open of the primary lsass.exe process access token,
1176 * assign its copy for the current thread.
1178 if (!change_token(lsass_token, &old_token))
1179 goto err_privilege_not_held;
1181 revert_to_old_token = TRUE;
1183 nt_status = MyNtSetInformationProcess(GetCurrentProcess(), ProcessUserModeIOPL, NULL, 0);
1184 if (nt_status == STATUS_PRIVILEGE_NOT_HELD)
1187 * Now current thread is not using primary process token anymore
1188 * but is using custom access token. There is no need to revert
1189 * enabled Tcb privilege as the whole custom access token would
1190 * be reverted. So there is no need to setup revert method for
1191 * enabling privilege.
1193 if (have_privilege(luid_tcb_privilege) ||
1194 !enable_privilege(luid_tcb_privilege, NULL, NULL))
1195 goto err_privilege_not_held;
1196 nt_status = MyNtSetInformationProcess(GetCurrentProcess(), ProcessUserModeIOPL, NULL, 0);
1200 else if (nt_status == STATUS_NOT_IMPLEMENTED)
1201 goto err_not_implemented;
1202 else if (nt_status == STATUS_PRIVILEGE_NOT_HELD)
1203 goto err_privilege_not_held;
1209 * Some Windows NT kernel versions (e.g. Windows 2003 x64) do not
1210 * implement ProcessUserModeIOPL syscall at all but incorrectly
1211 * returns success when it is called by user process. So always
1212 * after this call verify that IOPL is set to 3.
1214 if (read_iopl() != 3)
1215 goto err_not_implemented;
1219 err_not_implemented:
1220 SetLastError(ERROR_INVALID_FUNCTION);
1224 err_privilege_not_held:
1225 SetLastError(ERROR_PRIVILEGE_NOT_HELD);
1230 SetLastError(ERROR_GEN_FAILURE);
1235 if (revert_to_old_token)
1236 revert_to_token(old_token);
1238 if (impersonate_privilege_enabled)
1239 revert_privilege(luid_impersonate_privilege, revert_token_impersonate_privilege, revert_only_impersonate_privilege);
1242 CloseHandle(lsass_token);
1251 intel_setup_io(struct pci_access *a)
1254 /* 16/32-bit non-NT systems allow applications to access PCI I/O ports without any special setup. */
1255 OSVERSIONINFOA version;
1256 version.dwOSVersionInfoSize = sizeof(version);
1257 if (GetVersionExA(&version) && version.dwPlatformId < VER_PLATFORM_WIN32_NT)
1259 a->debug("Detected 16/32-bit non-NT system, skipping NT setup...");
1264 /* On NT-based systems issue ProcessUserModeIOPL syscall which changes IOPL to 3. */
1265 if (!SetProcessUserModeIOPL())
1267 DWORD error = GetLastError();
1268 a->debug("NT ProcessUserModeIOPL call failed: %s.", error == ERROR_INVALID_FUNCTION ? "Not Implemented" : error == ERROR_PRIVILEGE_NOT_HELD ? "Access Denied" : "Operation Failed");
1272 a->debug("NT ProcessUserModeIOPL call succeeded...");
1277 intel_cleanup_io(struct pci_access *a UNUSED)
1280 * 16/32-bit non-NT systems do not use any special setup and on NT-based
1281 * systems ProcessUserModeIOPL permanently changes IOPL to 3 for the current
1282 * NT process, no revert for current process is possible.
1286 static inline void intel_io_lock(void)
1290 static inline void intel_io_unlock(void)