Skip to content
Race condition Write-up Advanced

Getting SYSTEM on Windows in style

A time-of-check to time-of-use flaw in Windows theme loading allowed a local attacker to replace a signed visual styles verification DLL with a malicious one between signature check and load, leading to code execution as SYSTEM in winlogon.exe. The attacker could also use a remote SMB share to control which file version is served on each read, avoiding the race.

Sector 7 Follow

Published on sector7.computest.nl

Microsoft has published a patch for CVE-2023-38146 on patch Tuesday of September 2023. The advisory for this vulnerability mentions that the impact is remote code execution, which was demonstrated by @carrotc4k3 - the researcher who first reported the vulnerability to Microsoft in May of 2023.

Sector 7 (@sector7_nl), on sector7.computest.nl

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 10 min read.

Microsoft published a patch for CVE-2023-38146 on the September 2023 patch Tuesday. The advisory describes the impact as remote code execution, demonstrated by @carrot_c4k3, who first reported the vulnerability to Microsoft in May 2023. Her ThemeBleed writeup and proof of concept show how an attacker might get code execution by luring a victim into opening a booby-trapped .themepack file.

We had also identified and reported the same vulnerability in August 2023, but our proof of concept took a slightly different path with a distinct outcome. It turns out the vulnerability can be exploited for initial access as well as privilege escalation. This writeup covers the code path we identified and how we exploited it for privilege escalation.

Context

Windows users can modify their desktop environment through theme files, simple INI-style config files with the .theme extension. They consist of key-value entries for text colours, scrollbar colours, desktop icons and the like. Next to simple graphical elements, a Windows theme must contain an entry denoting the theme's associated "Visual Styles". This entry can specify colour and sizing information for UI elements and, optionally, a Path entry pointing to an .msstyles file. These are Portable Executable (PE) files that should only contain resources controlling the styling of "deeper" elements of the operating system's UI, such as windows and buttons.

Once a user chooses a theme, if the [VisualStyles]\Path entry exists and points to a valid .msstyles file, it is stored in their registry hive at HKCU\Software\Microsoft\Windows\CurrentVersion\ThemeManager\DllName. Usually it is set to the visual styles file for the Windows default theme, Aero.msstyles.

Any user may use any theme or modify one freely, but they may not use visual styles files that are not provided by Microsoft, because .msstyles PEs are signed and validated at some point during processing.

Setup

While investigating signature verification routines in Windows 11, we noticed an oddity in how theme loading code handled .msstyles files. That oddity was our path to CVE-2023-38146, which seems to stem from code changes to Windows theme loading introduced in Windows 11.

A user's theme should be applied to their desktop session when they log in or whenever it needs to be re-applied. This is performed by Winlogon as part of the user's desktop creation and in response to a number of events that may occur in a user's session.

On a vulnerable build of Windows 11, Winlogon (re-)loads the currently logged-in user's theme as follows:

  1. Some event that requires (re-)loading the current user's theme occurs (e.g. the user logs on), causing winlogon.exe to invoke a series of functions eventually calling UXInit!CThemeServicesInit::LoadCurrentTheme.
  2. UXInit!CThemeServicesInit::LoadCurrentTheme reads the registry key HKCU\Software\Microsoft\Windows\CurrentVersion\ThemeManager\DllName for the user to be logged in, to obtain the path to the theme's visual style file (the .msstyles file).
  3. Eventually, UXInit!LoadThemeLibrary is called to load the theme's .msstyles file using LoadLibraryEx with the LOAD_LIBRARY_AS_DATAFILE flag, to ensure that no code, if any, is executed. Afterwards, the loaded .msstyles module's PACKTHEM_VERSION resource section is read. This is expected to contain a version number represented as a 2-byte integer.
  4. If the value equals 999 (0x03e7), the function UXInit!ReviseVersionIfNecessary checks whether the .msstyles path followed by _vrf.dll exists. For example, if the .msstyles file is at C:\a.msstyles, the function checks for the existence of C:\a.msstyles_vrf.dll.
  5. If this path exists, its signature is verified for validity.
  6. If that signature verification passes, the _vrf.dll file is loaded into winlogon.exe and the function <loaded_vrf_dll>!VerifyThemeVersion is called.

All of the steps above are executed before any validation of the embedded .msstyle file signature.

Finding it

In the process above, steps (5) and (6) must be performed as one atomic operation from the filesystem's point of view, with no modifications allowed to the _vrf.dll file in between. Otherwise it is possible to swap the _vrf.dll file after step (5) but before step (6), which is a Time-of-check to time-of-use (TOCTOU) vulnerability.

That is exactly the vulnerability, as can be seen in the decompilation of UXInit!ReviseVersionIfNecessary (irrelevant parts omitted for brevity):

C
// ...snip...
if ( !PathFileExistsW(vrf_file_path) ) // [1]
	return 0x80004005;
*&themeSig_object = &CThemeSignature::`vftable`;
*(&themeSig_object + 1) = 0i64;
v16[0] = 0ui64;
CThemeSignature::_Init(&themeSig_object, v7, v8);
err = CThemeSignature::Verify(&themeSig_object, vrf_file_path); // [2]
CThemeSignature::~CThemeSignature(&themeSig_object);
if ( (err & 0x80000000) != 0 )
{
	// ...snip...
	// Do further checks using NtGetCachedSigningLevel
	// ...snip...
}
vrf_library = LoadLibraryW(vrf_file_path); // [3]
v11 = vrf_library;
if ( !vrf_library )
	return 0x80004005;
VerifyThemeVersion = GetProcAddress(vrf_library, "VerifyThemeVersion");
memset(v16, 0, 20);
themeSig_object = xmmword_180028E88;
err = VerifyThemeVersion();
// ...snip...

The function first checks that the _vrf.dll file exists [1], then verifies its signature [2]. Next, LoadLibraryW opens the file again [3]. Because no locking is applied to the file between [2] and [3], it may be modified between these steps. By first placing a visual styles file that is properly signed and setting the current theme to use that path, then replacing it at just the right moment with an arbitrary DLL, it is possible to load that DLL into winlogon.exe, executing its code as SYSTEM.

Exploitation

To exploit the TOCTOU vulnerability, one would have to race against the vulnerable code path as it is repeatedly invoked while constantly switching between a properly signed visual styles file and a malicious one. That means a method to trigger the vulnerable code path in winlogon.exe repeatedly and quickly is necessary to improve the chances of a successful race in a short time window. Alternatively, a way to increase the race window duration or skip it altogether would be sufficient, as long as the vulnerable code path can be triggered at least once.

Regardless of the specifics, the exploit outline is:

  1. Prepare a .msstyles file with a PACKTHEM_VERSION of 999 at some path $x.
  2. Change the registry key HKCU\Software\Microsoft\Windows\CurrentVersion\ThemeManager\DllName to point to $x.
  3. Put a validly signed .msstyles file at $x_vrf.dll.
  4. Trigger the theme loading code path.
  5. Replace the file $x_vrf.dll with our malicious version, hopefully between the signature verification check and the LoadLibraryW call.
  6. If all goes well, our payload is now executing inside winlogon.exe, which is running as NT AUTHORITY\SYSTEM.
  7. Otherwise, repeat steps (3) to (5).

Avoiding the race

While exploiting race conditions may be fun, it is even better if there is no need to race at all. Since an attacker has full control of the theme's visual styles DLL path, there is no need to race. All they have to do is specify a UNC path pointing to a file on a remote SMB share under their control. That allows them to control exactly which version of the _vrf.dll is returned for which file read operation.

The only requirement is that the share at the other end is set up to host a properly signed .msstyles file and returns a validly signed _vrf.dll file on the first read and a malicious _vrf.dll file the second time.

Triggering the vulnerable code path

Winlogon is responsible for creating the user's desktop upon logon, so logging out and back in again should trigger the vulnerable code path. Indeed, that causes a theme reload and, combined with a visual styles file path pointing to a remote SMB share, guarantees a successful exploit in one shot. However, it seemed a bit complicated, so we set out to find another way.

We found that changing the UI's scaling to a value above 100% triggers a theme reload at least once, though it was a bit flaky in our tests. Since racing is no longer needed, that does not matter, and a single theme reload is sufficient to exploit the vulnerability. On the upside, changing the UI's scaling can easily be done with some PowerShell:

PowerShell
function Set-Scaling {
    # Posted by IanXue-MSFT on
    # https://learn.microsoft.com/en-us/answers/questions/197944/batch-file-or-tool-like-powertoy-to-change-the-res.html
    # $scaling = 0 : 100% (default)
    # $scaling = 1 : 125%
    # $scaling = 2 : 150%
    # $scaling = 3 : 175%
    param($scaling)
    $source = @'
    [DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]
    public static extern bool SystemParametersInfo(
                      uint uiAction,
                      uint uiParam,
                      uint pvParam,
                      uint fWinIni);
'@
    $apicall = Add-Type -MemberDefinition $source -Name WinAPICall -Namespace SystemParamInfo -PassThru
    $apicall::SystemParametersInfo(0x009F, $scaling, $null, 1) | Out-Null
}
# .. Set up exploit
# Trigger the vulnerable code path
Set-Scaling -scaling 2

# Reset the scaling
Set-Scaling -scaling 0

# .. Cleanup

The function calls SystemParametersInfo with action 0x009F and the requested scaling value, which triggers a theme reload; in the authors' tests this was a bit flaky.

Putting it all together

Modifying the exploit template from earlier, a reliable exploit looks like this:

  1. Prepare a .msstyles file with a PACKTHEM_VERSION of 999 and store it on an attacker-controlled SMB share at \\<share host>\path\to\file.msstyles
  2. Change the registry key HKCU\Software\Microsoft\Windows\CurrentVersion\ThemeManager\DllName to point to \\<share host>\path\to\file.msstyles.
  3. Put a validly signed .msstyles file at \\<share host>\path\to\file.msstyles_vrf.dll
  4. Trigger a theme re-load by setting the UI scaling to some value > 100%
  5. Wait until the file at \\<share host>\path\to\file.msstyles_vrf.dll is read once
  6. Replace the file \\<share host>\path\to\file.msstyles_vrf.dll with a malicious version.
  7. When the file is requested for the second time by LoadLibraryW, it is presented instead with the malicious version, thereby achieving code execution inside winlogon.exe

For our exploit, we set up a remote host running a samba share and a scapy-based Python script to perform the file replacement step. The script detects when the first read operation has been sent over the wire, after which it replaces the validly signed file.msstyles_vrf.dll on disk with our malicious DLL.

Demo

The video below shows the exploit in action. We start with a standard authenticated user, lowuser, then run the exploit script. It sets the user's visual styles DLL key described above to \\[redacted]\public\asdf.msstyles. Afterwards, it changes the UI's scaling to 150%, causing winlogon.exe to reload the user's theme. Once the .msstyles file is loaded and its PACKTHEM_VERISON resource is checked, winlogon.exe verifies the signature of \\[redacted]\public\asdf.msstyles_vrf.dll. This signature verification step passes since the first file presented by the SMB share is correctly signed. Afterwards, winlogon.exe loads the DLL one more time, at which point our Python script has replaced it with an unsigned malicious DLL. The result can be seen as the malicious DLL spawns an interactive command prompt as NT AUTHORITY\SYSTEM.

From the original on sector7.computest.nl

Root cause

The mistake is the gap between the signature check and the load in UXInit!ReviseVersionIfNecessary. The file is checked with CThemeSignature::Verify and then opened again with LoadLibraryW, with no locking in between, so the file's contents can change between the two operations. The PACKTHEM_VERSION value of 999 is what routes processing into this _vrf.dll path in the first place, and all of it happens before the embedded .msstyle signature is validated. Because the path comes from the user's own registry key, the attacker also controls where the file is read from, which is what makes the SMB share trick possible: the same path can return different bytes on the first and second read.

Impact

Successful exploitation loads an arbitrary DLL into winlogon.exe, which runs as NT AUTHORITY\SYSTEM, so the attacker's code executes with SYSTEM privileges. The report describes the vulnerability as usable both for initial access and for privilege escalation.

Fix

Microsoft's patch updated the code for LoadThemeLibrary in both uxtheme.dll and UXInit.dll to remove the PACKTHEM_VERSION check and the ReviseVersionIfNecessary function entirely. The initially vulnerable code path therefore no longer loads any DLLs besides the LOAD_LIBRARY_AS_DATAFILE loading of the .msstyles PE.

The fix did not address how visual styles signatures are validated. That code is still vulnerable to a TOCTOU vulnerability, so it may be possible for attackers to exploit any processing bugs that occur after signature validation.

Detection

Since the fix removes the visual style version verification functionality entirely, it seems safe to assume Microsoft deemed it unnecessary. Any attempt to load a DLL whose path ends in .msstyles_vrf.dll is therefore likely a CVE-2023-38146 exploit attempt.

  • Point HKCU\Software\Microsoft\Windows\CurrentVersion\ThemeManager\DllName at a UNC path on a share you control and watch the SMB reads. A positive result is two reads of the same _vrf.dll path, where the second read is served different bytes than the first.
  • Trigger a theme reload by setting UI scaling above 100% with SystemParametersInfo action 0x009F. A positive result is a theme reload that reaches the _vrf.dll verification path without a logoff.
  • Look for other check-then-use pairs around signed resource loading, where a signature is verified and the file is then opened again by path. A positive result is a window in which the file can be swapped between the two operations.
  • Test whether processing that happens after visual styles signature validation can be reached with a modified file. A positive result is code or resource handling that runs after the check but still acts on attacker-controlled content.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 16 min read.

What happened, in plain words

In September 2023, Microsoft released a security fix for a flaw tracked as CVE-2023-38146. A CVE is simply a public catalogue number for a known security bug, so anyone can look it up. Microsoft's advisory says the impact is remote code execution, which means an attacker can get their own program to run on someone else's computer. That demonstration was made by @carrot_c4k3, who first told Microsoft about the bug in May 2023. Her ThemeBleed writeup and proof of concept show how an attacker might get code execution by luring a victim into opening a booby-trapped .themepack file. A proof of concept is a small demonstration program that proves a bug is real without being a full attack tool.

We had also found and reported the same vulnerability in August 2023. Our proof of concept took a slightly different path and reached a different outcome. It turns out the vulnerability can be used both for initial access (getting a first foothold on a machine) and for privilege escalation (turning a limited account into a more powerful one). This writeup covers the code path we identified and how we used it for privilege escalation.

Context

Windows lets people change how their desktop looks through theme files. These are simple configuration files with the .theme extension, written in the INI style: plain text made of sections, each holding key=value lines. They hold entries for text colours, scrollbar colours, desktop icons and similar settings.

Besides the simple graphical elements, a Windows theme must contain an entry naming the theme's associated "Visual Styles". That entry can carry colour and sizing information for interface elements and, optionally, a Path entry pointing to an .msstyles file. An .msstyles file is a Portable Executable (PE) file. A PE file is the standard container format Windows uses for programs and libraries; it is the same kind of file as an .exe or a .dll. In theory an .msstyles file should only contain resources, meaning data such as images and numbers, that control the styling of "deeper" parts of the operating system's interface, such as windows and buttons.

Once a user picks a theme, if the [VisualStyles]\Path entry exists and points to a valid .msstyles file, that path is stored in the user's registry hive at HKCU\Software\Microsoft\Windows\CurrentVersion\ThemeManager\DllName. The registry is Windows' central settings database, organised as a tree of keys and values. HKCU is short for HKEY_CURRENT_USER, the branch that belongs to the logged-in user, so each user has their own copy. Usually this value points to the visual styles file of the Windows default theme, Aero.msstyles.

Any user may use any theme, or modify one freely, but they may not use visual styles files that Microsoft did not provide. That is because .msstyles PE files are signed and validated at some point during processing. A digital signature here is a cryptographic stamp that lets Windows check who produced a file and whether it has been altered since. Validation is the act of checking that stamp.

Setup

While investigating how Windows 11 verifies signatures, we noticed something odd in the way the theme loading code handled .msstyles files. That oddity led us to CVE-2023-38146, which appears to come from code changes to Windows theme loading that were introduced in Windows 11.

A user's theme should be applied to their desktop session when they log in, or whenever it needs to be applied again. This is done by Winlogon, the Windows component that handles logging users on and creating their desktop. It does this as part of creating the user's desktop and in response to a number of events that can happen during a session.

On a vulnerable build of Windows 11, Winlogon loads (or reloads) the currently logged-in user's theme like this:

  1. Some event that requires loading or reloading the current user's theme happens (for example, the user logs on). This makes winlogon.exe call a chain of functions that eventually reaches UXInit!CThemeServicesInit::LoadCurrentTheme. The module!function notation just means "this function, inside this module".
  2. UXInit!CThemeServicesInit::LoadCurrentTheme reads the registry key HKCU\Software\Microsoft\Windows\CurrentVersion\ThemeManager\DllName for the user who is logging in, to get the path to the theme's visual style file (the .msstyles file).
  3. Eventually UXInit!LoadThemeLibrary is called to load the theme's .msstyles file, using a Windows function called LoadLibraryEx with the LOAD_LIBRARY_AS_DATAFILE flag. That flag tells Windows to treat the file purely as data, so that no code inside it, if there is any, gets executed. Afterwards the loaded .msstyles module's PACKTHEM_VERSION resource section is read. A resource section is a named block of data stored inside a PE file. This one is expected to hold a version number stored as a 2-byte integer.
  4. If the value equals 999 (0x03e7), the function UXInit!ReviseVersionIfNecessary checks whether the .msstyles path followed by _vrf.dll exists. For example, if the .msstyles file is at C:\a.msstyles, the function checks whether C:\a.msstyles_vrf.dll exists. The _vrf suffix is simply appended to the file name.
  5. If that path exists, its signature is checked for validity.
  6. If the signature check passes, the _vrf.dll file is loaded into winlogon.exe and the function <loaded_vrf_dll>!VerifyThemeVersion is called. Loading a DLL into a running program means the program gains the code that DLL contains and can run it.

All of the steps above run before any validation of the signature of the embedded .msstyle file itself.

Finding it

In the process above, steps (5) and (6) must happen as one indivisible operation from the filesystem's point of view, with no changes allowed to the _vrf.dll file in between. Otherwise it is possible to swap the _vrf.dll file after step (5) but before step (6). That is a Time-of-check to time-of-use (TOCTOU) vulnerability. The everyday comparison: a bouncer checks your ID at the door, then you walk to the bar, and in that gap someone swaps your ID for a different one. The check was done on one thing, the use happened on another.

That is exactly the vulnerability, as can be seen in the decompilation of UXInit!ReviseVersionIfNecessary (irrelevant parts omitted for brevity). Decompilation means turning compiled machine code back into something resembling source code so a human can read it:

C
// ...snip...
if ( !PathFileExistsW(vrf_file_path) ) // [1]
	return 0x80004005;
*&themeSig_object = &CThemeSignature::`vftable`;
*(&themeSig_object + 1) = 0i64;
v16[0] = 0ui64;
CThemeSignature::_Init(&themeSig_object, v7, v8);
err = CThemeSignature::Verify(&themeSig_object, vrf_file_path); // [2]
CThemeSignature::~CThemeSignature(&themeSig_object);
if ( (err & 0x80000000) != 0 )
{
	// ...snip...
	// Do further checks using NtGetCachedSigningLevel
	// ...snip...
}
vrf_library = LoadLibraryW(vrf_file_path); // [3]
v11 = vrf_library;
if ( !vrf_library )
	return 0x80004005;
VerifyThemeVersion = GetProcAddress(vrf_library, "VerifyThemeVersion");
memset(v16, 0, 20);
themeSig_object = xmmword_180028E88;
err = VerifyThemeVersion();
// ...snip...

Line by line, in plain words:

  • if ( !PathFileExistsW(vrf_file_path) ) // [1] asks the filesystem whether the _vrf.dll file exists. The W at the end of the function name means it takes wide (Unicode) strings, which is how Windows stores text internally.
  • return 0x80004005; is what happens if the file is missing: the function stops and returns an error code. 0x80004005 is a generic Windows "unspecified failure" code.
  • The next few lines set up a CThemeSignature object, a small structure the program uses to hold signature-checking state. _Init prepares it.
  • err = CThemeSignature::Verify(&themeSig_object, vrf_file_path); // [2] is the check itself: it verifies the signature of the file at that path and stores the result in err.
  • The if ( (err & 0x80000000) != 0 ) block runs when the check failed. Inside it, further checks are made using NtGetCachedSigningLevel, a Windows function that looks up a file's signing information from a system cache.
  • vrf_library = LoadLibraryW(vrf_file_path); // [3] opens the file again, this time to load it as a library into the current process.
  • if ( !vrf_library ) return 0x80004005; stops with an error if the load failed.
  • VerifyThemeVersion = GetProcAddress(vrf_library, "VerifyThemeVersion"); looks up a function named VerifyThemeVersion inside the freshly loaded library, so it can be called.
  • The remaining lines call that function and store its result in err.

The function first checks that the _vrf.dll file exists [1], then verifies its signature [2]. Next, LoadLibraryW opens the file again [3]. Because no locking is applied to the file between [2] and [3], it can be modified between those steps. So: place a visual styles file that is properly signed, set the current theme to use that path, then replace the file at just the right moment with an arbitrary DLL. That DLL then gets loaded into winlogon.exe, and its code runs as SYSTEM. SYSTEM is the most powerful built-in Windows account, the one the operating system itself uses.

Exploitation

To exploit the TOCTOU vulnerability, you would have to race against the vulnerable code path: trigger it over and over while constantly switching between a properly signed visual styles file and a malicious one. That means you need a way to trigger the vulnerable code path in winlogon.exe repeatedly and quickly, to improve the chances of winning the race in a short time window. Alternatively, a way to make the race window longer, or to skip the race altogether, would be enough, as long as the vulnerable code path can be triggered at least once.

Whatever the specifics, the outline of the exploit is:

  1. Prepare a .msstyles file with a PACKTHEM_VERSION of 999 at some path $x.
  2. Change the registry key HKCU\Software\Microsoft\Windows\CurrentVersion\ThemeManager\DllName to point to $x.
  3. Put a validly signed .msstyles file at $x_vrf.dll.
  4. Trigger the theme loading code path.
  5. Replace the file $x_vrf.dll with our malicious version, hopefully between the signature check and the LoadLibraryW call.
  6. If all goes well, our payload is now running inside winlogon.exe, which runs as NT AUTHORITY\SYSTEM.
  7. Otherwise, repeat steps (3) to (5).

Avoiding the race

Exploiting race conditions may be fun, but it is even better if there is no need to race at all. Since the attacker has full control of the theme's visual styles DLL path, there is no need to race. All they have to do is specify a UNC path pointing to a file on a remote SMB share under their control. A UNC path is the Windows way of writing a location on the network, starting with two backslashes, like \\server\share. SMB is the file-sharing protocol Windows uses to read files from another machine. Because the attacker runs the server on the other end, they can control exactly which version of the _vrf.dll is returned for which file read operation.

The only requirement is that the share at the other end is set up to host a properly signed .msstyles file, and to return a validly signed _vrf.dll file on the first read and a malicious _vrf.dll file on the second read.

Triggering the vulnerable code path

Winlogon is responsible for creating the user's desktop when they log on, so logging out and back in again should trigger the vulnerable code path. Indeed, that causes a theme reload and, combined with a visual styles file path pointing to a remote SMB share, guarantees a successful exploit in one shot. However, that seemed a bit complicated, so we looked for another way.

We found that changing the interface scaling to a value above 100% triggers a theme reload at least once, though it was a bit flaky in our tests. Since racing is no longer needed, that does not matter, and a single theme reload is enough to exploit the vulnerability. On the plus side, changing the interface scaling is easy to do with some PowerShell. PowerShell is Windows' built-in scripting language and command shell:

PowerShell
function Set-Scaling {
    # Posted by IanXue-MSFT on
    # https://learn.microsoft.com/en-us/answers/questions/197944/batch-file-or-tool-like-powertoy-to-change-the-res.html
    # $scaling = 0 : 100% (default)
    # $scaling = 1 : 125%
    # $scaling = 2 : 150%
    # $scaling = 3 : 175%
    param($scaling)
    $source = @'
    [DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]
    public static extern bool SystemParametersInfo(
                      uint uiAction,
                      uint uiParam,
                      uint pvParam,
                      uint fWinIni);
'@
    $apicall = Add-Type -MemberDefinition $source -Name WinAPICall -Namespace SystemParamInfo -PassThru
    $apicall::SystemParametersInfo(0x009F, $scaling, $null, 1) | Out-Null
}
# .. Set up exploit
# Trigger the vulnerable code path
Set-Scaling -scaling 2

# Reset the scaling
Set-Scaling -scaling 0

# .. Cleanup

Line by line, in plain words:

  • function Set-Scaling { starts the definition of a reusable block of PowerShell code named Set-Scaling.
  • The # lines are comments. They credit the original author of the snippet and list the scaling values: 0 is 100% (the default), 1 is 125%, 2 is 150%, 3 is 175%.
  • param($scaling) declares that the function takes one input, the desired scaling value.
  • $source = @' ... '@ stores a block of text in a variable. The text is C# code, and the @' and '@ markers delimit it as a literal here-string, meaning nothing inside is interpreted by PowerShell.
  • Inside that text, [DllImport("user32.dll", EntryPoint = "SystemParametersInfo")] tells .NET (the runtime PowerShell is built on) that we want to call a function named SystemParametersInfo that lives in user32.dll, a core Windows library. An API is simply a function that one program offers so other programs can call it; here, Windows is offering SystemParametersInfo to us.
  • public static extern bool SystemParametersInfo( followed by the parameter list declares the function's signature: its name, the types of its four inputs (uint means an unsigned integer) and its return type (bool, true or false).
  • $apicall = Add-Type -MemberDefinition $source -Name WinAPICall -Namespace SystemParamInfo -PassThru compiles that C# text on the fly and gives back a handle to the resulting type, stored in $apicall.
  • $apicall::SystemParametersInfo(0x009F, $scaling, $null, 1) | Out-Null actually calls the function. 0x009F is the action code that means "set the interface scaling"; $scaling is the value requested; $null means no extra data is passed; 1 tells Windows to apply the change. | Out-Null throws away the return value so it is not printed.
  • Set-Scaling -scaling 2 calls the function with 150%, which triggers the vulnerable code path.
  • Set-Scaling -scaling 0 puts the scaling back to 100%.

The function calls SystemParametersInfo with action 0x009F and the requested scaling value, which triggers a theme reload; in the authors' tests this was a bit flaky.

Putting it all together

Modifying the exploit template from earlier, a reliable exploit looks like this:

  1. Prepare a .msstyles file with a PACKTHEM_VERSION of 999 and store it on an attacker-controlled SMB share at \\<share host>\path\to\file.msstyles
  2. Change the registry key HKCU\Software\Microsoft\Windows\CurrentVersion\ThemeManager\DllName to point to \\<share host>\path\to\file.msstyles.
  3. Put a validly signed .msstyles file at \\<share host>\path\to\file.msstyles_vrf.dll
  4. Trigger a theme reload by setting the interface scaling to some value above 100%
  5. Wait until the file at \\<share host>\path\to\file.msstyles_vrf.dll has been read once
  6. Replace the file \\<share host>\path\to\file.msstyles_vrf.dll with a malicious version.
  7. When the file is requested for the second time by LoadLibraryW, it is served the malicious version instead, which achieves code execution inside winlogon.exe

For our exploit, we set up a remote host running a samba share and a scapy-based Python script to do the file replacement step. Samba is software that lets a non-Windows machine act as an SMB file server. Scapy is a Python library for crafting and inspecting network packets. The script notices when the first read operation has been sent over the wire, and after that it replaces the validly signed file.msstyles_vrf.dll on disk with our malicious DLL.

Demo

The video below shows the exploit in action. We start with a standard authenticated user, lowuser, then run the exploit script. It sets the user's visual styles DLL key described above to \\[redacted]\public\asdf.msstyles. Afterwards it changes the interface scaling to 150%, which makes winlogon.exe reload the user's theme. Once the .msstyles file is loaded and its PACKTHEM_VERISON resource is checked, winlogon.exe verifies the signature of \\[redacted]\public\asdf.msstyles_vrf.dll. This signature check passes, because the first file presented by the SMB share is correctly signed. Afterwards winlogon.exe loads the DLL one more time, at which point our Python script has replaced it with an unsigned malicious DLL. The result can be seen as the malicious DLL spawns an interactive command prompt as NT AUTHORITY\SYSTEM.

From the original on sector7.computest.nl

Root cause

The mistake is the gap between the signature check and the load in UXInit!ReviseVersionIfNecessary. The file is checked with CThemeSignature::Verify and then opened again with LoadLibraryW, with no locking in between, so the file's contents can change between the two operations. The PACKTHEM_VERSION value of 999 is what routes processing into this _vrf.dll path in the first place, and all of it happens before the embedded .msstyle signature is validated. Because the path comes from the user's own registry key, the attacker also controls where the file is read from, which is what makes the SMB share trick possible: the same path can return different bytes on the first and second read.

Impact

Successful exploitation loads an arbitrary DLL into winlogon.exe, which runs as NT AUTHORITY\SYSTEM, so the attacker's code runs with SYSTEM privileges. The report describes the vulnerability as usable both for initial access and for privilege escalation.

Fix

Microsoft's patch updated the code for LoadThemeLibrary in both uxtheme.dll and UXInit.dll to remove the PACKTHEM_VERSION check and the ReviseVersionIfNecessary function entirely. The originally vulnerable code path therefore no longer loads any DLLs besides the LOAD_LIBRARY_AS_DATAFILE loading of the .msstyles PE.

The fix did not address how visual styles signatures are validated. That code is still vulnerable to a TOCTOU vulnerability, so it may be possible for attackers to exploit any processing bugs that occur after signature validation.

Detection

Since the fix removes the visual style version verification functionality entirely, it seems safe to assume Microsoft deemed it unnecessary. Any attempt to load a DLL whose path ends in .msstyles_vrf.dll is therefore likely a CVE-2023-38146 exploit attempt.

  • Point HKCU\Software\Microsoft\Windows\CurrentVersion\ThemeManager\DllName at a UNC path on a share you control and watch the SMB reads. A positive result is two reads of the same _vrf.dll path, where the second read is served different bytes than the first.
  • Trigger a theme reload by setting interface scaling above 100% with SystemParametersInfo action 0x009F. A positive result is a theme reload that reaches the _vrf.dll verification path without a logoff.
  • Look for other check-then-use pairs around signed resource loading, where a signature is verified and the file is then opened again by path. A positive result is a window in which the file can be swapped between the two operations.
  • Test whether processing that happens after visual styles signature validation can be reached with a modified file. A positive result is code or resource handling that runs after the check but still acts on attacker-controlled content.

Glossary

  • API: a function that one program offers so other programs can call it; here, Windows functions that programs can use.
  • CVE: a public catalogue number for a known security vulnerability.
  • Decompilation: turning compiled machine code back into something resembling source code so a human can read it.
  • DLL: a Dynamic Link Library, a file of code and data that a running program can load and use.
  • HKCU: HKEY_CURRENT_USER, the part of the Windows registry that belongs to the logged-in user.
  • INI-style: a plain text configuration format made of sections and key=value lines.
  • Initial access: getting a first foothold on a machine.
  • LoadLibraryEx / LoadLibraryW: Windows functions that load a file as a library into a running program.
  • PE (Portable Executable): the standard Windows file format for programs and libraries, such as .exe and .dll files.
  • PowerShell: Windows' built-in scripting language and command shell.
  • Privilege escalation: turning a limited account into a more powerful one.
  • Proof of concept: a small demonstration program that proves a bug is real without being a full attack tool.
  • Registry: Windows' central settings database, organised as a tree of keys and values.
  • Remote code execution: an attacker getting their own program to run on someone else's computer.
  • Resource section: a named block of data stored inside a PE file.
  • Samba: software that lets a non-Windows machine act as an SMB file server.
  • Scapy: a Python library for crafting and inspecting network packets.
  • SMB: the file-sharing protocol Windows uses to read files from another machine.
  • SYSTEM / NT AUTHORITY\SYSTEM: the most powerful built-in Windows account, the one the operating system itself uses.
  • TOCTOU (Time-of-check to time-of-use): a bug where something is checked, and then used later, with a gap in between in which it can be changed.
  • UNC path: the Windows way of writing a location on the network, starting with two backslashes, like \\server\share.
  • Validation: the act of checking a digital signature.
  • Winlogon: the Windows component that handles logging users on and creating their desktop.

More by Sector 7

View all

7 more disclosed reports, best first.

More from Microsoft (Windows)

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Race conditions

The lesson behind this report.

Parallel requests reach a state the code assumed could not happen: a coupon used twice, a limit overrun, a check skipped.