Fix Your Broken Applications: The Black Art of Shims

Chris Jackson
The App Compat Guy
Microsoft Corporation
WCL304
How Shims Work
Import
Function
Export
Function
Application
Windows
Shim DLL
Shims for User Account Control
Standard User Analyzer
Application
LuaPriv
Windows
AppVerifier
Logs
XML
SUA Mitigations
SUA can recommend:
ElevateCreateProcess
ForceAdminAccess
LocalMappedObject
VirtualizeDeleteFile
VirtualizeHKCRLite
CorrectFilePaths
VirtualRegistry
ElevateCreateProcess
Symptoms
ERROR_ELEVATION_REQUIRED
Fix description
Tries again, requesting elevation
ForceAdminAccess
Symptoms
Fails explicit administrator check
Fix description
Lies
ForceAdminAccess Shim for IsUserAnAdmin:
return TRUE;
LocalMappedObject
Symptoms
Can’t create in Global namespace
Fix description
Creates in Local namespace
VirtualizeDeleteFile
Symptoms
Can’t delete files
Fix description
Pretends to delete files
VirtualizeHKCRLite
Symptoms
Can’t register COM components
Fix description
Registers them per-user
SUA Mitigations
UAC Manifests
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1"
manifestVersion="1.0">
<assemblyIdentity type="win32" processorArchitecture="*"
version="1.0.0.0" name="MyApplication.exe"/>
<description>My totally sweet Vista application</description>
<ms_asmv2:trustInfo xmlns:ms_asmv2="urn:schemas-microsoftcom:asm.v2">
<ms_asmv2:security>
<ms_asmv2:requestedPrivileges>
<ms_asmv2:requestedExecutionLevel level="asInvoker ||
highestAvailable || requireAdministrator"/>
</ms_asmv2:requestedPrivileges>
</ms_asmv2:security>
</ms_asmv2:trustInfo>
</assembly>
Installer Detection
Legacy installers / updaters
SpecificInstaller
GenericInstaller
SpecificNonInstaller
RunAsAdmin
Symptoms
Requires admin
Fix description
Prompts for elevation
RunAsHighest
Symptoms
Had both admin and standard user views
Fix description
Provides most powerful token
RunAsInvoker
Symptoms
Prompting unnecessarily
Fix description
No more prompt
SpecificInstaller
Symptoms
Not fixed as a legacy setup
Fix description
Flags it as a legacy setup
SpecificNonInstaller
Symptoms
Flagged as a legacy setup inappropriately
Fix description
No longer flagged as a legacy setup
Run Level Specification
VirtualizeRegisterTypeLib
Symptoms
Registering type library fails
Fix description
Registers type library per-user
Shims for File and Registry Paths
VirtualRegistry
Symptoms
Problem reading/writing registry value
Fix description
Returns a different registry value
Command line parameters...
VirtualRegistry Generic Fix
AddRedirect ( HKLM\Key ^ HKCU\Key ^
HKLM\Key2 ^ HKCU\Key2)
VirtualRegistry
CorrectFilePaths
Symptoms
Problem reading/writing a file
Fix description
Redirects to a different file
CorrectFilePaths
Shims for User Interface
Process Isolation
UIPIEnableStandardMessages
Symptoms
Window messages not delivered
Fix description
Adds the message to the filter
Parameters
MessageID1 MessageID2 MessageID3
Example:
1055 1056 1057 1058 1069
UIPIEnableCustomMessages
Symptoms
Custom window messages not delivered
Fix description
Adds the custom window message to the allowed filter
Parameters
MessageString1 MessageString2
User Interface Process Isolation
Shims for Windows
Resource Protection
Shims for
WRPMitigation
Symptoms
Writing protected operating system file / registry key
Fix description
Lies
WRPDllRegister
Symptoms
Registering protected OS component
Fix description
New DllRegisterServer
Parameters
componet1.dll;component2.dll
Example:
hhctrl.ocx;itircl.dll;itss.dll
WRPRegDeleteKey
Symptoms
Can’t delete protected OS registry key
Fix description
Lies
Windows Resource Protection
Shims for Operating System Version
I Can't Find the > Key…
Operating System
Version Number
Release Date
Windows 1.0
1.04
1985
Windows 2.0
2.11
1987
Windows 3.0
3.00
1990
Windows NT 3.1
3.10.528
1993
Windows for Workgroups 3.11
3.11
1993
Windows NT Workstation 3.5
3.5.807
1994
Windows NT Workstation 3.51
3.51.1057
1995
Windows 95
4.0.950
1995
Windows NT Workstation 4.0
4.0.1381
1996
Windows 98
4.1.1998
1998
Windows 98 Second Edition
4.1.2222
1999
Windows Me
4.90.3000
2000
Windows 2000 Professional
5.0.2195
2000
Windows XP
5.1.2600
2001
Windows Vista
6.0.6000
2006
xxxVersionLie
Symptoms
“Unsupported operating system”
Fix description
Lies
Version Lie Shims
Win95VersionLie
WinNT4SP5VersionLie
Win98VersionLie
Win2000VersionLie
Win2000SP1VersionLie
Win2000SP2VersionLie
Win2000SP3VersionLie
WinXPVersionLie
WinXPSP1VersionLie
WinXPSP2VersionLie
Win2K3RTMVersionLie
Win2K3SP1VersionLie
VistaRTMVersionLie
Version Lie Layers
Win95
NT4SP5
Win98
Win2000
Win2000SP2
Win2000SP3
WinXP
WinXPSP1
WinXPSP2
WinXPSP2VersionLie
WinSrv03
WinSrv03SP1
VistaRTM
Shims and Layers
Application
Shim
Child Application
Layer
Windows
Layers: More Than Version Lies
XPSP2 Layer:
DirectXVersionLie
ElevateCreateProcess
EmulateSorting
EnableLegacyException
HandlingInOLE
FailObsoleteShellAPIs
GlobalMemoryStatus2GB
HandleBadPtr
HardwareAudioMixer
LoadLibraryCWD
NoGhost
RedirectMP3Codec
VirtualRegistry
WinXPSP2VersionLie
Operating System Version
How to INSTALL Custom
Shim Databases
sdbinst.exe
%windir%\system32\sdbinst.exe
sdbinst Command Line
-q
-u
-g
-n
Quiet mode
Uninstall
Guid (uninstall only)
Internal name (uninstall only)
Deployment Options
Per enterprise
Per application
Installing Custom Shim Databases
API Hooking Option #1
Overwriting code
Locate the address of the function
Save the first few bytes
Overwrite with JMP
Overwriting Code: Hooking
USER32!MessageBoxA:
mov edi,edi ;nop for hot patching
push ebp
;set up stack frame
mov ebp,esp ;””
Overwriting Code: Hooking
USER32!MessageBoxA:
jmp rel8
;short jump to hook
push ebp
;we never get here
mov ebp,esp ;””
Overwriting Code: Challenges
CPU dependent
JUMP instructions vary between x86, x64, IA-64
Not thread safe
“…it is the programmer’s responsibility to ensure
that no other threads are executing in the address
space while a detour is inserted or removed.”
API Hooking Option #2
Module import section
Modify address
No CPU dependency
No thread synchronization
IAT Modification: Data Structures
PE Signature
File Headers
MS-DOS Header
Optional Headers
Export Table
NT Headers
Data Directories
Import Table
Section Headers
Resource Table
Section Images
Exception Table
...
IAT Modification: Import Table
Original First Thunk
Time Date Stamp
0x1034
GetModuleHandleA
0x1047
LoadLibrary
...
...
Forwarder Chain
Imported DLL Name
First Thunk
kernel32.dll
...
user32.dll
advapi32.dll
...
IAT Modification: Sample Code
Richter & Nasarre, 2008
ULONG ulSize;
PIMAGE_IMPORT_DESCRIPTOR pImportDesc = NULL;
__try {
pImportDesc = (PIMAGE_IMPORT_DESCRIPTOR)ImageDirectoryEntryToData(hmodCaller, TRUE,
IMAGE_DIRECTORY_ENTRY_IMPORT, &ulSize);
} __except (InvalidReadExceptionFilter(GetExceptionInformation())) {}
if (pImportDesc == NULL) return;
for (; pImportDesc->Name; pImportDesc++) {
PSTR pszModName=(PSTR)((PBYTE)hmodCaller + pImportDesc->Name);
if (lstrcmpiA(pszModName, pszCalleeModName) == 0) {
PIMAGE_THUNK_DATA pThunk = (PIMAGE_THUNK_DATA)((PBYTE)hmodCaller + pImportDesc->FirstThunk);
for (; pThunk->u1.Function; pThunk++) {
PROC* ppfn = (PROC*)&pThunk->u1.Function;
BOOL bFound = (*ppfn == pfnCurrent);
if (bFound) {
if (!WriteProcessMemory(GetCurrentProcess(), ppfn, &pfnNew, sizeof(pfnNew),
NULL) && (ERROR_NOACCESS == GetLastError())) {
DWORD dwOldProtect;
if (VirtualProtect(ppfn, sizeof(pfnNew), PAGE_WRITECOPY, &dwOldProtect)) {
WriteProcessMemory(GetCurrentProcess(), ppfn, &pfnNew, sizeof(pfnNew), NULL);
VirtualProtect(ppfn, sizeof(pfnNew), dwOldProtect, &dwOldProtect);
}
}
return;
}
}
}
}
Security: the Good
Application
Shim
Security: Something to Think About
Crack resources to locate dialog item ID
Implement hook for GetDlgItemText
Trick user into installing it
Your user-mode API interception can now
harvest passwords
API Hooking
Compatibility Administrator
/x switch
Search
Not perfect
Query
Shim Debug Spew
[HKEY_CURRENT_USER\Software\Microsoft\
Windows NT\CurrentVersion\AppCompatFlags]
"ShowDebugInfo"=dword:00000009
Debugger, DebugView, etc.
Shim Logging
Environment variables:
reg add
"HKLM\SYSTEM\CurrentControlSet\Control\Session
Manager\Environment" /v SHIM_DEBUG_LEVEL /t
REG_SZ /d 9 /f
reg add
"HKLM\SYSTEM\CurrentControlSet\Control\Session
Manager\Environment" /v SHIM_FILE_LOG /t
REG_SZ /d logfile.txt /f
%appdata%\logfile.txt
Shim Diagnostic Tools
When to Use Shims
Define standards:
Vender no longer in business
Internal applications
Support negotiable
Custom SDBs Management
Custom SDBs defined by GUID
Affects updates
Define and enforce policy / workflow
Test / mitigation  deployment
Centralized resources
Custom SDB Deployment
Package with installer
Centralized enterprise SDB
Managing Shims in the Enterprise
http://go.microsoft.com/fwlink/?LinkId=107072
Custom SDB Deployment
(More) Shims for User Account Control
CorrectShellExecuteHWND
Symptom
Taskbar flasher
Fix description
Use the currently active HWND
RetryOpenServiceWithReadAccess
Symptoms
Access denied opening service
Fix description
Try again requesting fewer rights
RetryOpenSCManagerWithReadAccess
Symptoms
Access denied opening Service Control Manager
Fix description
Try again requesting fewer rights
(More) UAC Shims
Shims for User Interface Issues
DisableDWM
Symptoms
Not rendering correctly
Fix description
Turn off DWM when the app is running
FakeLunaTheme
Symptoms
Hard to read
Fix description
Use XP Luna theme colors
User Interface Shims
Shims for Miscellaneous Issues
EmulateSorting
Symptoms
Search functions fail
Fix description
Use legacy sorting tables
SessionShim
Symptoms
Unable to talk to service
Fix description
Global  Local  original API
Parameters
\\ delimited list of object names, otherwise all objects shimmed
IgnoreAltTab
Symptoms
Alt-Tab or other special keys fail
Fix description
Filters out special keys
Parameters
NOKEYS – doesn’t disable Filter Keys / Sticky Keys
OPENGL – do not shim if running in OpenGL
IgnoreException
Symptoms
Unhandled exception (typically crashes)
Fix description
Ignores the exception
Yes, this should make you nervous…
Parameters...
IgnoreException Parameters 1/2
EXCEPTION1_NAME:EXCEPTION1_LEVEL;
EXCEPTION2_NAME:EXCEPTION2_LEVEL;…
Exception names can be:
ACCESS_VIOLATION_READ
ACCESS_VIOLATION_WRITE
ARRAY_BOUNDS_EXCEEDED
BREAKPOINT
DATATYPE_MISALIGNMENT
FLT_DENORMAL_OPERAND
FLT_DIVIDE_BY_ZERO
FLT_INEXACT_RESULT
FLT_INVALID_OPERATION
FLT_OVERFLOW
FLT_STACK_CHECK
FLT_UNDERFLOW
ILLEGAL_INSTRUCTION
IN_PAGE_ERROR
INT_DIVIDE_BY_ZERO
INT_OVERFLOW
INVALID_DISPOSITION
NONCONTINUABLE_EXCEPTION
PRIV_INSTRUCTION
SINGLE_STEP
STACK_OVERFLOW
INVALID_HANDLE
IgnoreException Parameters 2/2
Exception levels can be:
0 - Don't ignore the exception
1 - Ignore first chance exception
2 - Ignore second chance exception
3 - Exit process on second chance exception
IgnoreMessageBox
Symptoms
Extraneous message box
Fix description
Ignores the message box
Parameters
MessageBoxText1,MessageBoxCaption1;
MessageBoxText2,MessageBoxCaption2
Empty arguments match anything
Supports * and ? wildcards
Escape these characters: ? * , ; \
Miscellaneous Shims
Frequently Asked Questions
Managed code?
VB6 code?
msvbvm60.dll
16-bit code?
Top 10 System SDB Shims
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
GameUX
VirtualRegistry
CorrectFilePaths
Win95VersionLie
WinXPSP2VersionLie
IgnoreAltTab
ShimViaEAT
AOLFindBundledInstaller
ElevateCreateProcess
OpenDirectoryACL
http://www.appcompatguy.com
[email protected]
Resources
www.microsoft.com/teched
www.microsoft.com/learning
Sessions On-Demand & Community
Microsoft Certification & Training Resources
http://microsoft.com/technet
http://microsoft.com/msdn
Resources for IT Professionals
Resources for Developers
www.microsoft.com/learning
Microsoft Certification and Training Resources
Related Content
Breakout Sessions (session codes and titles)
WCL302 – Are You Breaking my Stuff Again? The Windows 7 App Compat Story
WCL304 – Fix Your Broken Applications: The Black Art of Shims
WCL401 – Not for the Faint of Heart: Hard Core App Compat Debugging
Track Resources
→ Want to find out which Windows Client sessions are best
suited to help you in your deployment lifecycle?
→ Want to talk face-to-face with folks from
the Windows Product Team?
Meet us today at the
Springboard Series Lounge, or visit us at
www.microsoft.com/springboard
Springboard Series
The Springboard Series empowers you to select the right resources, at the right
technical level, at the right point in your Windows® Client adoption and management
process. Come see why Springboard Series is your destination for Windows 7.
Complete an
evaluation on
CommNet and
enter to win!
© 2009 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.
The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should
not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS,
IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
Complete an
evaluation on
CommNet and
enter to win!
© 2009 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.
The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should
not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS,
IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.