Hello everyone. Thank you for coming to our talk, Shimmy What You Got? Manipulating Shim and Office for Code Injection. We are very excited to be here. Let's introduce ourselves. My name is Ron Ben-Yitzhak. I'm a security researcher at Deep Instinct. And this is the third year in a row I'm speaking here at DEF CON. And my name is David Shandalov. I'm also a security researcher at Deep Instinct. And this is my first time here. This is what we're going to talk about today. I'll start with an intro about the app compatibility framework, what it is made of, and known techniques to abuse it. Then I'll dive into our attack surface research on Microsoft Office. I'll show how we found an interesting RPC method and combined several manipulations into a single attack that achieves both code injection and privilege escalation. Then we'll show another novel attack. We'll show the reverse engineering process of the driver and the undocumented structures that make the app compatibility mechanism. And how we discovered the finest technique to apply a malicious shim on a process. At the conclusion of the talk, we'll discuss how to detect the attacks shown here and how the community can continue our research. The app compatibility framework is used for backwards compatibility. Software developed for old versions of Windows might behave unexpectedly on newer versions. Microsoft offers many compatibility modes that might look familiar from this window. Programs might access registry paths or directories that no longer exist, such as the C-documented settings, for those who remember. Those issues are fixed with API hooking, patching the assembly of the program itself, and other runtime modifications. Behind the scenes, this is how the mechanism works. The OS uses shim database files, or SDB files, that contain the fixes and modes various applications require. The main file is sysmain.sdb. It is maintained by Microsoft and can only be modified by system updates. We can view those files using a graphic software provided by Microsoft, the compatibility administrator. Here we can see that Edge of Empires 3 requires the compatibility mode High DPI Aware. Users can also install custom SDB files by writing them to these registry paths. Like every component of the OS, people looked for ways to abuse it. There were several talks over the years about the malicious implications to the shim framework. Here you can see a DEF CON talk from almost 10 years ago that shows shims can be used for credential access, network redirection, and more. Also, Alex UNESCO released several articles about this subject back in 2007. Because this is such an old attack vector, most security products should detect malicious shim usage. And the easiest way to do it is by monitoring the registry paths used for installing custom SDB files. So, once upon a time, David and I wanted to start a new research. Initially, we thought about bypassing an EDR, or even disabling it. But apparently, some products just disable themselves. So, instead of EDR bypass, we decided to start an attack surface research. And we needed a target. One of the first choices we came up with is Office. This software is very popular. It can be found on almost every Windows machine. It is also very complex. It has COM objects, tripped-in engines, cloud synchronization, and more. The more components there are, the higher the chances to find an issue. And the most promising feature about Office is the backwards compatibility. It was released over 30 years ago. And legacy code is usually the problematic one, which is good for us. Now, let's talk about the research itself. We wanted to find RPC servers related to Office. And that led us to the service ClickToRunSVC. Here you can see the RPC interfaces it exposes. And narrowing down this list to files related to Office results in three files. The actual executable of the service, OfficeClickToRun.exe. And let's skip the long prefix and just call them virtualization.dll and subsystemcontroller.dll. We started looking into these files to see what functionality they provide. And we found an interesting string in the virtualization.dll. Could not inject subsystem.dll to child process. And lucky us, this string is used by a function that is exposed through RPC. This means that you can easily invoke it. Still, before we start reverse engineering the RPC interface and its methods, we wanted to make sure it actually performs DLL injection. So we debugged it, put breakpoints on the API used for code injection, and then we launched Word. That caused the service to call write process memory. This diagram shows the call stack that led to this API. The RPC call went through several undocumented functions in a few DLL files until it reached write process memory. So what is this DLL? The file description is Microsoft Application Virtualization Client Virtualization Manager Component. And yes, it says virtualization twice. This file exposes two undocumented RPC methods. Instead of diving headfirst into the code, we wanted to find symbols that can shed some light on these functions. We used PowerShell to find RPC clients, and that led us to a file that has symbols. subsystem64.dll. Again, I'm going to skip the long names. The functions in the client are called notifyNewProcess and notifyNewChildProcess. We didn't find anything interesting about the first one. The second function causes the server to call write process memory. Now we want to understand the flow that leads to the DLL injection. So we'll start by debugging the client. We notice that before Word performs the call, it spawns ai.exe as a child process in a suspended state. Then we reach the call itself. We reverse-engineered it and came with its definition. This syntax is for the IDL file. It sends two parameters, the process ID of ai.exe and the string subsystem64.dll, the name of the DLL that made the call. Time to switch sides to the RPC server. Like I said before, those DLL files are undocumented and we want to save time on reverse-engineering them. We searched for all the files that are related to the app virtualization platform and found out that there are files with similar names in the system32 directory. Those files have symbols and they show that the detours library is being used. This is an official library by Microsoft used for hooking and it can also inject code into another process. The functions detourUpdateProcess.dll and detourCopyPayloadToProcess are used to patch the import address table of the target process and force it to load a DLL. Comparing the two files with bindif further proves the similarities. The name primary column belongs to the office file and the name secondary column belongs to the system32 file. Those functions are a perfect match. We can easily understand how the injection is done with the source code of detours. The optional header is modified to point to a new copy of the import table that includes an additional import descriptor to the injected DLL. This is how WinDebug displays the headers. We can see the full path to the DLL, which is unusual. Compilers link the base name. This is everything done by the RPC server. Now let's go back to the client and finish going through this process. Word resumes ai.txt and since the process is not yet initialized, the loader uses the new import table. Because of that, subsystem64 is loaded into the process. We looked at what happens if we imitate the RPC call but specify a 32-bit process as the target. In this case, office click-to-run isn't writing to the memory of this process directly. It launches the tool mavinject32, which is known as a living off-the-land binary, but the injection is exactly the same. Now we want to understand exactly... now that we know exactly how the DLL is injected, what can we gain from it? Security products detect all kinds of malicious behavior. File encryption, shellcode execution, and code injection. But sometimes legitimate programs do that. We just saw an example. And to avoid generating false positive events for customers, such programs will be excluded by the products. This means that if we force office click-to-run to inject a DLL, we'll be able to bypass detection. We know the definition of the RPC method, and we can imitate it to inject subsystem64.dll. But the big question is, can we inject another DLL? As I showed before, the function receives a string, so we can just change the name of the file. But that means we'll have to write our DLL to the office directory, which is very suspicious. And it also requires admin privileges. We tried providing a full path to the file instead of the base name, and this is what happened. We changed the string to ctemp-injected.dll, and it was appended as it is to the office directory. This should raise a flag for every security researcher. It means that there are no sanity checks on the inputs. So we can go back to the 90s and use directory traversal. We can manipulate the file lookup to a completely different place. Let's display the headers of the process again with win-debug, this time after we manipulated the call. We can see our malicious string was appended to the office directory and written to the memory of the process. With this trick, we can inject any DLL we want. But there are still a few limitations. The modified import address table will be used only if the process was launched as suspended and wasn't resumed until the injection was done. It must be uninitialized. Right now, we have a new technique to force a legitimate program to inject a DLL for us. But what more can we achieve from this? A nice thing about RPC is that the client can have lower privileges than the server. The office service runs this anti-authority system. So, can we perform privilege escalation? Well, the short answer is no. The server calls RPC impersonate client before the injection is done. This means that the thread that handles our request will use our token and not the token of anti-authority system. This is done to verify that the client has enough permissions to access the remote process. After the impersonation, the request reaches a subsystem controller.dll which calls open process to gain a handle to the remote process. If we can't get this handle, so will the RPC server and the call will fail. But still, maybe we can escalate from admin to system. The first step to do that will be to launch a process with the privileges of system in a suspended state. We used API monitoring to find such calls and we found that the task scheduler service does exactly that. Scheduled tasks are a great target because there are many default ones that are configured to run a system and even some that are related to office. Such as this one, office automatic updates 2.0. Our injection will be even less suspicious if the service will inject a DLL to another process that is related to office. But we still have a few challenges ahead. The task scheduler service resumes the process shortly after it is launched. We need to find a way to hold the execution of the task scheduler service. And we can do that with an opportunistic lock. Opportunistic locks, or oplocks for short, are a special kind of locks that are used to keep data coherency across computers accessing a file server. A client can lock a file. And when another client tries to access the same file, it will wait. The server will break the lock and notify the first client. The new data will be flushed, the file will be closed, and only then the second client will be able to access it. The nice thing about oplocks is that they can be requested from the local file system by a process. This usage is effectively a semaphore managed by the local file system that synchronizes multiple processes. So, how does it relate to our attack? If we could find a file that is accessed by the task scheduler service after the process is created, but before it is resumed, we could lock it, and it will stop the service from resuming the process. Keeping the process suspended will allow us to inject a DLL to it. We monitor the system for file access while launching the scheduled tasks, and we saw that sysmain.sdb was accessed. In this image, we can see the call stack. Inside createProcessInternal, functions related to the app compatibility were called, and then the shim database was opened. At this point, we know that the task scheduler sometimes reads sysmain.sdb, but we need to understand which tasks lead to that. We need to find a task that executes a file with app compatibility settings. To do that, we locked the sdb file, launched every task registered on the machine, and checked when we were notified about the lock breaking. This led us to a task that executes Microsoft Edge updates. This file has app compatibility settings because of the following entry. The generic installer fix will be applied on every process that has the word update in it. So, this is good, but still, it's not good enough. This file is under Program Files x86, which means it is a 32-bit process. We want to find a target for 64-bit as well. We continue digging into this subject to understand under which circumstances the sdb file will be read, and we noticed a strange behavior that applies to the OS as a whole, not just the task scheduler service. The sdb file was read the first time an executable ran since the machine started, even if it didn't need a fix. And after that, in all other runs, it wasn't. If we could guarantee that the sdb file will be read any time an executable runs, we could choose any scheduled task as our targets. And, of course, we could register a custom sdb file that applies some fix to every process, but that is too noisy. We want to avoid actions that are monitored by security products. We need to find a way to manage the app compatibility mechanism. We looked for files related to this mechanism and found apphelp.dll. By looking at the code of this DLL, we understood that it wraps various operations with the API AntiAppHelpCacheControl. Let's try to understand how to use it. This is an undocumented API that is exported by NTDLL. We searched for references to this API online and in several DLL files until we found that the symbols of combase.dll contain information about it. This is a screenshot of a function from combase without any reverse engineering. We can see that the first parameter is an integer that represents the type of operation to be performed, and the second parameter is a structure with various members that are filled based on the operation chosen. We extracted those definitions and that revealed to us everything that can be done with this API. We applied the definitions on calls from other DLL files and that helped us understand them better. Let's look at createProcess, for example. Now we know that it performs the lookup operation and what information it requires. Like I said before, we encountered a strange behavior. The sdb file was read the first time in an executable run since the machine started, even if it didn't need a fix. And then, it wasn't. At this point, we had enough information to come up with an assumption on why it happens. In this scenario, cmd is going to launch calc. So we have these two processes and also the upheld cache, which is empty at this point. We know that when we call createProcess, the lookup operation is done on the cache. So cmd is going to look for an entry about calc. The cache is empty, so the response is no entry found. That causes cmd to read the sdb file to check if it contained information about fixes calc requires. It doesn't require any fix. So the next step is that the cache is updated and an entry is added. Calc, no fix needed. Then, let's say cmd launches calc again, so it queries that cache one more time. This time, the response is no fix needed. And that is why cmd doesn't read sysmin.sdb again. Based on this assumption, if we could remove this entry from the cache, the sdb file will be read again. We looked at various calls to anti-app-help-cache-controller and found out that both kernel32 and app-help perform the remove operation. In this pseudocode, we can see the information required. It requires the path and the handle to the file. Kernel32 exports a function that does most of the work for us, and it saves us the effort of recreating this call in our code. After this call, the execution of the file will once again trigger reading the sdb file. Okay, so we talked about a lot of stuff. RPC methods, locks, and undocumented API. So in case you lost track, let's put everything together. This is the flow of the attack. We'll start by writing the DLL that will be injected. Then we'll pick a scheduled task. Let's say, Office Automatic Updates 2.0. We need to take care of the shim cache. The file that will be executed might have an entry, so we're going to remove it. Then we'll lock sysmin.sdb. The next step will be to start the task, and that will launch a suspended process with the privileges of system. The task scheduler will try to read the sdb file and start waiting. That will send us a notification about the lock breaking, which means it's time to send the RPC request to the office service. This service will patch the import table of the suspended process and link it to our DLL. The last step will be to release the lock, and that will cause the task scheduler to resume the process and our DLL will be loaded. Ready to see if it works? First, we'll copy our tool to the machine. And let's even scan it. And of course, Defender won't detect it. Now, just to make it clear, we are running the latest version of Office 365, and also the latest Windows 11 build. Now that we made it clear, let's start monitoring the system and launch our tool. We can see that Office C to our client loaded our DLL, and that we gained the console with the privileges of... anti-authority system. Time to summarize. We decided to make an attack surface research on Microsoft Office. We manipulated several components of the OS into a single functioning attack. And these are the advantages of it. Security products will most likely ignore code injection done by Office click-to-run, because this is its purpose. So we'll bypass detection. It will be difficult to link this attack back to us, because not only the injection is done by another process, but the target process is spawned under the task scheduler, not under us. We escalate our privileges from admin to system, and the rest of the actions we perform aren't suspicious. It is very unlikely that someone monitors calls to anti-app-help-cache-control, or monitors using Oprox. So this is the end of my part of the talk. Now please welcome David Chandalov. Thank you, Ron. As we concluded our first attack surface research, we identified a significant knowledge gap regarding anti-app-help-cache-control. Despite extensive information available online, we found that crucial details about some data structures and flows remain unclear. Additionally, with the continuous updates and changes in Windows versions over the years, many publicly shared insights have been altered by Microsoft. Today, I'll provide a comprehensive overview of the mechanism and the modernized attack. So, let's dive right in. As we embarked on our research journey, we were driven by a fundamental question. What can we achieve with the anti-app-help-cache-control API? This inquiry became our guiding light, sparking our curiosity and determination to delve deeper. Our initial exploration gave us a foothold, but we knew we needed more. We needed to understand the technical intricacies. After all, this API controls shim fixes. Maybe we can bend it to our will and control which shim fixes are applied to specific processes. Our second question was more technical. As you can see from the screenshots, during the reading of sysmain.sdb, we noticed that anti-app-help-cache-control interacts with the kernel. This API calls a driver named ahcache.sys, which contains some intriguingly named functions. Functions like api-lookup and write-to-process and cache-lookup stood out, suggesting deeper mechanisms at play. These findings hinted at something significant inside of ahcache.sys, something that required us to dig deeper. So, down the rabbit hole we go. All right, let's lay the foundation. To understand how ahcache.sys operates, we need to start with the basics of its initialization process. When the system boots up, ahcache.sys is loaded, and it requires some initial setup to function properly. This is where the registry comes into play. The registry provides essential values that ahcache.sys reads and stores data to. These values act as a safe location for the driver's operations. This path contains binary data that the driver sorts into an AVL table. The cache needs to be properly initialized through the Windows API before these components can start working. The opposite process happens a shutdown and restart. The AVL table is dumped into the registry, into the app.compat.cache value. Let's take a moment to understand the link between sysmain.sdb, registry entries, and the app.compatibility cache. Each entry in the registry's values data is representing either a file that needs a shim fix or a file that doesn't. We'll revisit the decision-making process for applying fixes, but for now, let's focus on entries indicating files that need a fix. These entries contain several fields, the most significant being the exit tag, which points to a specific shim fix. By examining the data within these entries, we can observe notable differences. Specifically, free bytes vary across entries, and in the last entry, the free bytes are zeroized. Is it a sign for a file not needing a fix? Considering the data's little-endian format, converting it could reveal connections to sysmain.sdb. With sdbexplorer, we can search for these converted values in a readable version of sysmain.sdb. Zooming in on the fields that appear in the sdb, we have the name of the file field, and we can see the matching file field. The matching file field contains just an asterisk, so the whole name field will be compared as it appears. And lastly, we find the shim reference field. Each shim reference has a name and an ID. Some have a command line for additional arguments. Each field has an hexadecimal number attached. Why? It represents the address in the sdb that contains the exit tag as it prefixes the shimfix information block. Now that we understand what an exit tag is and how the registry cache and sysmain.sdb are linked, we wanted to look under the hood of Ahcache.sys. We started looking at the dispatch routines for device Ahcache, and we found that, among other things, anti-app-help-cache-control can update the table with hc-api-update that utilizes insert-element-api, lookup a table entry with hc-api-lookup-cdb that uses lookup-element-api, or it can remove an entry from the table with hc-api-remove using delete-element-api. We decided to continue looking through the dispatch routines. As we already have shown, anti-app-help-cache-control uses the Ahc service class enum, but it is also being used in the dispatch routine inside of Ahcache.sys. The enum has an interestingly sounding member, in its process data for short. We traced a function that is using this value. We were surprised to see no mentions of AVL table manipulation. Maybe this is what we were looking for? Writing to a process through a kernel driver? Sounds awesome! But before we check if we got the good news, let's go through some definitions. Almost every dispatch routine has a unique structure for its operation. This structure contains an undocumented data field. We tried to search the web for definitions, and with some more in-house reverse engineering, we got shim-data. It contains a fixed magic value and a fixed size value. Remember this struct, as we will come to visit it later. Diving deeper inside the function, the calling process and the target process are being checked. Now here is the tricky part. We need to have a protected signer app and PPL. And these two values will be important later. But the call fails in PSGetProcessProtection. Looking at every process in Windows 11, we concluded that no Windows apps with this kind of protection exist. We came to a dead end. But the undocumented structure I talked about before, it piqued our interest. We decided to take that strange name we found and try to look for references of this structure. Maybe we can understand by which operation it is being used and who can be the target. There were a few hits. Reverse engineering the functions that reference shim data revealed that this structure represents the shim fixes that need to be applied to a process. Let's see how a new process is born. Notepad.exe is the child process that is created on behalf of the parent process cmd.exe. The parent queries the app help cache to check if the child process requires shim fixes, as we have shown in the first attack. The parent process reads this main.sdb to retrieve the complete information about the fixes. The parent builds the structure according to the specific fixes and writes it to the memory of the child process. The parent modifies the value of the process environment blocks pshim data to point to the new structure. NTDLL is already loaded in the child process. So NTDLL's loader loads apphelp.dll if pshim data is not empty. Apphelp identifies which shim fixes are to be applied. And so apphelp.dll applies the shim fixes according to the structure. We also wanted to share the flow of the shim data structure creation for future references. The flow starts with create process internal in kernel base, goes through kernel 32 and finally ends with apphelp.dll. The finished struct is built in the sdb pack up compa data function inside of apphelp.dll. Okay. Let's consider the implications of manipulating a system component to build and trigger unauthorized fixes. This could potentially allow us to inject or alter code in a way that bypasses typical security measures. Our investigation into pshim data begins with understanding what data is being written to this specific part of the process environment block. We utilized the compatibility administrator to create and apply custom rules. By extracting the shim data directly from process memory, we gained a first insight into how the data is organized. We chose to fuzz the inputs to see the effect on the data. This process helped us identify patterns in the data handling. By following these steps, we gained a comprehensive understanding of how shim data looks like. And so, at last, we have reversed engineered the shim data structure, essential for understanding how to manipulate shims to our advantage. Here we can see the previous version of the shim data, if you can recall. This is the struct I ask you to remember. There are quite a few changes, most notably the exit tab type field, the exit tag field, and the exit count field. All are essential for correct use of shim fix manipulation. At this stage, we are preparing to use all of our accumulated knowledge for an attack. We can make a target process load a shim fix simply by building our own shim data struct and pointing to the target pshim data to it. The process won't check any condition the original rule has configured. This allows us to apply any fix we want. We chose to inject a DLL into the target process by itself. This effectively makes the attack a file-less and register-less DLL injection that can evade detection. According to this entry, rtvideo.dll will be injected if the process name starts with glj, ends with the temp extension, and it has the correct checksum. Luckily, these checks are done by the parent process and not by the child process. This means that once the exit tag in shim data points to this entry, the child process's app.ldll will apply the fix without checking the conditions. Having said all that, our attack has three limitations. The target process must be started as a suspended process. If the injected process executable file resides in this specific path, or the security identifier of the file's owner is a trusted installer, the shim fix won't be loaded. Injected DLL is not available to 64-bit processes as acgeneral.dll revealed. And you won't believe it, we found the target. And it's the Microsoft Edge updater we have shown before. Microsoft has made our lives easier as all three limitations are not present. Let's inject. At this point, we have enough knowledge to abuse the app compatibility mechanism. So let's go over all of the steps. We need to write our own DLL as the name of the rule specifies. We launch our binary as a suspended process. The struct is built with the correct tag as in our example. We write the struct to the target process's memory. We point to the struct. We resume the execution. And so app help will help us and apply our desired fix. An RT video will load to the target process. Let's see how it looks in action. shim injector.exe is dropped. And so we can see the hello message from inside of the child process. RT video.dll is loaded by our target. We can see our call stack going from install after init to ns inject dll. And lastly, to load library. We also have some logs on the command prompt. You can see the unique size, magic, exit type and exit tag we defined earlier. Let's recap our second attack. There is a long history of shim attacks and how security products typically detect and mitigate malicious shim attacks, attack vectors. We were able to uncover new definitions and insights on the app compatibility component. And we used them to change what we think about this attack vector. This new perspective allowed us to create a new file-less and registry-less attack. We essentially took care of the problem of creating a custom SDB on a system with all that comes with it, namely registry and disk tracks. By writing to a child process which is not suspicious and by loading the target dll from the suspended child process before any EDR hook can be established, we effectively bypassed EDR detection. We chose this specific shim fix because it is applicable to many scenarios and demonstrates our attack in a clear way. There are many more shim fixes that can be used for malicious purposes. This was only one of them. We've come a long way. Let's summarize both attacks and see what we can take away from this research. As for detections, let's go over how should someone detect these kinds of attacks. For the first attack, RPC is a big and early part of the first attack. So monitoring remote procedure calls made to click-to-run service can reveal the use of non-standard dll paths. Requests for opportunistic locks on critical system files like sysmain.sdb should be flagged. Implementing security policies that restrict such high-level memory write operations as it is very suspicious. Click-to-run service shouldn't write to this type of processes on its own. Regarding the second attack, keeping an eye on file system activity, particularly for the creation of dll files which are listed in sysmain.sdb and are in directories unrelated to the original files, to the original rules. Also, we invite the community to take our findings to refine our attacks and make new and better ones. Some ideas. The community could find the target for the init process data operation that we didn't find. There is much more to understand about the shim data structure and how it can affect the execution of the AHCache.sys functions. There are many more flows that can potentially manipulate the AVL table which in turn will affect which process will get what shim fix. In conclusion, in our presentation, we detailed our comprehensive methodology for conducting attack surface research. By leveraging and manipulating various system components, including services, op locks and compatibility mechanisms, we demonstrated how to consolidate these elements into a singular cohesive attack strategy. The op lock and the compatibility mechanisms could be integral parts of other multi-component sophisticated and complex attacks. Op lock can be used in many scenarios as a building block and there are many more shim fixes that can be used with malicious intent, even with 64-bit processes. Our extensive research uncovered new techniques for stealthy injection and privilege escalation, enhancing the effectiveness of these attacks. We demonstrated two attacks that won't be monitored by EDRs. The injection occurs in a very early stage, a stage where EDRs can't establish a hook yet. Through reverse engineering an undocumented API and its associated structures, we gained valuable insights that contributed to the development of these methods. Additionally, we modernized a previously known malicious technique, transforming it into a more elusive fileless and registryless attack. Lastly, we once again encourage the community to continue building on our research, exploring the leads we have provided to further advance this field. Thank you. Thank you so much for being here and hearing our talk. The source code of our tools is now public. If you have any questions, you are free to ask. You can also find us on Twitter and LinkedIn. Thanks again.