Extraordinary String Based Attacks PDF

1m ago
3.04 MB
81 Pages

Extraordinary String Based Attacks

About MeSecurity Researcher at Azimuth Security Past presentations Heaps of Doom (/w Chris Valasek) Kernel Attacks Through User-ModeCallbacks Kernel Pool Exploitation on Windows 7Generally interested in operating systeminternals and bug finding Recent focus on embedded platforms

This Talk A rather unusual Windows bug class Affects Windows atoms 3 vulnerabilities patched 2 days ago inMS12-041 Allows a non-privileged user to run codein the context of a privileged process E.g. the Windows login manager (winlogon) No need to run arbitrary code in Ring 0 DEP/ASLR? SMEP? No problem!

Previous Work Atoms briefly mentioned in Windowssandboxing literature Stephen A. Ridley – Escaping the Sandbox Tom Keetch – Practical Sandboxing onWindows Getadmin exploit (1997) Exploited unchecked pointer in NtAddAtom API issue – not specific to atom misuse

OutlineAtoms Vulnerabilities Attack Vectors Exploitation Windows 8 Conclusion

Smashing the Atom

Atoms A Windows data type used to store stringsand integers Referenced using 16-bit valuesStored in a hash table known as an atomtable Generally used to share informationbetween processes Initially designed to support Dynamic DataExchange (DDE) Also used by the operating system

Atom TablesDefined in the local (application) orglobal (system) scope Application defined tables are fullymanaged in user-mode System defined tables are managed bythe kernel Callouts to win32k where necessary Two common system tables Global And User Atom Tables

Local Atom TableDefined per application Table initialization handled transparentlyto applications Exposed through an own set of APIs(kernel32) AddAtom, DeleteAtom, FindAtom, Actual implementation in runtime library(NTDLL)

Global Atom Table Defined per window station win32k!CreateGlobalAtomTableAccessible to any application in thesame window station by default Can also be job specific if global atomsUI restrictions are enabled Exposed through an own set of APIsprefixed “Global” GlobalAddAtom, GlobalDeleteAtom,

Global Atom Table (DDE)Window StationGlobal Atom TableRegisters conversationtopic string atomClient ProcessClientWindowServer ProcessAtomSends message withtopic atomServerWindowUses the atom to lookup the topic string

User Atom Table Defined per session win32k!UserRtlCreateAtomTable Holds data used by the User subsystem Window class names Clipboard format names , Not exposed to user applications directly However, some APIs allow values to beinserted and queried RegisterWindowMessage

Atom Table dAtomNTDLLKERNEL32RtlAddAtomToAtomTableUser tomToAtomTableWindows 7 SP1UserGlobalAtomTableCalloutUserAddAtom

Atom Types Two types of atoms Strings and integers Both types are managed by the sameatom table Defined with separate atom value ranges No type information needed Both types are handled using the sameAPIs

String AtomsRegistered upon passing a string toRtlAddAtomToAtomTable Assigned an atom value in the range0xC001 through 0xFFFF Subsequently used to look up the stringLimits the string size to 255 bytes Reference counted to keep track of use Example: Window class names

Integer Atoms Integer values map directly to the atomvalue Never actually stored in the atom table Defined in the range 1 to 0xBFFF Only stores decimal values up to 49151Only registered for the sake ofconsistency Example: Standard clipboard formats

Atom Table CreationCreated using RtlCreateAtomTable Initialized with an integer representingthe number of hash buckets (default 37) A string atom is inserted into a bucketbased on its string hash Used for efficient lookup of string atoms The atom table itself is defined by theRTL ATOM TABLE structure

Atom Table Structuretypedef struct RTL ATOM TABLE{/*0x000*/ ULONG32Signature;/*0x004*/ struct RTL CRITICAL SECTION CriticalSection;/*0x01C*/ struct RTL HANDLE TABLE RtlHandleTable;/*0x03C*/ ULONG32NumberOfBuckets;/*0x040*/ struct RTL ATOM TABLE ENTRY* Buckets[1];} RTL ATOM TABLE, *PRTL ATOM TABLE;Windows 7 SP1 (x86)

Atom Table EntriesEach string atom is represented by anRTL ATOM TABLE ENTRY structure Defines the atom value and string Reference counted to keep track ofstring (atom) use Incremented whenever an identical string isadded to the atom table Flags to indicate whether an atom hasbeen pinned

Atom Table Entry Structuretypedef struct RTL ATOM TABLE ENTRYFor handling stringhash collisions{/*0x000*/ struct RTL ATOM TABLE ENTRY* HashLink;Used to generate/*0x004*/ UINT16HandleIndex;atom values/*0x006*/ UINT16Atom;/*0x008*/ UINT16ReferenceCount;/*0x00A*/ UINT8Flags;Track atom use/*0x00B*/ UINT8NameLength;/*0x00C*/ WCHAR Name[1];} RTL ATOM TABLE ENTRY, *PRTL ATOM TABLE ENTRY;Windows 7 SP1 (x86)

Atom Pinning If the reference count of an atom overflows,the atom is pinned Indicated by the RTL ATOM PINNED (1) flag A pinned atom is not freed until its atomtable is destroyed E.g. upon destroying a window station orlogging out a user Windows also supports on-demand pinning RtlPinAtomInAtomTable Prevents atoms from being deliberately deleted

Atom Value Assignment Atom tables use a separate handle tablefor string atom value assignment Retrieved using ExCreateHandle Attempts to use a recently freed handleto optimize lookup Otherwise performs exhaustive search Actual atom value is obtained by OR’ingthe handle index with MAXINTATOM Atom ( Handle 2 ) 0xC000

System Atom Table Access System atom tables are generallyavailable to all user processes Designed for sharing information In a sandbox, we want to restrict accessin the less privileged components Prevent leaking of (sensitive) information Prevent deletion of atoms used by other(e.g. more privileged) applications

Global Atom Table Access Access can be restricted using job objectUI restrictions JOB OBJECT UILIMIT GLOBALATOMS When set, Windows creates a separateatom table and associates it with the jobobject The process of choosing the correct atom table ishandled in win32k!UserGlobalAtomTableCallout Checks the global atoms UI restriction flag bycalling nt!PsGetJobUIRestrictionsClass

User Atom Table Access In Windows 7, there’s no practical isolationof the user atom table More on Windows 8 later Accessible to any process running in thesame session E.g. using APIs which (indirectly) operate on it A process can query the values of any useratom using GetClipboardFormatName No distinction made between clipboard formatstrings and other user atom strings

Enumerating User Atoms

Smashing the Atom

Atom Handling Vulnerabilities 3 separate vulnerabilities in string atomhandling Register Class Name Handling Vulnerability Set Class Name Handling Vulnerability Clipboard Format Name Handling Vulnerability Addressed in MS12-041 in/ms12-041 Allows an attacker to take control oversystem managed string atoms We discuss the implications of this later

Window Class An application describes a window’sattributes using a window class Defined by the WNDCLASS(EX) structure lpszClassName sets the class name Can either be a string or an atom Win32k differs between the twointernally by looking at the high 16-bits If only lower 16-bits are set, it is handled asan atom

Class Name String Atom If a string is provided, win32k convertsthe string into an atom Handled by win32k!UserAddAtom Atom value stored in the win32k managedclass data structure (win32k!tagCLS) If an atom is provided, the functionsimply copies its value to the class datastructure No atom validation or retaining of reference

CVE-2012-1864No referenceacquired whenproviding an atomAtom storedWindows 7 SP1 (x86)

CVE-2012-1864 When a class is unregistered,win32k!DestroyClass releases theatom reference Even when no reference was acquiredpreviously An attacker could register a class usingan atom of a more privileged application Could free and reregister the atom with adifferent string

Version Prefixed Class Name Since Windows XP, class objects definetwo class name atoms atomClassName atomNVClassName The former defines the base class name Fixed once registered The latter prefixes the name with versionspecific information 6.0.7600.16661!ScrollBar Allows classes of the same name, but ofdifferent versions to be styled differently

Updating Class Name Atom An application can update the versionprefixed name of a registered class SetClassLongPtr using the GCW ATOM(0xFFFFFFE0) index Internally, win32k looks up the index(adjusted) in an offset table Finds the offset to the atom value in the classobject structure In setting or replacing the version prefixedclass name atom, no validation orreferencing is performed

CVE-2012-1865Offset to versionprefixed classname in the classdata structureReplaces value withoutvalidation and acquiringor releasing referencesWindows 7 SP1 (x86)

Clipboard FormatsWindows uses atoms to uniquely identifyeach clipboard format type Applications can also register their ownclipboard formats user32!RegisterClipboardFormat Registers the atom for the user providedformat name string in the user atom table user32!SetClipboardData Sets clipboard data of the particular typeusing the provided atom value

InternalSetClipboardDataHandles SetClipboardData requests Calls win32k!UserGetAtomName andwin32k!UserAddAtom if the providedatom is present Properly verifies and references the string atom If the atom is not present, the function stillsaves the data using the (invalid) atom Considers the atom to be a default type (integer) Fails to check if the atom is really an integeratom (i.e. below 0xC000)

CVE-2012-1866References atom if string ispresent in the user atomtableConsiders the atom to bevalid, regardless of typeWindows 7 SP1 (x86)

Smashing the Atom

Enumerating Attack Vectors Look at how (string) atoms are used bythe system Registered window messages Clipboard format names Window class names Cursor module paths Hook module paths Evaluate how user input may affectstring atom operations

Registered Window Messages An application can register new windowmessages RegisterWindowMessage Stored as a string atom in the user atomtable Typically used when messagingbetween two cooperating applications If both register the same string, they receivethe same message value

Registered Window MessagesWindows does not pin the string atomfor the registered message An attacker may potentially free windowmessage atoms registered byapplications Can cause desynchronization between twoapplications sending private messages E.g. by freeing and re-registering messagesin reverse-order

Clipboard Format Names Applications can register their ownclipboard formats RegisterClipboardFormat Identified as string atoms in the user atom tableThese atoms are not pinned, hence can befreed by an attacker However, clipboard data handling betweenprivilege levels is subject to UIPI List of exempt formats only contain standard(integer) clipboard formats

Window Class Names Names of window classes are stored inthe user atom table Atom used by the class object to look up theclass name stringWindows does not pin the string atomsof non-system class objects An attacker could free the atom used bythe system to identify class objects Re-registering the string could causelookups to resolve to the wrong object

Cursor Module Names Windows stores the module path of aloaded cursor as a string atom atomModName field of the cursor object Used to determine if a cursor hasalready been loaded win32k! FindExistingCursorIcon Windows does not pin this atom An attacker could potentially free its value Minimal security impact

Hook Module Paths Windows allows external modules to beused when setting windows hooks SetWindowsHookEx SetWinEventHook RegisterUserApiHook The module path is stored as a stringatom in the user atom table Atom value stored at an index in the globalaatomSysLoaded array

Hook Module String AtomsKernel ModeaatomSysLoadedAtom User Atom TableHook ObjectEvent Hook dUserApiHookaatomSysLoadedarray indexRegisterUserApiHook

Hook Module Loading Windows looks up the string atom uponloading an external module hook Invokes a user-mode callback and passesthe string to LoadLibraryAn attacker who frees any such atomcould possibly inject arbitrary modules Hooks play an integral part in Windowsin providing application theming Relies on the user api hook

User Api Hook Special hooking mechanism introducedto support Windows themes RegisterUserApiHook Can only be registered by privilegedprocesses Requires the TCB privilege Caller must be running as SYSTEM Allows Windows to load a theme clientmodule into every GUI application

Smashing the Atom

Theme Subsystem Introduced in Windows XP Extended in Vista to support desktopcomposition (DWM)Hooks into USER32 in order tocustomize non-client region metrics Loads an instance of uxtheme.dll intoevery Windows application Uses the user api hook registered bywinlogon

Theme Server Manages the theme subsystem Runs in a service host process Registers //ThemeApiPortKeeps track of the Windows themeconfiguration for all running sessions Each GUI (themed) process keeps anactive connection with the theme server Used to retrieve updated themeconfigurations

Theme Api Port Connectionskd !alpc /lpc 8701a4588701a458('ThemeApiPort') 1, 10 connections85a17ae0 0 - 85e53038 0 853c3790('winlogon.exe')872802f8 0 - 863df540 0 853d8540('winlogon.exe')85289f00 0 - 853e3038 0 853c3790('winlogon.exe')86464d18 0 - 8538a928 0 853d8540('winlogon.exe')85be9038 0 - 8533c2e0 0 853ea5c0('mmc.exe')87257980 0 - 86fd6458 0 85e63030('explorer.exe')871fd038 0 - 86f3db98 0 85dfc8a0('dwm.exe')85a53368 0 - 8534f298 0 852eb030('explorer.exe')871c76a0 0 - 8659ef00 0 852aa030('calc.exe')872bc8f8 0 - 85e6b370 0 853a4388('procexp.exe')

Theme Session Initialization On each new session, Winlogon callsUXINIT to interface with the Theme Server Acts as the theme server client Sends a ThemeApiConnectionRequest packetto //ThemeApiPort over ALPC Once connected, Winlogon registers a setof callbacks CThemeServerClient::SessionCreate() Allows the theme server to load themes andinstall and remove theme hooks

Theme Hooks Installation For installing hooks, the theme serverservice injects a thread into Winlogon UXINIT!Remote ThemeHooksInstall Winlogon (from UXINIT) subsequentlycalls RegisterUserApiHook Takes a structure defining the library to loadand the function (export) to execute Library:%SystemRoot%/System32/uxtheme.dll Function: ThemeInitApiHook

Ux Theme ArchitectureRegisters theUser Api

used when setting windows hooks ... Relies on the user api hook . User Api Hook Special hooking mechanism introduced to support Windows themes RegisterUserApiHook Can only be registered by privileged processes Requires the TCB privilege Caller must be running as SYSTEM Allows Windows to load a theme client module into every GUI application . Smashing the Atom . Theme Subsystem Introduced in ...