2 * Copyright 2015-2017 Mark Jansen (mark.jansen@reactos.org)
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 #define WIN32_NO_STATUS
24 /* Make sure we don't include apphelp logging */
25 #define APPHELP_NOSDBPAPI
31 FARPROC WINAPI
StubGetProcAddress(HINSTANCE hModule
, LPCSTR lpProcName
);
32 BOOL WINAPI
SE_IsShimDll(PVOID BaseAddress
);
35 extern HMODULE g_hInstance
;
36 static UNICODE_STRING g_WindowsDirectory
;
37 static UNICODE_STRING g_System32Directory
;
38 static UNICODE_STRING g_SxsDirectory
;
39 ULONG g_ShimEngDebugLevel
= 0xffffffff;
40 BOOL g_bComPlusImage
= FALSE
;
41 BOOL g_bShimDuringInit
= FALSE
;
42 BOOL g_bInternalHooksUsed
= FALSE
;
43 static ARRAY g_pShimInfo
; /* PSHIMMODULE */
44 static ARRAY g_pHookArray
; /* HOOKMODULEINFO */
45 static ARRAY g_InExclude
; /* INEXCLUDE */
47 /* If we have setup a hook for a function, we should also redirect GetProcAddress for this function */
48 HOOKAPIEX g_IntHookEx
[] =
51 "kernel32.dll", /* LibraryName */
52 "GetProcAddress", /* FunctionName */
53 StubGetProcAddress
, /* ReplacementFunction*/
54 NULL
, /* OriginalFunction */
60 static inline BOOL
ARRAY_InitWorker(PARRAY Array
, DWORD ItemSize
)
63 Array
->Size__
= Array
->MaxSize__
= 0;
64 Array
->ItemSize__
= ItemSize
;
69 static inline BOOL
ARRAY_EnsureSize(PARRAY Array
, DWORD ItemSize
, DWORD GrowWith
)
75 ASSERT(ItemSize
== Array
->ItemSize__
);
77 if (Array
->MaxSize__
> Array
->Size__
)
80 Count
= Array
->Size__
+ GrowWith
;
81 pNewData
= SeiAlloc(Count
* ItemSize
);
85 SHIMENG_FAIL("Failed to allocate %d bytes\n", Count
* ItemSize
);
88 Array
->MaxSize__
= Count
;
92 memcpy(pNewData
, Array
->Data__
, Array
->Size__
* ItemSize
);
93 SeiFree(Array
->Data__
);
95 Array
->Data__
= pNewData
;
100 static inline PVOID
ARRAY_AppendWorker(PARRAY Array
, DWORD ItemSize
, DWORD GrowWith
)
104 if (!ARRAY_EnsureSize(Array
, ItemSize
, GrowWith
))
107 pData
= Array
->Data__
;
108 pData
+= (Array
->Size__
* ItemSize
);
114 static inline PVOID
ARRAY_AtWorker(PARRAY Array
, DWORD ItemSize
, DWORD n
)
119 ASSERT(ItemSize
== Array
->ItemSize__
);
120 ASSERT(n
< Array
->Size__
);
122 pData
= Array
->Data__
;
123 return pData
+ (n
* ItemSize
);
127 #define ARRAY_Init(Array, TypeOfArray) ARRAY_InitWorker((Array), sizeof(TypeOfArray))
128 #define ARRAY_Append(Array, TypeOfArray) (TypeOfArray*)ARRAY_AppendWorker((Array), sizeof(TypeOfArray), 5)
129 #define ARRAY_At(Array, TypeOfArray, at) (TypeOfArray*)ARRAY_AtWorker((Array), sizeof(TypeOfArray), at)
130 #define ARRAY_Size(Array) (Array)->Size__
133 VOID
SeiInitDebugSupport(VOID
)
135 static const UNICODE_STRING DebugKey
= RTL_CONSTANT_STRING(L
"SHIMENG_DEBUG_LEVEL");
136 UNICODE_STRING DebugValue
;
138 ULONG NewLevel
= SEI_MSG
; /* Show some basic info in the logs, unless configured different */
141 RtlInitEmptyUnicodeString(&DebugValue
, Buffer
, sizeof(Buffer
));
143 Status
= RtlQueryEnvironmentVariable_U(NULL
, &DebugKey
, &DebugValue
);
145 if (NT_SUCCESS(Status
))
147 if (!NT_SUCCESS(RtlUnicodeStringToInteger(&DebugValue
, 10, &NewLevel
)))
150 g_ShimEngDebugLevel
= NewLevel
;
155 * Outputs diagnostic info.
157 * @param [in] Level The level to log this message with, choose any of [SHIM_ERR,
158 * SHIM_WARN, SHIM_INFO].
159 * @param [in] FunctionName The function this log should be attributed to.
160 * @param [in] Format The format string.
161 * @param ... Variable arguments providing additional information.
163 * @return Success: TRUE Failure: FALSE.
165 BOOL WINAPIV
SeiDbgPrint(SEI_LOG_LEVEL Level
, PCSTR Function
, PCSTR Format
, ...)
168 char* Current
= Buffer
;
169 const char* LevelStr
;
170 size_t Length
= sizeof(Buffer
);
174 if (g_ShimEngDebugLevel
== 0xffffffff)
175 SeiInitDebugSupport();
177 if (Level
> g_ShimEngDebugLevel
)
200 hr
= StringCchPrintfExA(Current
, Length
, &Current
, &Length
, STRSAFE_NULL_ON_FAILURE
, "[%s] [%s] ", LevelStr
, Function
);
202 hr
= StringCchPrintfExA(Current
, Length
, &Current
, &Length
, STRSAFE_NULL_ON_FAILURE
, "[%s] ", LevelStr
);
207 va_start(ArgList
, Format
);
208 hr
= StringCchVPrintfExA(Current
, Length
, &Current
, &Length
, STRSAFE_NULL_ON_FAILURE
, Format
, ArgList
);
213 DbgPrint("%s", Buffer
);
218 PVOID
SeiGetModuleFromAddress(PVOID addr
)
220 PVOID hModule
= NULL
;
221 RtlPcToFileHeader(addr
, &hModule
);
227 /* TODO: Guard against recursive calling / calling init multiple times! */
228 VOID
NotifyShims(DWORD dwReason
, PVOID Info
)
232 for (n
= 0; n
< ARRAY_Size(&g_pShimInfo
); ++n
)
234 PSHIMMODULE pShimModule
= *ARRAY_At(&g_pShimInfo
, PSHIMMODULE
, n
);
235 if (!pShimModule
->pNotifyShims
)
238 pShimModule
->pNotifyShims(dwReason
, Info
);
244 VOID
SeiCheckComPlusImage(PVOID BaseAddress
)
246 ULONG ComSectionSize
;
247 g_bComPlusImage
= RtlImageDirectoryEntryToData(BaseAddress
, TRUE
, IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR
, &ComSectionSize
) != NULL
;
249 SHIMENG_INFO("COM+ executable %s\n", g_bComPlusImage
? "TRUE" : "FALSE");
253 PSHIMMODULE
SeiGetShimModuleInfo(PVOID BaseAddress
)
257 for (n
= 0; n
< ARRAY_Size(&g_pShimInfo
); ++n
)
259 PSHIMMODULE pShimModule
= *ARRAY_At(&g_pShimInfo
, PSHIMMODULE
, n
);
261 if (pShimModule
->BaseAddress
== BaseAddress
)
267 PSHIMMODULE
SeiCreateShimModuleInfo(PCWSTR DllName
, PVOID BaseAddress
)
269 static const ANSI_STRING GetHookAPIs
= RTL_CONSTANT_STRING("GetHookAPIs");
270 static const ANSI_STRING NotifyShims
= RTL_CONSTANT_STRING("NotifyShims");
271 PSHIMMODULE
* pData
, Data
;
272 PVOID pGetHookAPIs
, pNotifyShims
;
274 if (!NT_SUCCESS(LdrGetProcedureAddress(BaseAddress
, (PANSI_STRING
)&GetHookAPIs
, 0, &pGetHookAPIs
)) ||
275 !NT_SUCCESS(LdrGetProcedureAddress(BaseAddress
, (PANSI_STRING
)&NotifyShims
, 0, &pNotifyShims
)))
277 SHIMENG_WARN("Failed to resolve entry points for %S\n", DllName
);
281 pData
= ARRAY_Append(&g_pShimInfo
, PSHIMMODULE
);
285 *pData
= SeiAlloc(sizeof(SHIMMODULE
));
289 RtlCreateUnicodeString(&Data
->Name
, DllName
);
290 Data
->BaseAddress
= BaseAddress
;
292 Data
->pGetHookAPIs
= pGetHookAPIs
;
293 Data
->pNotifyShims
= pNotifyShims
;
295 ARRAY_Init(&Data
->EnabledShims
, PSHIMINFO
);
300 PSHIMINFO
SeiAppendHookInfo(PSHIMMODULE pShimModuleInfo
, PHOOKAPIEX pHookApi
, DWORD dwHookCount
, PCWSTR ShimName
)
302 PSHIMINFO
* pData
, Data
;
304 pData
= ARRAY_Append(&pShimModuleInfo
->EnabledShims
, PSHIMINFO
);
308 *pData
= SeiAlloc(sizeof(SHIMINFO
));
314 Data
->ShimName
= SdbpStrDup(ShimName
);
318 Data
->pHookApi
= pHookApi
;
319 Data
->dwHookCount
= dwHookCount
;
320 Data
->pShimModule
= pShimModuleInfo
;
321 ARRAY_Init(&Data
->InExclude
, INEXCLUDE
);
325 PHOOKMODULEINFO
SeiFindHookModuleInfo(PUNICODE_STRING ModuleName
, PVOID BaseAddress
)
329 for (n
= 0; n
< ARRAY_Size(&g_pHookArray
); ++n
)
331 PHOOKMODULEINFO pModuleInfo
= ARRAY_At(&g_pHookArray
, HOOKMODULEINFO
, n
);
333 if (BaseAddress
&& BaseAddress
== pModuleInfo
->BaseAddress
)
336 if (!BaseAddress
&& RtlEqualUnicodeString(ModuleName
, &pModuleInfo
->Name
, TRUE
))
343 PHOOKMODULEINFO
SeiFindHookModuleInfoForImportDescriptor(PBYTE DllBase
, PIMAGE_IMPORT_DESCRIPTOR ImportDescriptor
)
345 UNICODE_STRING DllName
;
349 if (!RtlCreateUnicodeStringFromAsciiz(&DllName
, (PCSZ
)(DllBase
+ ImportDescriptor
->Name
)))
351 SHIMENG_FAIL("Unable to convert dll name to unicode\n");
355 Success
= LdrGetDllHandle(NULL
, NULL
, &DllName
, &DllHandle
);
356 RtlFreeUnicodeString(&DllName
);
358 if (!NT_SUCCESS(Success
))
360 SHIMENG_FAIL("Unable to get module handle for %wZ\n", &DllName
);
364 return SeiFindHookModuleInfo(NULL
, DllHandle
);
367 static LPCWSTR
SeiGetStringPtr(PDB pdb
, TAGID tag
, TAG type
)
369 TAGID tagEntry
= SdbFindFirstTag(pdb
, tag
, type
);
370 if (tagEntry
== TAGID_NULL
)
373 return SdbGetStringTagPtr(pdb
, tagEntry
);
376 static DWORD
SeiGetDWORD(PDB pdb
, TAGID tag
, TAG type
)
378 TAGID tagEntry
= SdbFindFirstTag(pdb
, tag
, type
);
379 if (tagEntry
== TAGID_NULL
)
382 return SdbReadDWORDTag(pdb
, tagEntry
, TAGID_NULL
);
386 static VOID
SeiAddShim(TAGREF trShimRef
, PARRAY pShimRef
)
390 Data
= ARRAY_Append(pShimRef
, TAGREF
);
397 /* Propagate layers to child processes */
398 static VOID
SeiSetLayerEnvVar(LPCWSTR wszLayer
)
401 UNICODE_STRING VarName
= RTL_CONSTANT_STRING(L
"__COMPAT_LAYER");
402 UNICODE_STRING Value
;
404 RtlInitUnicodeString(&Value
, wszLayer
);
406 Status
= RtlSetEnvironmentVariable(NULL
, &VarName
, &Value
);
407 if (NT_SUCCESS(Status
))
408 SHIMENG_INFO("Set env var %wZ=%wZ\n", &VarName
, &Value
);
410 SHIMENG_FAIL("Failed to set %wZ: 0x%x\n", &VarName
, Status
);
413 #define MAX_LAYER_LENGTH 256
415 /* Translate all Exe and Layer entries to Shims, and propagate all layers */
416 static VOID
SeiBuildShimRefArray(HSDB hsdb
, SDBQUERYRESULT
* pQuery
, PARRAY pShimRef
)
418 WCHAR wszLayerEnvVar
[MAX_LAYER_LENGTH
] = { 0 };
421 for (n
= 0; n
< pQuery
->dwExeCount
; ++n
)
425 if (SdbTagRefToTagID(hsdb
, pQuery
->atrExes
[n
], &pdb
, &tag
))
427 LPCWSTR ExeName
= SeiGetStringPtr(pdb
, tag
, TAG_NAME
);
428 TAGID ShimRef
= SdbFindFirstTag(pdb
, tag
, TAG_SHIM_REF
);
431 SeiDbgPrint(SEI_MSG
, NULL
, "ShimInfo(Exe(%S))\n", ExeName
);
433 while (ShimRef
!= TAGID_NULL
)
436 if (SdbTagIDToTagRef(hsdb
, pdb
, ShimRef
, &trShimRef
))
437 SeiAddShim(trShimRef
, pShimRef
);
440 ShimRef
= SdbFindNextTag(pdb
, tag
, ShimRef
);
443 /* Handle FLAG_REF */
448 for (n
= 0; n
< pQuery
->dwLayerCount
; ++n
)
452 if (SdbTagRefToTagID(hsdb
, pQuery
->atrLayers
[n
], &pdb
, &tag
))
454 LPCWSTR LayerName
= SeiGetStringPtr(pdb
, tag
, TAG_NAME
);
455 TAGID ShimRef
= SdbFindFirstTag(pdb
, tag
, TAG_SHIM_REF
);
459 SeiDbgPrint(SEI_MSG
, NULL
, "ShimInfo(Layer(%S))\n", LayerName
);
460 if (wszLayerEnvVar
[0])
461 StringCchCatW(wszLayerEnvVar
, ARRAYSIZE(wszLayerEnvVar
), L
" ");
462 hr
= StringCchCatW(wszLayerEnvVar
, ARRAYSIZE(wszLayerEnvVar
), LayerName
);
465 SHIMENG_FAIL("Unable to append %S\n", LayerName
);
469 while (ShimRef
!= TAGID_NULL
)
472 if (SdbTagIDToTagRef(hsdb
, pdb
, ShimRef
, &trShimRef
))
473 SeiAddShim(trShimRef
, pShimRef
);
475 ShimRef
= SdbFindNextTag(pdb
, tag
, ShimRef
);
478 /* Handle FLAG_REF */
481 if (wszLayerEnvVar
[0])
482 SeiSetLayerEnvVar(wszLayerEnvVar
);
485 /* Given the hooks from one shim, find the relevant modules and store the combination of module + hook */
486 VOID
SeiAddHooks(PHOOKAPIEX hooks
, DWORD dwHookCount
, PSHIMINFO pShim
)
489 UNICODE_STRING UnicodeModName
;
492 RtlInitEmptyUnicodeString(&UnicodeModName
, Buf
, sizeof(Buf
));
494 for (n
= 0; n
< dwHookCount
; ++n
)
496 ANSI_STRING AnsiString
;
498 PHOOKAPIEX hook
= hooks
+ n
;
499 PHOOKAPIEX
* pHookApi
;
500 PHOOKMODULEINFO HookModuleInfo
;
502 RtlInitAnsiString(&AnsiString
, hook
->LibraryName
);
503 if (!NT_SUCCESS(RtlAnsiStringToUnicodeString(&UnicodeModName
, &AnsiString
, FALSE
)))
505 SHIMENG_FAIL("Unable to convert %s to Unicode\n", hook
->LibraryName
);
509 RtlInitAnsiString(&AnsiString
, hook
->FunctionName
);
510 if (NT_SUCCESS(LdrGetDllHandle(NULL
, 0, &UnicodeModName
, &DllHandle
)))
515 if (!NT_SUCCESS(LdrGetProcedureAddress(DllHandle
, &AnsiString
, 0, &ProcAddress
)))
517 SHIMENG_FAIL("Unable to retrieve %s!%s\n", hook
->LibraryName
, hook
->FunctionName
);
521 HookModuleInfo
= SeiFindHookModuleInfo(NULL
, DllHandle
);
522 hook
->OriginalFunction
= ProcAddress
;
526 HookModuleInfo
= SeiFindHookModuleInfo(&UnicodeModName
, NULL
);
532 HookModuleInfo
= ARRAY_Append(&g_pHookArray
, HOOKMODULEINFO
);
536 HookModuleInfo
->BaseAddress
= DllHandle
;
537 ARRAY_Init(&HookModuleInfo
->HookApis
, PHOOKAPIEX
);
538 RtlCreateUnicodeString(&HookModuleInfo
->Name
, UnicodeModName
.Buffer
);
541 hook
->pShimInfo
= pShim
;
543 for (j
= 0; j
< ARRAY_Size(&HookModuleInfo
->HookApis
); ++j
)
545 PHOOKAPIEX HookApi
= *ARRAY_At(&HookModuleInfo
->HookApis
, PHOOKAPIEX
, j
);
546 int CmpResult
= strcmp(hook
->FunctionName
, HookApi
->FunctionName
);
549 /* Multiple hooks on one function? --> use ApiLink */
550 SHIMENG_FAIL("Multiple hooks on one API is not yet supported!\n");
554 pHookApi
= ARRAY_Append(&HookModuleInfo
->HookApis
, PHOOKAPIEX
);
559 typedef FARPROC(WINAPI
* GETPROCADDRESSPROC
)(HINSTANCE
, LPCSTR
);
561 /* Check if we should fake the return from GetProcAddress (because we also redirected the iat for this module) */
562 FARPROC WINAPI
StubGetProcAddress(HINSTANCE hModule
, LPCSTR lpProcName
)
564 char szOrdProcName
[10] = "";
565 LPCSTR lpPrintName
= lpProcName
;
566 PVOID Addr
= _ReturnAddress();
567 PHOOKMODULEINFO HookModuleInfo
;
568 FARPROC proc
= ((GETPROCADDRESSPROC
)g_IntHookEx
[0].OriginalFunction
)(hModule
, lpProcName
);
570 if (!HIWORD(lpProcName
))
572 sprintf(szOrdProcName
, "#%lu", (DWORD
)lpProcName
);
573 lpPrintName
= szOrdProcName
;
576 Addr
= SeiGetModuleFromAddress(Addr
);
577 if (SE_IsShimDll(Addr
))
579 SHIMENG_MSG("Not touching GetProcAddress for shim dll (%p!%s)", hModule
, lpPrintName
);
583 SHIMENG_MSG("(GetProcAddress(%p!%s) => %p\n", hModule
, lpProcName
, lpPrintName
);
585 HookModuleInfo
= SeiFindHookModuleInfo(NULL
, hModule
);
587 /* FIXME: Ordinal not yet supported */
588 if (HookModuleInfo
&& HIWORD(lpProcName
))
591 for (n
= 0; n
< ARRAY_Size(&HookModuleInfo
->HookApis
); ++n
)
593 PHOOKAPIEX HookApi
= *ARRAY_At(&HookModuleInfo
->HookApis
, PHOOKAPIEX
, n
);
594 int CmpResult
= strcmp(lpProcName
, HookApi
->FunctionName
);
597 SHIMENG_MSG("Redirecting %p to %p\n", proc
, HookApi
->ReplacementFunction
);
598 proc
= HookApi
->ReplacementFunction
;
607 /* Walk all shim modules / enabled shims, and add their hooks */
608 VOID
SeiResolveAPIs(VOID
)
612 /* Enumerate all Shim modules */
613 for (mod
= 0; mod
< ARRAY_Size(&g_pShimInfo
); ++mod
)
615 PSHIMMODULE pShimModule
= *ARRAY_At(&g_pShimInfo
, PSHIMMODULE
, mod
);
616 DWORD dwShimCount
= ARRAY_Size(&pShimModule
->EnabledShims
);
618 /* Enumerate all Shims */
619 for (n
= 0; n
< dwShimCount
; ++n
)
621 PSHIMINFO pShim
= *ARRAY_At(&pShimModule
->EnabledShims
, PSHIMINFO
, n
);
623 PHOOKAPIEX hooks
= pShim
->pHookApi
;
624 DWORD dwHookCount
= pShim
->dwHookCount
;
626 SeiAddHooks(hooks
, dwHookCount
, pShim
);
631 /* If we hooked something, we should also redirect GetProcAddress */
632 VOID
SeiAddInternalHooks(DWORD dwNumHooks
)
636 g_bInternalHooksUsed
= FALSE
;
640 SeiAddHooks(g_IntHookEx
, ARRAYSIZE(g_IntHookEx
), NULL
);
641 g_bInternalHooksUsed
= TRUE
;
644 /* Patch one function in the iat */
645 VOID
SeiPatchNewImport(PIMAGE_THUNK_DATA FirstThunk
, PHOOKAPIEX HookApi
, PLDR_DATA_TABLE_ENTRY LdrEntry
)
647 ULONG OldProtection
= 0;
652 SHIMENG_INFO("Hooking API \"%s!%s\" for DLL \"%wZ\"\n", HookApi
->LibraryName
, HookApi
->FunctionName
, &LdrEntry
->BaseDllName
);
654 Ptr
= &FirstThunk
->u1
.Function
;
655 Size
= sizeof(FirstThunk
->u1
.Function
);
656 Status
= NtProtectVirtualMemory(NtCurrentProcess(), &Ptr
, &Size
, PAGE_EXECUTE_READWRITE
, &OldProtection
);
658 if (!NT_SUCCESS(Status
))
660 SHIMENG_FAIL("Unable to unprotect 0x%p\n", &FirstThunk
->u1
.Function
);
664 SHIMENG_INFO("changing 0x%p to 0x%p\n", FirstThunk
->u1
.Function
, HookApi
->ReplacementFunction
);
666 FirstThunk
->u1
.Function
= (ULONGLONG
)HookApi
->ReplacementFunction
;
668 FirstThunk
->u1
.Function
= (DWORD
)HookApi
->ReplacementFunction
;
671 Size
= sizeof(FirstThunk
->u1
.Function
);
672 Status
= NtProtectVirtualMemory(NtCurrentProcess(), &Ptr
, &Size
, OldProtection
, &OldProtection
);
674 if (!NT_SUCCESS(Status
))
676 SHIMENG_WARN("Unable to reprotect 0x%p\n", &FirstThunk
->u1
.Function
);
681 PINEXCLUDE
SeiFindInExclude(PARRAY InExclude
, PCUNICODE_STRING DllName
)
685 for (n
= 0; n
< ARRAY_Size(InExclude
); ++n
)
687 PINEXCLUDE InEx
= ARRAY_At(InExclude
, INEXCLUDE
, n
);
689 if (RtlEqualUnicodeString(&InEx
->Module
, DllName
, TRUE
))
696 BOOL
SeiIsExcluded(PLDR_DATA_TABLE_ENTRY LdrEntry
, PHOOKAPIEX HookApi
)
698 PSHIMINFO pShimInfo
= HookApi
->pShimInfo
;
699 PINEXCLUDE InExclude
;
700 BOOL IsExcluded
= FALSE
;
704 /* Internal hook, do not exclude it */
708 /* By default, everything from System32 or WinSxs is excluded */
709 if (RtlPrefixUnicodeString(&g_System32Directory
, &LdrEntry
->FullDllName
, TRUE
) ||
710 RtlPrefixUnicodeString(&g_SxsDirectory
, &LdrEntry
->FullDllName
, TRUE
))
713 InExclude
= SeiFindInExclude(&pShimInfo
->InExclude
, &LdrEntry
->BaseDllName
);
716 /* If it is on the 'exclude' list, bail out */
717 if (!InExclude
->Include
)
719 SHIMENG_INFO("Module '%wZ' excluded for shim %S, API '%s!%s', because it on in the exclude list.\n",
720 &LdrEntry
->BaseDllName
, pShimInfo
->ShimName
, HookApi
->LibraryName
, HookApi
->FunctionName
);
724 /* If it is on the 'include' list, override System32 / Winsxs check. */
727 SHIMENG_INFO("Module '%wZ' included for shim %S, API '%s!%s', because it is on the include list.\n",
728 &LdrEntry
->BaseDllName
, pShimInfo
->ShimName
, HookApi
->LibraryName
, HookApi
->FunctionName
);
736 SHIMENG_INFO("Module '%wZ' excluded for shim %S, API '%s!%s', because it is in System32/WinSXS.\n",
737 &LdrEntry
->BaseDllName
, pShimInfo
->ShimName
, HookApi
->LibraryName
, HookApi
->FunctionName
);
743 VOID
SeiAppendInExclude(PARRAY dest
, PCWSTR ModuleName
, BOOL IsInclude
)
745 PINEXCLUDE InExclude
;
746 UNICODE_STRING ModuleNameU
;
747 RtlInitUnicodeString(&ModuleNameU
, ModuleName
);
749 InExclude
= SeiFindInExclude(dest
, &ModuleNameU
);
752 InExclude
->Include
= IsInclude
;
756 InExclude
= ARRAY_Append(dest
, INEXCLUDE
);
759 PCWSTR ModuleNameCopy
= SdbpStrDup(ModuleName
);
760 RtlInitUnicodeString(&InExclude
->Module
, ModuleNameCopy
);
761 InExclude
->Include
= IsInclude
;
765 /* Read the INEXCLUD tags from a given parent tag */
766 VOID
SeiReadInExclude(PDB pdb
, TAGID parent
, PARRAY dest
)
770 InExcludeTag
= SdbFindFirstTag(pdb
, parent
, TAG_INEXCLUD
);
772 while (InExcludeTag
!= TAGID_NULL
)
775 TAGID ModuleTag
= SdbFindFirstTag(pdb
, InExcludeTag
, TAG_MODULE
);
776 TAGID IncludeTag
= SdbFindFirstTag(pdb
, InExcludeTag
, TAG_INCLUDE
);
778 ModuleName
= SdbGetStringTagPtr(pdb
, ModuleTag
);
781 SeiAppendInExclude(dest
, ModuleName
, IncludeTag
!= TAGID_NULL
);
785 SHIMENG_WARN("INEXCLUDE without Module: 0x%x\n", InExcludeTag
);
788 InExcludeTag
= SdbFindNextTag(pdb
, parent
, InExcludeTag
);
792 VOID
SeiBuildGlobalInclExclList(HSDB hsdb
)
795 TAGREF tr
= TAGREF_ROOT
;
796 TAGID root
, db
, library
;
798 if (!SdbTagRefToTagID(hsdb
, tr
, &pdb
, &root
))
800 SHIMENG_WARN("Unable to resolve database root\n");
803 db
= SdbFindFirstTag(pdb
, root
, TAG_DATABASE
);
804 if (db
== TAGID_NULL
)
806 SHIMENG_WARN("Unable to resolve database\n");
809 library
= SdbFindFirstTag(pdb
, db
, TAG_LIBRARY
);
810 if (library
== TAGID_NULL
)
812 SHIMENG_WARN("Unable to resolve library\n");
816 SeiReadInExclude(pdb
, library
, &g_InExclude
);
819 VOID
SeiBuildInclExclList(PDB pdb
, TAGID ShimTag
, PSHIMINFO pShimInfo
)
823 /* First duplicate the global in/excludes */
824 for (n
= 0; n
< ARRAY_Size(&g_InExclude
); ++n
)
826 PINEXCLUDE InEx
= ARRAY_At(&g_InExclude
, INEXCLUDE
, n
);
827 SeiAppendInExclude(&pShimInfo
->InExclude
, InEx
->Module
.Buffer
, InEx
->Include
);
830 /* Now read this shim's in/excludes (possibly overriding the global ones) */
831 SeiReadInExclude(pdb
, ShimTag
, &pShimInfo
->InExclude
);
834 /* Given one loaded module, redirect (hook) all functions from the iat that are registered by shims */
835 VOID
SeiHookImports(PLDR_DATA_TABLE_ENTRY LdrEntry
)
838 PIMAGE_IMPORT_DESCRIPTOR ImportDescriptor
;
839 PBYTE DllBase
= LdrEntry
->DllBase
;
841 if (SE_IsShimDll(DllBase
) || g_hInstance
== LdrEntry
->DllBase
)
843 SHIMENG_INFO("Skipping shim module 0x%p \"%wZ\"\n", LdrEntry
->DllBase
, &LdrEntry
->BaseDllName
);
847 ImportDescriptor
= RtlImageDirectoryEntryToData(DllBase
, TRUE
, IMAGE_DIRECTORY_ENTRY_IMPORT
, &Size
);
848 if (!ImportDescriptor
)
850 SHIMENG_INFO("Skipping module 0x%p \"%wZ\" due to no iat found\n", LdrEntry
->DllBase
, &LdrEntry
->BaseDllName
);
854 SHIMENG_INFO("Hooking module 0x%p \"%wZ\"\n", LdrEntry
->DllBase
, &LdrEntry
->BaseDllName
);
856 for ( ;ImportDescriptor
->Name
&& ImportDescriptor
->OriginalFirstThunk
; ImportDescriptor
++)
858 PHOOKMODULEINFO HookModuleInfo
;
860 /* Do we have hooks for this module? */
861 HookModuleInfo
= SeiFindHookModuleInfoForImportDescriptor(DllBase
, ImportDescriptor
);
865 PIMAGE_THUNK_DATA OriginalThunk
, FirstThunk
;
868 for (n
= 0; n
< ARRAY_Size(&HookModuleInfo
->HookApis
); ++n
)
871 PHOOKAPIEX HookApi
= *ARRAY_At(&HookModuleInfo
->HookApis
, PHOOKAPIEX
, n
);
873 /* Check if this module should be excluded from being hooked (system32/winsxs, global or shim exclude) */
874 if (SeiIsExcluded(LdrEntry
, HookApi
))
879 OriginalThunk
= (PIMAGE_THUNK_DATA
)(DllBase
+ ImportDescriptor
->OriginalFirstThunk
);
880 FirstThunk
= (PIMAGE_THUNK_DATA
)(DllBase
+ ImportDescriptor
->FirstThunk
);
882 /* Walk all imports */
883 for (;OriginalThunk
->u1
.AddressOfData
&& FirstThunk
->u1
.Function
; OriginalThunk
++, FirstThunk
++)
885 if (!IMAGE_SNAP_BY_ORDINAL32(OriginalThunk
->u1
.AddressOfData
))
887 PIMAGE_IMPORT_BY_NAME ImportName
;
889 ImportName
= (PIMAGE_IMPORT_BY_NAME
)(DllBase
+ OriginalThunk
->u1
.AddressOfData
);
890 if (!strcmp((PCSTR
)ImportName
->Name
, HookApi
->FunctionName
))
892 SeiPatchNewImport(FirstThunk
, HookApi
, LdrEntry
);
894 /* Sadly, iat does not have to be sorted, and can even contain duplicate entries. */
900 SHIMENG_FAIL("Ordinals not yet supported\n");
907 /* One entry not found. */
909 SHIMENG_INFO("Entry \"%s!%s\" not found for \"%wZ\"\n", HookApi
->LibraryName
, HookApi
->FunctionName
, &LdrEntry
->BaseDllName
);
911 SHIMENG_INFO("Entry \"%s!%s\" found %d times for \"%wZ\"\n", HookApi
->LibraryName
, HookApi
->FunctionName
, dwFound
, &LdrEntry
->BaseDllName
);
919 VOID
PatchNewModules(PPEB Peb
)
921 PLIST_ENTRY ListHead
, ListEntry
;
922 PLDR_DATA_TABLE_ENTRY LdrEntry
;
924 ListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
925 ListEntry
= ListHead
->Flink
;
927 while (ListHead
!= ListEntry
)
929 LdrEntry
= CONTAINING_RECORD(ListEntry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
930 SeiHookImports(LdrEntry
);
932 ListEntry
= ListEntry
->Flink
;
937 VOID
SeiInitPaths(VOID
)
939 #define SYSTEM32 L"\\system32"
940 #define WINSXS L"\\winsxs"
942 PWSTR WindowsDirectory
= SdbpStrDup(SharedUserData
->NtSystemRoot
);
943 RtlInitUnicodeString(&g_WindowsDirectory
, WindowsDirectory
);
945 g_System32Directory
.MaximumLength
= g_WindowsDirectory
.Length
+ SdbpStrsize(SYSTEM32
);
946 g_System32Directory
.Buffer
= SdbpAlloc(g_System32Directory
.MaximumLength
);
947 RtlCopyUnicodeString(&g_System32Directory
, &g_WindowsDirectory
);
948 RtlAppendUnicodeToString(&g_System32Directory
, SYSTEM32
);
950 g_SxsDirectory
.MaximumLength
= g_WindowsDirectory
.Length
+ SdbpStrsize(WINSXS
);
951 g_SxsDirectory
.Buffer
= SdbpAlloc(g_SxsDirectory
.MaximumLength
);
952 RtlCopyUnicodeString(&g_SxsDirectory
, &g_WindowsDirectory
);
953 RtlAppendUnicodeToString(&g_SxsDirectory
, WINSXS
);
960 Level(INFO) Using USER apphack flags 0x2080000
963 VOID
SeiInit(PUNICODE_STRING ProcessImage
, HSDB hsdb
, SDBQUERYRESULT
* pQuery
)
967 DWORD dwTotalHooks
= 0;
969 PPEB Peb
= NtCurrentPeb();
971 /* We should only be called once! */
972 ASSERT(g_pShimInfo
.ItemSize__
== 0);
974 ARRAY_Init(&ShimRefArray
, TAGREF
);
975 ARRAY_Init(&g_pShimInfo
, PSHIMMODULE
);
976 ARRAY_Init(&g_pHookArray
, HOOKMODULEINFO
);
977 ARRAY_Init(&g_InExclude
, INEXCLUDE
);
981 SeiCheckComPlusImage(Peb
->ImageBaseAddress
);
984 if (pQuery->trApphelp)
985 SeiDisplayAppHelp(?pQuery->trApphelp?);
988 SeiDbgPrint(SEI_MSG
, NULL
, "ShimInfo(ExePath(%wZ))\n", ProcessImage
);
989 SeiBuildShimRefArray(hsdb
, pQuery
, &ShimRefArray
);
990 SeiDbgPrint(SEI_MSG
, NULL
, "ShimInfo(Complete)\n");
992 SHIMENG_INFO("Got %d shims\n", ARRAY_Size(&ShimRefArray
));
993 SeiBuildGlobalInclExclList(hsdb
);
995 /* Walk all shims referenced (in layers + exes), and load their modules */
996 for (n
= 0; n
< ARRAY_Size(&ShimRefArray
); ++n
)
1001 TAGREF tr
= *ARRAY_At(&ShimRefArray
, TAGREF
, n
);
1003 if (SdbTagRefToTagID(hsdb
, tr
, &pdb
, &ShimRef
))
1005 LPCWSTR ShimName
, DllName
, CommandLine
= NULL
;
1007 WCHAR FullNameBuffer
[MAX_PATH
];
1008 UNICODE_STRING UnicodeDllName
;
1010 PSHIMMODULE pShimModuleInfo
= NULL
;
1011 ANSI_STRING AnsiCommandLine
= RTL_CONSTANT_STRING("");
1012 PSHIMINFO pShimInfo
= NULL
;
1013 PHOOKAPIEX pHookApi
;
1016 ShimName
= SeiGetStringPtr(pdb
, ShimRef
, TAG_NAME
);
1019 SHIMENG_FAIL("Failed to retrieve the name for 0x%x\n", tr
);
1023 CommandLine
= SeiGetStringPtr(pdb
, ShimRef
, TAG_COMMAND_LINE
);
1024 if (CommandLine
&& *CommandLine
)
1026 RtlInitUnicodeString(&UnicodeDllName
, CommandLine
);
1027 if (NT_SUCCESS(RtlUnicodeStringToAnsiString(&AnsiCommandLine
, &UnicodeDllName
, TRUE
)))
1029 SHIMENG_INFO("COMMAND LINE %s for %S", AnsiCommandLine
.Buffer
, ShimName
);
1033 AnsiCommandLine
.Buffer
= "";
1038 ShimTag
= SeiGetDWORD(pdb
, ShimRef
, TAG_SHIM_TAGID
);
1041 SHIMENG_FAIL("Failed to resolve %S to a shim\n", ShimName
);
1045 if (!SdbGetAppPatchDir(NULL
, FullNameBuffer
, ARRAYSIZE(FullNameBuffer
)))
1047 SHIMENG_WARN("Failed to get the AppPatch dir\n");
1051 DllName
= SeiGetStringPtr(pdb
, ShimTag
, TAG_DLLFILE
);
1052 if (DllName
== NULL
||
1053 !SUCCEEDED(StringCchCatW(FullNameBuffer
, ARRAYSIZE(FullNameBuffer
), L
"\\")) ||
1054 !SUCCEEDED(StringCchCatW(FullNameBuffer
, ARRAYSIZE(FullNameBuffer
), DllName
)))
1056 SHIMENG_WARN("Failed to build a full path for %S\n", ShimName
);
1060 RtlInitUnicodeString(&UnicodeDllName
, FullNameBuffer
);
1061 if (NT_SUCCESS(LdrGetDllHandle(NULL
, NULL
, &UnicodeDllName
, &BaseAddress
)))
1063 /* This shim dll was already loaded, let's find it */
1064 pShimModuleInfo
= SeiGetShimModuleInfo(BaseAddress
);
1066 else if (!NT_SUCCESS(LdrLoadDll(NULL
, NULL
, &UnicodeDllName
, &BaseAddress
)))
1068 SHIMENG_WARN("Failed to load %wZ for %S\n", &UnicodeDllName
, ShimName
);
1071 /* No shim module found (or we just loaded it) */
1072 if (!pShimModuleInfo
)
1074 pShimModuleInfo
= SeiCreateShimModuleInfo(DllName
, BaseAddress
);
1075 if (!pShimModuleInfo
)
1077 SHIMENG_FAIL("Failed to allocate ShimInfo for %S\n", DllName
);
1082 SHIMENG_INFO("Shim DLL 0x%p \"%wZ\" loaded\n", BaseAddress
, &UnicodeDllName
);
1083 SHIMENG_INFO("Using SHIM \"%S!%S\"\n", DllName
, ShimName
);
1085 /* Ask this shim what hooks it needs (and pass along the commandline) */
1086 pHookApi
= pShimModuleInfo
->pGetHookAPIs(AnsiCommandLine
.Buffer
, ShimName
, &dwHookCount
);
1087 SHIMENG_INFO("GetHookAPIs returns %d hooks for DLL \"%wZ\" SHIM \"%S\"\n", dwHookCount
, &UnicodeDllName
, ShimName
);
1089 pShimInfo
= SeiAppendHookInfo(pShimModuleInfo
, pHookApi
, dwHookCount
, ShimName
);
1091 /* If this shim has hooks, create the include / exclude lists */
1093 SeiBuildInclExclList(pdb
, ShimTag
, pShimInfo
);
1095 if (CommandLine
&& *CommandLine
)
1096 RtlFreeAnsiString(&AnsiCommandLine
);
1098 dwTotalHooks
+= dwHookCount
;
1102 SeiAddInternalHooks(dwTotalHooks
);
1104 PatchNewModules(Peb
);
1108 /* Load the database + unpack the shim data (if this process is allowed) */
1109 BOOL
SeiGetShimData(PUNICODE_STRING ProcessImage
, PVOID pShimData
, HSDB
* pHsdb
, SDBQUERYRESULT
* pQuery
)
1111 static const UNICODE_STRING ForbiddenShimmingApps
[] = {
1112 RTL_CONSTANT_STRING(L
"ntsd.exe"),
1113 RTL_CONSTANT_STRING(L
"windbg.exe"),
1115 RTL_CONSTANT_STRING(L
"slsvc.exe"),
1118 static const UNICODE_STRING BackSlash
= RTL_CONSTANT_STRING(L
"\\");
1119 static const UNICODE_STRING ForwdSlash
= RTL_CONSTANT_STRING(L
"/");
1120 UNICODE_STRING ProcessName
;
1121 USHORT Back
, Forward
;
1125 if (!NT_SUCCESS(RtlFindCharInUnicodeString(RTL_FIND_CHAR_IN_UNICODE_STRING_START_AT_END
, ProcessImage
, &BackSlash
, &Back
)))
1128 if (!NT_SUCCESS(RtlFindCharInUnicodeString(RTL_FIND_CHAR_IN_UNICODE_STRING_START_AT_END
, ProcessImage
, &ForwdSlash
, &Forward
)))
1135 Back
+= sizeof(WCHAR
);
1137 ProcessName
.Buffer
= ProcessImage
->Buffer
+ Back
/ sizeof(WCHAR
);
1138 ProcessName
.Length
= ProcessImage
->Length
- Back
;
1139 ProcessName
.MaximumLength
= ProcessImage
->MaximumLength
- Back
;
1141 for (n
= 0; n
< ARRAYSIZE(ForbiddenShimmingApps
); ++n
)
1143 if (RtlEqualUnicodeString(&ProcessName
, ForbiddenShimmingApps
+ n
, TRUE
))
1145 SHIMENG_MSG("Not shimming %wZ\n", ForbiddenShimmingApps
+ n
);
1150 /* We should probably load all db's here, but since we do not support that yet... */
1151 hsdb
= SdbInitDatabase(HID_DOS_PATHS
| SDB_DATABASE_MAIN_SHIM
, NULL
);
1154 if (SdbUnpackAppCompatData(hsdb
, ProcessImage
->Buffer
, pShimData
, pQuery
))
1159 SdbReleaseDatabase(hsdb
);
1166 VOID NTAPI
SE_InstallBeforeInit(PUNICODE_STRING ProcessImage
, PVOID pShimData
)
1169 SDBQUERYRESULT QueryResult
= { { 0 } };
1170 SHIMENG_MSG("(%wZ, %p)\n", ProcessImage
, pShimData
);
1172 if (!SeiGetShimData(ProcessImage
, pShimData
, &hsdb
, &QueryResult
))
1174 SHIMENG_FAIL("Failed to get shim data\n");
1178 g_bShimDuringInit
= TRUE
;
1179 SeiInit(ProcessImage
, hsdb
, &QueryResult
);
1180 g_bShimDuringInit
= FALSE
;
1182 SdbReleaseDatabase(hsdb
);
1185 VOID NTAPI
SE_InstallAfterInit(PUNICODE_STRING ProcessImage
, PVOID pShimData
)
1187 NotifyShims(SHIM_NOTIFY_ATTACH
, NULL
);
1190 VOID NTAPI
SE_ProcessDying(VOID
)
1192 SHIMENG_MSG("()\n");
1193 NotifyShims(SHIM_NOTIFY_DETACH
, NULL
);
1196 VOID WINAPI
SE_DllLoaded(PLDR_DATA_TABLE_ENTRY LdrEntry
)
1198 SHIMENG_INFO("%sINIT. loading DLL \"%wZ\"\n", g_bShimDuringInit
? "" : "AFTER ", &LdrEntry
->BaseDllName
);
1199 NotifyShims(SHIM_REASON_DLL_LOAD
, LdrEntry
);
1202 VOID WINAPI
SE_DllUnloaded(PLDR_DATA_TABLE_ENTRY LdrEntry
)
1204 SHIMENG_MSG("(%p)\n", LdrEntry
);
1205 NotifyShims(SHIM_REASON_DLL_UNLOAD
, LdrEntry
);
1208 BOOL WINAPI
SE_IsShimDll(PVOID BaseAddress
)
1210 SHIMENG_MSG("(%p)\n", BaseAddress
);
1212 return SeiGetShimModuleInfo(BaseAddress
) != NULL
;