fix your broken applications: the black art of shims

Post on 01-Jan-2017

255 Views

Category:

Documents

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Fix your Broken Applications: The Black Art of Shims

Chris JacksonThe App Compat GuyMicrosoft CorporationWCL304

Application Windows

How Shims Work

Shim DLL

ImportFunction

ExportFunction

ImportFunction

ExportFunction

Shims for User Account Control

Standard User Analyzer

Application

Windows

AppVerifier Logs XMLLuaPriv

SUA MitigationsSUA can recommend:

ElevateCreateProcessForceAdminAccessLocalMappedObjectVirtualizeDeleteFileVirtualizeHKCRLiteCorrectFilePathsVirtualRegistry

ElevateCreateProcessSymptomsERROR_ELEVATION_REQUIRED

Fix descriptionTries again, requesting elevation

ForceAdminAccess

SymptomsFails explicit administrator check

Fix descriptionLies

ForceAdminAccess Shim for IsUserAnAdmin:

return TRUE;

LocalMappedObject

SymptomsCan’t create in Global namespace

Fix descriptionCreates in Local namespace

VirtualizeDeleteFile

SymptomsCan’t delete files

Fix descriptionPretends to delete files

VirtualizeHKCRLite

SymptomsCan’t register COM components

Fix descriptionRegisters them per-user

SUA Mitigationsdemo

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-microsoft-

com: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

SymptomsRequires admin

Fix descriptionPrompts for elevation

RunAsHighest

SymptomsHad both admin and standard user views

Fix descriptionProvides most powerful token

RunAsInvoker

SymptomsPrompting unnecessarily

Fix descriptionNo more prompt

SpecificInstaller

SymptomsNot fixed as a legacy setup

Fix descriptionFlags it as a legacy setup

SpecificNonInstaller

SymptomsFlagged as a legacy setup inappropriately

Fix descriptionNo longer flagged as a legacy setup

Run Level Specificationdemo

VirtualizeRegisterTypeLib

SymptomsRegistering type library fails

Fix descriptionRegisters type library per-user

Shims for File and Registry Paths

VirtualRegistry

SymptomsProblem reading/writing registry value

Fix descriptionReturns a different registry value

Command line parameters...

VirtualRegistry Generic Fix

AddRedirect ( HKLM\Key ^ HKCU\Key ^ HKLM\Key2 ^ HKCU\Key2)

VirtualRegistrydemo

CorrectFilePaths

SymptomsProblem reading/writing a file

Fix descriptionRedirects to a different file

CorrectFilePathsdemo

Shims for User Interface Process Isolation

UIPIEnableStandardMessages

SymptomsWindow messages not delivered

Fix descriptionAdds the message to the filter

ParametersMessageID1 MessageID2 MessageID3

Example:1055 1056 1057 1058 1069

UIPIEnableCustomMessages

SymptomsCustom window messages not delivered

Fix descriptionAdds the custom window message to the allowed filter

ParametersMessageString1 MessageString2

User Interface Process Isolationdemo

Shims for Windows Resource Protection

Shims for

WRPMitigation

SymptomsWriting protected operating system file / registry key

Fix descriptionLies

WRPDllRegister

SymptomsRegistering protected OS component

Fix descriptionNew DllRegisterServer

Parameterscomponet1.dll;component2.dll

Example:hhctrl.ocx;itircl.dll;itss.dll

WRPRegDeleteKey

SymptomsCan’t delete protected OS registry key

Fix descriptionLies

Windows Resource Protectiondemo

Shims for Operating System Version

I Can't Find the > Key…Operating System Version Number Release Date

Windows 1.0 1.04 1985Windows 2.0 2.11 1987Windows 3.0 3.00 1990Windows NT 3.1 3.10.528 1993Windows for Workgroups 3.11 3.11 1993Windows NT Workstation 3.5 3.5.807 1994Windows NT Workstation 3.51 3.51.1057 1995Windows 95 4.0.950 1995Windows NT Workstation 4.0 4.0.1381 1996Windows 98 4.1.1998 1998Windows 98 Second Edition 4.1.2222 1999Windows Me 4.90.3000 2000Windows 2000 Professional 5.0.2195 2000Windows XP 5.1.2600 2001Windows Vista 6.0.6000 2006

xxxVersionLie

Symptoms“Unsupported operating system”

Fix descriptionLies

Version Lie ShimsWin95VersionLieWinNT4SP5VersionLieWin98VersionLieWin2000VersionLieWin2000SP1VersionLieWin2000SP2VersionLie

Win2000SP3VersionLieWinXPVersionLieWinXPSP1VersionLieWinXPSP2VersionLieWin2K3RTMVersionLieWin2K3SP1VersionLieVistaRTMVersionLie

Version Lie LayersWin95NT4SP5Win98Win2000Win2000SP2Win2000SP3

WinXPWinXPSP1WinXPSP2WinXPSP2VersionLieWinSrv03WinSrv03SP1VistaRTM

Shims and Layers

Windows

Shim

Application Child Application

Layer

Layers: More Than Version LiesXPSP2 Layer:

DirectXVersionLieElevateCreateProcessEmulateSortingEnableLegacyExceptionHandlingInOLEFailObsoleteShellAPIsGlobalMemoryStatus2GB

HandleBadPtrHardwareAudioMixerLoadLibraryCWDNoGhostRedirectMP3CodecVirtualRegistryWinXPSP2VersionLie

Operating System Versiondemo

How to INSTALL Custom Shim Databases

sdbinst.exe

%windir%\system32\sdbinst.exe

sdbinst Command Line-q Quiet mode-u Uninstall-g Guid (uninstall only)-n Internal name (uninstall only)

Deployment Options

Per enterprise

Per application

Installing Custom Shim Databasesdemo

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 patchingpush ebp ;set up stack framemov ebp,esp ;””

Overwriting Code: Hooking

USER32!MessageBoxA:jmp rel8 ;short jump to hookpush ebp ;we never get heremov 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

MS-DOS Header

NT Headers

Section Headers

Section Images

PE Signature

File Headers

Optional Headers

Data Directories

Export Table

Import Table

Resource Table

Exception Table

...

Original First Thunk

Time Date Stamp

Forwarder Chain

Imported DLL Name

First Thunk

...

IAT Modification: Import Table

0x1034

0x1047

...

GetModuleHandleA

LoadLibrary

...

kernel32.dll

user32.dll

advapi32.dll

...

IAT Modification: Sample CodeRichter & Nasarre, 2008ULONG 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 IDImplement hook for GetDlgItemTextTrick user into installing itYour user-mode API interception can now harvest passwords

API Hookingdemo

Compatibility Administrator

/x switch

SearchNot 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 Toolsdemo

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 Enterprisehttp://go.microsoft.com/fwlink/?LinkId=107072

Custom SDB Deploymentdemo

(More) Shims for User Account Control

Symptom

Taskbar flasher

CorrectShellExecuteHWND

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 Shimsdemo

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 Shimsdemo

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

ParametersNOKEYS – 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 exceptionYes, this should make you nervous…

Parameters...

IgnoreException Parameters 1/2

EXCEPTION1_NAME:EXCEPTION1_LEVEL;EXCEPTION2_NAME:EXCEPTION2_LEVEL;…Exception names can be:

ACCESS_VIOLATION_READACCESS_VIOLATION_WRITEARRAY_BOUNDS_EXCEEDEDBREAKPOINTDATATYPE_MISALIGNMENTFLT_DENORMAL_OPERANDFLT_DIVIDE_BY_ZEROFLT_INEXACT_RESULTFLT_INVALID_OPERATIONFLT_OVERFLOWFLT_STACK_CHECK

FLT_UNDERFLOWILLEGAL_INSTRUCTIONIN_PAGE_ERRORINT_DIVIDE_BY_ZEROINT_OVERFLOWINVALID_DISPOSITIONNONCONTINUABLE_EXCEPTIONPRIV_INSTRUCTIONSINGLE_STEPSTACK_OVERFLOWINVALID_HANDLE

IgnoreException Parameters 2/2

Exception levels can be:0 - Don't ignore the exception1 - Ignore first chance exception2 - Ignore second chance exception3 - Exit process on second chance exception

IgnoreMessageBox

Symptoms

Extraneous message box

Fix descriptionIgnores the message box

ParametersMessageBoxText1,MessageBoxCaption1;MessageBoxText2,MessageBoxCaption2

Empty arguments match anythingSupports * and ? wildcardsEscape these characters: ? * , ; \

Miscellaneous Shimsdemo

Frequently Asked Questions

Managed code?

VB6 code?

msvbvm60.dll

16-bit code?

Top 10 System SDB Shims1. GameUX2. VirtualRegistry3. CorrectFilePaths4. Win95VersionLie5. WinXPSP2VersionLie6. IgnoreAltTab7. ShimViaEAT8. AOLFindBundledInstaller9. ElevateCreateProcess10.OpenDirectoryACL

http://www.appcompatguy.comchris.jackson@microsoft.com

question & answer

www.microsoft.com/teched

Sessions On-Demand & Community

http://microsoft.com/technet

Resources for IT Professionals

http://microsoft.com/msdn

Resources for Developers

www.microsoft.com/learningMicrosoft Certification and Training Resources

www.microsoft.com/learning

Microsoft Certification & Training Resources

Resources

Related Content

Breakout Sessions (session codes and titles)WCL302 – Are You Breaking my Stuff Again? The Windows 7 App Compat StoryWCL304 – Fix Your Broken Applications: The Black Art of ShimsWCL401 – 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 SeriesThe 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.

top related