<<

Preventing Reflective DLL Injection on UWP Apps

Mojtaba Zaheri1, Salman Niksefat2, and Babak Sadeghiyan3 1,2,3APA Research Center, Amirkabir University of Technology

Abstract - Universal Windows Platform (UWP) is the ’s recent platform-homogeneous application architecture. It al-lows a code to run on variety of devices including PC, mobile devices, etc., without needing to be rewritten or recompiled. UWP apps are becoming more and more popular and consequently this new application platform is becoming the next attack target for hackers and malware developers. In this paper, we first study the issue of host-based code injection attacks (HBCIA) in UWP apps. We show that de-spite the embedded mechanisms in UWP to maintain code integrity and to only allow legitimate DLLs to be loaded in memory, it is still possible to circumvent the defensive mechanisms and launch a variant of HBCIA called Reflective DLL Injection on UWP apps. We then propose a novel defence mechanism against reflective DLL injection attacks on UWP apps. Our proposed method can detect malicious/benign injection attempts on UWP apps and prevents malicious injections while allowing the benign injections to proceed as normal. Our experiments show that the proposed defence has less than 1% impact on system’s overall performance and can be used inside anti-virus (AV) products to strengthen their protection capabilities.

KEYWORDS – DLL Injection, Universal Windows Platform, UWP

I. INTRODUCTION executing the code [1]. A recent research in [1] shows that near 64% of the total of 162850 Universal Windows Platform (UWP), first sample malware use HBCIA as part of their introduced in , is the Microsoft’s malicious behaviour. platform homogeneous application One strong motivation for using HBCIA by architecture. Its purpose is to allow malware is to evade detection and bypass development of universal applications that run host-based firewalls: Mal-ware usually on a variety of platforms including PC, mobile connect to their C&C 1 servers for sending in- devices, and IoT devices. This relieves the formation and receiving new commands. code from the need to be rewritten or Thus host-based firewalls are generally recompiled for each platform. Similar to sensitive to outgoing connections of locally Android and IOS, this platform has its own running applications and they have rules to store through which prevent unknown applications from accessing Microsoft can have more control over the the network. To prevent being caught by the distributed UWP applications. Since its firewalls, new malware generally uses smart release, Microsoft has encouraged the techniques for connecting to the . One software developers to write code in UWP such technique is taking advantage of and the company itself included some UWP HBCIAs, i.e., injecting a software module to applications in Windows 10, including another legitimate running such as browser and Microsoft Mozilla , or Groove . Chrome and communicating using the With rapid popularity of UWP applications injected module. Among these browsers, among soft-ware developers and considering Microsoft Internet Explorer has been more the strong support of Microsoft, UWP apps promising for hackers as it is generally are becoming more and more popular among available in Windows family of operating end users and consequently this new platform systems by default. Moreover, Microsoft- has become the next attack target for hackers Edge, the Microsoft’s new UWP-based and malware developers. One important browser introduced in Windows 10, can be the category of intra-host attacks that can next injection target for malware that are potentially target UWP applications is Host willing to launch a code-injection attack. Based Code Injection Attacks (HBCIA). In this paper, we demonstrate that it is still HBCIA is defined as locally copying a code possible to launch successful DLL injection from a malicious source process into the attacks by a technique called reflective DLL address space of a target process and injection [2][3] despite the new security

41 OIC-CERT Journal of Cyber Security (2018) 1.1:41-52 ISSN 2636-9680 Print Preventing Reflective DLL Injection on UWP Apps mechanisms embedded in UWP framework to countermeasures. In section III, we review the maintain code integrity and prevent un- security mechanisms embedded in UWP apps signed/malicious DLL injections. Then, we that are related to HBCIA attacks. In section propose a defence mechanism against such IV, we demonstrate the methods that can attacks on UWP apps. circumvent the integrity mechanisms of UWP Some currently published methods such as and perform the reflective DLL injection [4][5] try to parse the victim process memory attack in UWP frame-work. In section V, we and find if a malicious DLL is loaded into the present our defensive mechanism to reflective process memory. Then, they try to remove it DLL injection attacks. In section VI, we and clean the memory. How-ever, it’s not a present the results of the evaluation of the sound and complete countermeasure, as the proposed system. Finally, section VII malware is already loaded in the memory and concludes the paper. can do its malicious activities before being removed from the memory. In contrast, in our proposed mitigation, we try to prevent the II. RELATED WORK malware to load the malicious DLL from the very beginning. Another challenge in The works in host-based code injection countering such attacks is that not all code attacks can be classified into methods for injections are malicious. The performing such attacks, and mechanisms for may inject some legitimate DLLs into detection and prevention. In this section, we processes. Moreover, processes may inject review these works and considering the code into their own address space for detection and prevention mechanisms, we purposes like loading plug-ins, etc. Therefore, claim that none of them is suitable for we need a method to distinguish between defending against reflective DLL injection on malicious and benign injections. Our proposed UWP apps. defence mechanism does this with high precision. In case of a malicious injection, it A. Performing HBCIA successfully prevents the DLL to be written into the target process and raises an alarm. On Since these methods have rather a technical the other hand, in case of a benign injection, nature, the concept has received much more the injection proceeds as normal. Finally, by attention in the technical forums rather than taking advantage of PCMark benchmarking the research papers. tool, we show that our proposed technique In [1], the authors have presented a semi- imposes a little overhead on operating system. formal definition for host-based code injection To summarize, our contribution in this attacks that we cited in the introduction. The paper is a mitigation technique against paper has presented the basic idea of the reflective DLL injection on UWP apps that technique in three main steps including I) provides the following original advantages: Victim process selection, II) Code copying, i. It entirely prevents a malware from and III) Code execution. This paper also loading its malicious module into the mentions several motivations behind using target process memory. HBCIAs including interception of critical ii. The proposed mechanism is very information, privilege escalation, and efficient as it only monitors and detection avoidance. modifies the behaviour of one API In [6], a classification on various DLL (NtWriteVirtualMemory), which Injection techniques is presented. This paper leads to a very low overhead on the system performance. classifies these techniques as follows: iii. It doesn’t have any effects on normal CreateRemoteThread [7], Creating a Proxy DLL injections, as it’s possible to DLL [8], Modification of load legitimate/signed DLLs into [9], Windows Hooks [10][11], Using a target UWP apps through calling the Debugger [12], Patching the IAT [13] and LoadLibrary API. Reflective Injection [2][14]. This paper is organized as follows: In Most of the above techniques can’t be used section II, we re-view related work including to inject into UWP apps because the HBCIA methods and the existing LoadLibrary API has been limited by UWP

42 OIC-CERT Journal of Cyber Security Preventing Reflective DLL Injection on UWP Apps framework code integrity mechanism. process, it interrupts the process and loads a However, a specific type of DLL Injection monitoring module that later checks the API called Reflective Injection which was call patterns in the target process to see if its behavior is malicious. However, the proposed introduced in [2] can be used to circumvent method is only effective against Trojan this mechanism. This method can load a DLL downloaders. on UWP apps through the concept of Also, Detecting the Code Injection Engine reflective programming without directly using (DCIE) [19] tries to reject all the suspicious LoadLibrary API. In section 4, further details creating calls by hooking and about this technique is presented. tracing three main steps of code injection attacks: allocating memory, writing to the memory, and creating the thread. Although B. Detecting and Preventing HBCIA this method prevents the injection attacks, it Since the HBCIAs need to have local has two major weaknesses; access to the tar-get system, these types of attacks had not been considered very i. It rules out injection of legitimate and hazardous in the past. However, the advances signed DLLs, and in HB-CIA techniques and ever-increasing ii. It hooks three APIs, which decreases number of malwares in recent years have system’s performance. motivated the security researchers to work on In case of reflective injection, the articles mitigation mechanisms for these attacks. In [20][21] propose ideas to check the memory the following, we review some of these of running processes periodically and search methods. to find if there is any malicious content, and In [1], a mechanism named BeeMaster is then they try to delete the infected memory proposed to prevent host-based code pages, change their permissions, or even kill injections through using honeypot paradigm. the infected process. However, during the In this mechanism, a master bee and multiple time span between the two checks the worker bees are used. The master bee creates malware can harm the system. and instruments the workers to find if a code In comparison with previous methods, in injection is occurred. If so, the master bee this paper we propose a countermeasure creates a memory dump and terminates the against reflective DLL Injection on UWP worker bee. The downside of this mechanism apps, which is very effective, hooks only one is that the detection only works on the API so it does not depend on API succession processes that are created by the master bee, and has a very low impact on the system’s and therefore it cannot detect the targeted performance. Moreover, through its injections that occur on other processes of the combination with UWP Binary mitigation system. mechanism, it still lets legitimate DLLs to be [15] aims to detect malicious DLL loaded without any limitation. In section V5, injections by evaluating the injected DLLs our proposed countermeasure is presented. through the information provided by the process snapshots. For this purpose, it checks some common malicious DLL characteristics III. UWP SECURITY MECHANISMS in the loaded DLLs to find a match. Nevertheless, one of the drawbacks of this Before addressing the issue of code technique is that it cannot detect the attack injection attacks on UWP apps, we should before the injection, so it cannot prevent the first review several security mechanisms malicious DLL from being loaded. In [16] a embedded in UWP framework to prevent the similar technique is opted for to detect classic injection attacks to happen. malicious DLLs through their characteristics Microsoft’s attitude toward UWP is not only a by using machine learning methods and has better user experience but a more secure the similar defects of [17]. environment for application development that Some of the code injection methods makes it harder for malware to penetrate mentioned in section 2.1 are useful for UWP-based devices. Two important security detection and prevention purposes. For mechanisms in UWP are "App Container" and instance, in [18] a mechanism called DLL "Code Integrity Enforcement" which are Preemptive Injection is used that whenever the system is loading the UrlMon DLL to a

43 OIC-CERT Journal of Cyber Security Preventing Reflective DLL Injection on UWP Apps directly related to HBCIA attacks. We review SID2, and like users, the programs that are these mechanisms in this section. running in app containers. Security Identifier can be part of Built-In A. App Container groups, and consequently, have access to specific resources on the system. The UWP framework is equipped with a new associated name for these App Container security sandbox called App Container which Built-In groups is "Capabilities". provides more fine-grained per-mission Specifically, in case of DLL loading, it’s assignments and limits unauthorized read and worth mentioning that all DLLs must have the write operations throughout the system. App read/execute per-missions of SID "S-1-15-2- Container helps to make sure that an UWP 1" which is equivalent ID for app is only restricted to its defined security ALL_APPLICATION_PACKAGES, in permissions. In the following, we review a DLL’s Access Control List (ACL) number of App Container capabilities. (VoxelBlock, 2016). Limit access to files and peripherals. UWP apps are restricted to access directly to only B. Code Integrity Enforcement two directories: the app’s WindowsApps directory in Program Files, and the app’s Another important security mechanism in package directory located in AppData. The UWP apps is the Code Integrity Enforcement full path to the WindowsApps is [22]. This mechanism is applicable in both [Win_Drive]:\Program Files\WindowsApps. process and kernel levels. The process-level All files stored by apps in WindowsApps enforcement is useful until the time the have to be static files that don’t change process is not compromised because the code through the app’s lifetime. To enforce this integrity check can be disabled in a hacked rule, files stored by applications in this process by the malware. Therefore, Microsoft directory go through integrity checks before has implemented the enforcement in the the app is launched. If a file in this directory is kernel-level to strengthen it against hacked modified, the app will fail those integrity processes and to prevent mal-ware from checks and refuse to launch. Also, the app’s disabling this mechanism. local AppData directory is located in This mechanism activates during the [Win_Drive]:\Users\[UserName]\AppData\Lo LoadLibrary() API call. When a binary is cal\Packages. going to be loaded, the kernel calls This directory is meant to be a place for NtCreateSection() and then MiCreateSection() apps to store dynamic files that can change APIs. This last API finally invokes over the time. As such, files in this directory MiValidateSectionCreate() API which uses don’t go through integrity checks because it is ci.dll (Code Integrity) to check the file meant to be a place for apps to store cache signatures. If the verification does not match files, files, save files, and more. the defined policy, the kernel won’t create the Integrity Levels. App Container is section and will return an error. The implemented using the concept of Integrity mitigation is performed by the kernel, so to Levels. Considering the definition in turn off the mitigation, the intruder must have Microsoft’s MSDN (Microsoft, n..-c), the the kernel-level (ring 0) privilege [23]. Level has one of labels as System, High, The integrity check policies are defined in a Medium, Low, Untrusted. structure called Process Signature Policy in This notion has been introduced in "WinNT.h" (Microsoft, n.d.-a). Using the and is attributed to processes latest Windows SDK, one can see this and objects. This mechanism prevents low structure as shown below: level processes from reading or modifying high level processes and objects. typedef struct In , Integrity Levels have been _PROCESS_MITIGATION_BINARY_SIGNATURE_ POLICY combined with the App Container, and limit { processes to only read and write in their union { restricted area. This concept helps to ensure DWORD Flags; that the program does not have any access to struct { the areas that are out of its range, unless the DWORD MicrosoftSignedOnly : 1; access is explicitly granted. To address this DWORD StoreSignedOnly : 1; DWORD MitigationOptIn : 1; issue, every app container is assigned with a DWORD ReservedFlags : 29;

44 OIC-CERT Journal of Cyber Security Preventing Reflective DLL Injection on UWP Apps

} v. Obtaining the address of LoadLibrary DUMMYSTRU API through using GetProcAddress CTNAME; } API, with Kernel32.dll’s handle and LoadLibrary’s name as the input DUMMYUNIO parameters. NNAME; vi. Calling LoadLibrary API by one of } thread creating APIs like PROCESS_MITIGATION_BINARY_SIGNAT CreateRemoteThread, URE_POLICY, RtlCreateUserThread, and *PPROCESS_MITIGATION_BINARY_SIGN NtCreateThreadEx, by using handle ATURE_POLICY; of the target process, address of LoadLibrary API, and written The flags specified in the structure enforce memory address of the DLL path as integrity restrictions. MicrosoftSignedOnly input parameters to accomplish the can be set to prevent the process from loading attack. images that are not signed by Microsoft. StoreSignedOnly can be set to prevent the Due to the new code integrity security process from loading images that are not mechanism avail-able for UWP apps, it is signed by the Windows Store and finally possible to only allow signed DLLs to be MitigationOptIn can be set to prevent the loaded this way [22]. Thus, attackers must process from loading images that are not not be able to inject arbitrary DLLs on a target signed by Microsoft, the Windows Store and process that is being protected by the code the Windows Hardware Quality Labs integrity mechanism. (WHQL). However, Microsoft’s code integrity All in all, the above integrity mechanism mechanism only triggers on the LoadLibrary makes loading an unsigned DLL using API call, it is still possible to inject binary LoadLibrary API impossible. Nevertheless, in shellcodes into the target process as stated in the next section we review a number of recent [23]. However, working with shellcodes is techniques that allow intruders to circumvent very di cult and the attacker has to handle this mitigation and load arbitrary DLLs into many complexities. Hence, attackers are still the memory of UWP apps even in the looking for methods that de-spite the presence of an anti-virus. existence of Microsoft’s binary mitigation mechanism, inject their arbitrary DLLs to the memory of processes. A little surfing of the IV. HBCIAS ON UWP APPS security and hacking technical forums reveals that it is possible to use a tiny bootstrap shell- One way to perform a host-based code code to perform a so-called Reflective DLL injection attack is to put the code inside a Injection [2][3] and load an arbitrary DLL DLL file and inject the DLL to the target into a target process without directly using the process. This is called DLL injection. A LoadLibrary API call. However, the classic DLL injection attack in Windows reflective DLL injection technique has been operating system is usually carried out by the proposed for classic Windows applications following steps [7]: and their use against UWP apps is not yet documented in academic papers or technical i. Obtaining a handle to the victim forums. We confirmed that this technique process through calling OpenProcess works successfully against UWP apps too by API by setting the process’s ID as the injecting an arbitrary DLL into the Microsoft input parameter of this API. Edge browser’s memory. The details for the ii. Allocating space inside the target reflective DLL injection attack elaborate in process, by invoking VirtualAllocEx the next section. API. iii. Writing malicious DLL’s path into the A. Reflective DLL Injection allocated memory space, by using WriteProcessMemory API. Assuming the attacker has code execution iv. Obtaining a handle of Kernel32.dll capability in the target process and the whole module by calling GetModuleHandle content of the (s)he wishes to inject API. has been written into an arbitrary location of

45 OIC-CERT Journal of Cyber Security Preventing Reflective DLL Injection on UWP Apps memory in the target process, Reflective DLL V. THE PROPOSED DEFENSE Injection [2][3] works as follows: In section 4, we discussed that despite the i. Execution is passed via a tiny embedded mechanism in UWP framework bootstrap shellcode to the library’s against code injection at-tacks [22], it is still ReflectiveLoader function which is an possible to bypass protection and inject exported function found in the arbitrary DLLs in UWP apps. We explained library’s export table. that the reflective DLL injection can be used ii. Since the library’s image currently to inject a DLL into UWP apps (e.g. exists in an arbitrary location in Microsoft Edge browser) without direct call to memory, the ReflectiveLoader first the Loadlibrary API. In this section we calculates its own image’s current propose a technique for defending against location in memory so as to be able to code injection attacks in UWP apps. The parse its own headers for use later on. general idea for the defence is to precisely iii. The ReflectiveLoader will next parse monitor an API call that is commonly used in the processes kernel32.dll export table reflective DLL injection attacks. More in order to calculate the addresses of specifically, our idea is to monitor the input three functions required by the loader, parameters to NtWriteVirtualMemory() API, namely Load-LibraryA, which is used to write into the memory of a GetProcAddress and VirtualAlloc. target process, and only allow valid iv. The ReflectiveLoader will then parameters to get into. allocate a continuous region of To implement this, we use a hooking memory into which it will proceed to library to build a hooking DLL that hooks into load its own image. The location is all user-mode processes by means of a not important as the loader will system-wide Kernel-mode injection driver. correctly relocate the image later on. Since Microsoft strictly forbids patching or v. The library’s headers and sections are hooking in the driver land, we implemented loaded into their new locations in the hooking in user-level, and made it system- memory. wide by a driver that does the DLL injection vi. The ReflectiveLoader will then in the kernel-level. process the newly loaded copy of its image’s import table, loading any A. Preliminaries additional library’s and resolving their respective imported function Before presenting the proposed defence addresses. mechanism, we should first discuss some vii. The ReflectiveLoader will then preliminaries about the underlying Windows process the newly loaded copy of its internals that are used to build our mitigation image’s relocation table. engine. viii. The ReflectiveLoader will then call its User-Mode API Hooking is a technique by newly loaded image’s entry point which developers can instrument and modify function, DllMain with the behavior of API calls, for different DLL_PROCESS_ATTACH. The purposes like monitoring programs’ behavior, library has now been successfully forcing them to function in a different way, loaded into memory. etc. Hooks are widely used by anti-viruses, ix. Finally, the ReflectiveLoader will security applications, system utilities, return execution to the initial programming tools, and so on. There are bootstrap shellcode which called it. multiple hooking libraries such as Microsoft Detours [24], Mhook [25], Deviare [26], Since the technique doesn’t need a direct EasyHook [27], and others that can provide call to LoadLibrary, the security mechanism the user mode hooking capabilities. Their embedded in UWP apps is not able to prevent typical function is as follows: loading of the DLL. In the next section, we propose our mitigation mechanism to prevent i. Storing beginning bytes of the this type of attack. original code of the tar-get function somewhere else. It is needed for the correct behavior of the hooked function.

46 OIC-CERT Journal of Cyber Security Preventing Reflective DLL Injection on UWP Apps

ii. Overwriting the beginning bytes of can use the LoadLibrary API directly to load the target function with a custom code its malicious DLL in to the target process. (called trampoline). So, when the function executes, it jumps to the hook handler. iii. If needed, calling the stored original target function, at the end of the hook handler.

In this paper, we use Mhook [25] which is an open-source library and supports API hooking in both 32- and 64-bit programs. Microsoft also has introduced kernel-mode callbacks with Windows Vista. These callbacks are registered in kernel mode and Figure 1: Proposed defence in action while a malicious provide notifications to the registrar upon a reflective DLL Injection is being launched certain event (e.g. if you register a callback for a specific activity then you can have your For this purpose, we check the Signed Only callback function invoked before/after the flags in PROCESS_MITIGATION_ action has occurred on the system). Three BINARY_SIGNATURE_POLICY structure important callbacks for AV products are to find if the target app is forced to load only triggered for Create Process, Create Thread, signed DLLs. This information is provided by and Load Image events. These callbacks are "WinNT.h" in the Windows SDK version registered by invoking: 10.0.14393.0, and can be accessed by calling GetProcessMitigationPolicy() API with i. PsSetCreateProcessNotifyRoutine ProcessSignaturePolicy type, and ii. PsSetCreateThreadNotifyRoutine, ProcessHandle structure passed to and NtWriteVirtualMemory API, as inputs. This iii. PsSetLoadImageNotifyRoutine. way, the mechanism neglects the injections to other windows applications, just like the way Our proposed mitigation mechanism which the Windows 10 itself does. is written in a hooking DLL is deployed Detecting inter-process writes. It’s possible system-wide using the kernel-level injection for applications to write into their own in a LoadImage callback routine. address space using NtWriteVirtualMemmory API call, which is apparently a non-malicious B. The Mitigation Engine act. Therefore, we consider these intra- In this section we explain the proposed process writes as safe injections and continue technique that mitigates the code injection to check whether we detect a attacks by monitoring the calls to NtWriteVirtualMemory call in which the NtWriteVirtualMemory API. Figures 1 and 2 process IDs of the caller and the target process depict reflective versus normal DLL are different. Since the injections while our proposed defence NtWriteVirtualMemory API is invoked in the mechanism in action. Our proposed source process, the hook function is also mechanism consists three main steps: executed in the con-text of this process and Determining if the Binary Mitigation is we can get the process ID of this process by enforced in the target process: The proposed calling GetCurrentProcessId API. The countermeasure aims to prevent the malware process ID of the target process can also be from circumventing the binary mitigation obtained from the ProcessHandle structure mechanism. In fact, we want to tighten up the passed into the NtWriteVirtualMemory API. mitigation currently enforced in UWP apps, The GetProcessId(ProcessHandle) can obtain and consequently the proposed mechanism this data for us. If these two process IDs are should only be activated for UWP binaries equal, we consider it as a legitimate intra- that are already protected by Windows process injection, and call the original mitigation policy. In other words, if the NtWrite-VirtualMemory API without any binary mitigation is not active, the attacker modification. Otherwise we go to the next step for further checking.

47 OIC-CERT Journal of Cyber Security Preventing Reflective DLL Injection on UWP Apps

indicates whether this is a NE3 format or PE4 format executable or a virtual device driver with LE5 format. The word is $454E ("NE" in ASCII), $4550 ("PE") or $454C ("LE"). So, we check if the Signature field of NT header is equal to $4550. iv. Windows executables have a file header immediately following the $4550 magic number. This header structure has a Characteristics field which is a bit mask. If the bit mask contains the flag IMAGE_FILE_DLL then the file is a DLL, otherwise it is a program file.

Figure 3 illustrates the important structures in "WinNT.h" header file of Windows Kits version 10, considered in the pro-posed mitigation. If all the conditions are met, the Figure 2: Proposed defence in action while a benign normal DLL Injection is being launched mitigation engine considers the API call as malicious, aborts the call, and raises an alarm. Preventing the call if the input includes a DLL. The main difference between the reflective injection and normal DLL injection is that instead of writing the path of the desired DLL, it directly writes the DLL content into the target process memory, and consequently makes it possible to circumvent the Microsoft Mitigation Policy. So, we can utilize this fact, and prevent the write operation if the writing content contains a DLL. To check this please note that all Windows executables begin with a MS-DOS executable stub. So, we first check if a MS- DOS program header exists at the beginning of the injected data. We then check for markers for a Windows executable. If we Figure 3: Structures in a Windows executable file learned that the writing content is a Windows Since benign injections can be done in the executable, we look for information that normal way by writing only the path of the deter-mines whether the file is an application DLL into target process, there is no need to or is a DLL. So, we check the following write the executable content directly, so the conditions respectively: mitigation has no side effects on these benign injections. i. We check the first bytes of data for a valid DOS header. To do this we C. System-Wide DLL Injection check the DOS header size field which should be 64 bytes at We need a mechanism to load our minimum. mitigation engine DLL into all running ii. All DOS program files (and therefore processes upon their execution. To do this we Windows executables) begin with a have taken advantage of a system-wide DLL magic number; the word value $5A4D loading technique. A common method for ("MZ" in ASCII). So, we check if system-wide DLL loading is the e_magic field of DOS header is equal AppInit_DLLs infrastructure [9]. This to $5A4D. mechanism loads an arbitrary list of DLLs in iii. The Windows NT header begins with user-mode processes immediately after a magic number word whose value loading User32 DLL. However, it is not

48 OIC-CERT Journal of Cyber Security Preventing Reflective DLL Injection on UWP Apps enough as it does not load the DLLs in versions of Mitigation DLL are placed in processes that don’t load User32.dll. Like following directories: modern anti-virus products, we have written a kernel driver to implement an AppInit_DLLs- 64 bit : [Win_Drive]:\Windows\System32 like infrastructure that loads our mitigation 32 bit : [Win_Drive]:\Windows\SysWOW64 DLL immediately after loading Ntdll module instead of User32. This way, we will be iv. Allocate memory into the target process ensured that the DLL is loaded in all windows and write the assembly code there. processes, and the Mitigation is enforced Since the callback is called in the con- system-wide. As mentioned earlier, the text of the target process, we can simply PsSetLoadImageNotifyRoutine is used to use NtCurrentPro-cess() to specify what register a callback for Image Load events. process the memory will be allocated This routine has the following signature: and written into. v. Prepare an APC6 to call the assembly NTSTATUS PsSetLoadImageNotifyRoutine( code. APCs al-low user programs and _In_PLOAD_IMAGE_NOTIFY_ROUTINE system components to execute code in NotifyRoutine ); the context of a particular thread and, therefore, within the address space of a After setting this routine, whenever an particular process. One advantage of Image Load event occurs our defined APC is that it runs the code in the NotifyRoutine will be run with context of an existing thread and does PUNICODE_STRING FullImageName, not need to create a new thread for its HANDLE Proces-sId, PIMAGE_INFO operations, so makes it suitable for the ImageInfo, and BOOLEAN Create as input case of system wide injection, as we parameters. Our NotifyRoutine does the need to load our DLL into all processes system-wide DLL injection in five steps: with no impact on performance. Following steps are required to add the i. Check if the loading image is Ntdll. Ntdll code in the Thread APC Queue: is the first DLL that will be automatically loaded for every process on the system, Find a thread in the target process and also contains the target API for KeInitializeApc hooking in our Mitigation DLL, the KeInsertQueueApc NtWriteVirtualMemory API. ii. Find the address of LdrLoadDll. Another Then, the Mitigation DLL will be loaded reason to wait for Ntdll to be loaded is into the process when the APC runs the because we can parse the PE headers and assembly code. Finally, we have a find out the user mode address of mechanism like the AppInit_DLLs LdrLoadDll. As explained in section 4, infrastructure that can load our Mitigation in user mode DLL injection, the DLL in all processes immediately after LoadLibrary API is used for DLL loading the Ntdll. Our implementation codes loading, which is part of Kernel32 DLL. for Mitigation Engine and System Wide This API finally calls LdrLoadDll after Injection Driver are available in Github [28]. some initializations. Thus, as we want to load our Mitigation DLL before loading VI. EVALUATION Kernel32 DLL, we need to do the initialization in the callback routine and To evaluate the proposed mitigation and call the LdrLoadDll directly from Ntdll. assess its efficiency, we first used PCMark iii. Prepare an assembly code to load the benchmarking tool [29] to measure the impact Mitigation DLL through LdrLoadDll call of the new technique on the overall into target process. Since we are performance of the system. PCMark is one of working on x64 Windows, we need to a series of Windows performance testing tools write two different x64 and that are provided by the Futuremark. It assembly codes, to call the LdrLoadDll includes a variety of bench-mark tests with the name of the proper version of reflecting the different ways use their Mitigation DLL as input, into target 64- computers. Each benchmark produces and 32-bit processes. Also, two distinct detailed results for gaining a deep understanding of performance during each

49 OIC-CERT Journal of Cyber Security Preventing Reflective DLL Injection on UWP Apps individual workload. The technical guide in took advantage of API Monitor program [30] [29] explains specific tests the tool conducts to illustrate the fact that the on systems, and the formulas it uses to NtWriteVirtualMemory API call is not produce the scores. frequently used in prevalent Windows pro- We used a virtual machine with the grams. API Monitor is a free monitoring tool following specifications in our experiments that lets us monitor and control API calls which is Windows 10 x64 Enterprise Build made by applications and services. We 14393 as Operating System, Intel Xeon selected a set of Windows programs, and ran X5670 @ 2.93 GHz @ 2933 MHz as CPU, 1 each program for five minutes, to check call Core(s), 1 Logical Processor(s) and 8.00 GB frequency of NtWriteVirtualMemory API. As Memory. illustrated in Table 3, call frequency of the We selected 5 common benchmarks and API is at most 0.0002% in measured the system performance while our application. mitigation engine is on or off. Based on the results provided in Table 1, the overall Table 1: Overall Performance Impact on System (Time-Based). performance degradation is at most 0.59 Benchmark Normal Hooked Overhead % Web Browsing - percent which is very small and negligible. In 0.373 s 0.375 s 0.54 fact, the mitigation DLL does not have JunglePin Web Browsing - significant influence on typical user activities 0.141 s 0.141 s 0.0 like web browsing, text writing, video chat Amazonia and others. Since the technique only checks Writing 6.31 s 6.31 s 0.0 the NtWriteVirtualMemory API calls for Phone Editing v2 1.867 s 1.878 s 0.59 Video Chat v2/Video inter-process writes into UWP apps and this 704.7 ms 706.5 ms 0.26 Chat Encoding v2 event is not very common in ordinary usages of the system, it doesn’t have tangible impact Table 2: Performance Impact on NtWriteVirtualMemory API. on the system’s usual functionalities and Content is Target Normal Hooked Overhead performance. DLL is UWP ms ms % Next, we assess the proposed   0.0481 1.0270 2035.14 countermeasure’s impact on   0.0482 0.0504 4.56 NtWriteVirtualMemory which the specific   0.0480 0.0511 6.46 API is involved in the mitigation. To do so,   0.0481 0.0503 4.57 we called the API to write a 100 KB memory block into a target process for 10000 times Table 3: NtWriteVirtualMemory Call Frequency in Windows and calculated the average time. The detailed Programs results are provided in Table 2. Whenever a NtWriteVirtualMemory Total Number of Program DLL is being written into an UWP process Call Call memory, the write operation will be aborted, Vmware and the user will be informed about the Workstation 1 2330721 malicious activity, so the first row of the table Telegram 0 2495273 is not a usual write operation and its overhead Twitter 0 1658813 doesn’t have any impact on the system’s Spark Instant performance. If the target of the write Messenger 0 5255403 operation is a non-UWP process, the Notpad++ 0 1317342 mitigation will be stopped in the first step, and 1 12404209 based on the results of the second and fourth VLC Media Player 0 11506828 rows of the table, its overhead impact is TeamViewer 0 6176240 around 4.6 percent. However, if the writing Mozilla Firefox 0 15501030 content is not a DLL, and the target process is Google Chrome 23 10272584 UWP, the mitigation mechanism will be stopped in the third step and will have an Microsoft Edge 0 2464095 Wireshark Network overhead around 6.5 %. However, since it Analyzer 5 2843753 doesn’t occur commonly in the system, it Internet Download doesn’t have a tangible impact on the system Manager 0 4944558 overall performance, as shown in Table 1. Finally, to assess the number of NtWriteVirtualMemory API calls during execution of common Windows programs, we

50 OIC-CERT Journal of Cyber Security Preventing Reflective DLL Injection on UWP Apps

VII. CONCLUSION [9] Help, M., & Support. (2010). Working with the appinit DLLs registry value []. In this paper, we studied the issue of ://support.microsoft.com/en/us/help/1975 reflective DLL injection attacks on UWP apps 71/working-with-the-appinit-dlls -registry- and proposed a defence mechanism to counter value. such attacks. We discovered that despite the [10] Kuster, R. (2003). Three ways to inject your embedded security mechanism in UWP code into another process [Web Page]. framework, it is still possible to inject https://www.codeproject.com/ malicious/unsigned DLLs into UWP apps Articles/4610/Three-Ways-to-Inject-Your- even in the presence of an antivirus software. Code -into-Another-Process To defend against these attacks, we proposed [11] Newcomer, J. M. (2001). Hooks and DLLs a mechanism that monitors the input [Web Page]. parameters to NtWriteVirtualMemory() API https://www.codeproject.com/Articles/1037/ and aborts malicious DLL injection attacks. Hooks-and-DLLs. We implemented the proposed idea by [12] Shewmaker, J. (2010). Analyzing DLL leveraging the hooking libraries and Windows injection [Web Page]. kernel callbacks. This allows us to monitor http://www.bluenotch.com/. the processes and prevent malicious injections [13] NTCore. (2012). Explorer suite [Web Page]. into UWP apps while allowing the benign www.ntcore.com/ exsuite.php. injections to proceed as normal. [14] Barabosch, T., & Gerhards-Padilla, E. (2014). Host-based code injection attacks: A popular technique used by malware [Conference VIII. REFERENCES Proceedings]. In Malicious and unwanted software: The americas (malware), 2014 9th [1] Barabosch, T., Eschweiler, S., & Gerhards- international conference on (p. 8-17). IEEE. Padilla, E. (2014). Bee master: Detecting host- [15] Jang, M., Kim, H., & Yun, Y. (2007). based code injection attacks [Conference Detection of DLL inserted by windows Proceedings]. In International conference on malicious code [Conference Proceedings]. In detection of intrusions and malware, and Convergence information technology, 2007. vulnerability assessment (p. 235-254). international conference on (p. 1059-1064). Springer. IEEE. [2] Fewer, S. (2008). Reflective DLL injection [16] Glendowne, D., Miller, C., McGrew, W., & [Journal Article]. Harmony Security, Version, Dampier, D. (2015). Characteristics of 1. malicious DLLs in windows memory [3] Staples, D. (2015). Improved reflective [Conference Proceedings]. In Ifip international DLLinjection [Web Page]. conference on digital forensics (p. 149-161). https://github.com/dismantl/ImprovedReflecti Springer. veDLLInjection. [17] VoxelBlock. (2016). Basic and intermediate [4] Mertsarica. (2010). Antimeter tool [Web techniques of uwp app modding [Web Page]. Page].https://www.mertsarica.com/antimeter- https://www.unknowncheats.me/ tool/. [5] King, A. (2012). Detecting reflective injection forum/general-programming-and- [Web Page]. reversing/177183-basic intermediate- https://www.defcon.org/html/defcon-20/dc-20 techniques-uwp-app-modding.. -speakers.html#King. DEF CON R 20 [18] Yucheng, G., Peng, W., Juwei, L., & Hacking Conference. Qingping, G. (2011). A way to detect [6] Berdajs, J., & Bosnic,´ Z. (2010). Extending computer trojan based on DLL preemptive applications using an advanced approach to injection [Conference Proceedings]. In DLL injection and API hooking [Journal Distributed computing and applications to Article]. Software: Practice and Experience, business, engineering and science (dcabes), 40(7), 567-584. 2011 [7] Richter, J. (1994). Load your 32 bit DLL into [19] Sun, H.-M., Tseng, Y.-T., Lin, Y.-H., & another process’s address space using injlib Chiang, T. (2006). Detecting the code [Journal Article]. Microsoft Systems Journal- injection by hooking system calls in windows US Edition, 13-40. kernel mode [Conference Proceedings]. In [8] Lam, L.-c., Yu, Y., & Chiueh, T.-c. (2006). 2006 international computer symposium, ics. Secure mobile code execution service. In [20] DLL [Web Page]. http://www.codeguru.com/ Proceedings of the 20th conference on large cpp/g-m//directx8/article.php/c11453/ installation system administration (pp. 5–5).

51 OIC-CERT Journal of Cyber Security Preventing Reflective DLL Injection on UWP Apps

Intercept-Calls-to-DirectX-with-a-Proxy- DLL.htm. [21] Microsoft. (n.d.-a). Process mitigation binary signature policy structure [Web Page]. https://msdn.microsoft.com/en- us/library/windows/desktop/mt706242(v=vs.8 5).aspx [22] Cowan, C. (2015). Protecting microsoft edge against binary injection [Web Page]. https://blogs.windows.com/msedgedev/2015/1 1/17/microsoft-edge-module-code -integrity/. [23] Rascagneres, P. (2016). Microsoft edge binary injection mitigation overview [Web Page]. http://www.sekoia.fr/blog/microsoft-edge- binary-injection-mitigation -overview/. [24] Microsoft. (2002). Detours [Web Page]. https://www.microsoft.com/enus/research/proj ect/detours/. [25] Mhook, an API hooking library [Web Page]. (2014). https:// .com/martona/mhook. [26] Deviare API hook [Web Page]. (2017). http://www.nektra.com/products/deviare-api- hook-windows/. [27] Easyhook the reinvention of windows API hooking [Web Page]. (2017). https://easyhook.github.io/. [28] Zaheri, M., & Niksefat, S. (2017). Github project for preventing reflective DLL injection on UWP apps [Web Page]. https:// github.com/m0jt4b4/UWPHardening. [29] FutureMark. (2016a). Pcmark 8: The complete benchmark for windows [Web Page]. http://www.futuremark.com/ benchmarks/pcmark. [30] rohitab.com. (2017). APIMonitor: Spy on API calls and COM inter-faces [Web Page]. http://www.rohitab.com/apimonitor.

52 OIC-CERT Journal of Cyber Security