Reading view

There are new articles available, click to refresh the page.

Hunting Down MS Exchange Attacks. Part 2 (CVE-2020–0688, CVE-2020–16875, CVE-2021–24085)

The article written by Anton Medvedev, reviewed by Vadim Khrykov

Our previous article focused on the different techniques used to detect ProxyLogon exploitation. This time we will talk about the techniques used to detect other notorious MS Exchange Server vulnerabilities, namely CVE-2020–0688, CVE-2020–16875 and CVE-2021–24085.

Although these vulnerabilities are not as recent as ProxyLogon, we continue to find signs of their exploitation (including successful exploitation). The sooner an exploitation attempt is detected, the more likely it is to minimise or avoid the impact of the attack on the organisation.

Logs and Useful Events

We will use the previously mentioned MS Exchange and Windows logs as event sources.

Detecting Exploitation of CVE-2020–0688

The CVE-2020–0688 vulnerability is contained in the Exchange Control Panel (ECP) component and is related to the the server being unable to properly create unique cryptographic keys because the keys are not randomly generated but are preset with identical values. If we examine the content of the ECP settings in the web.config file from C:\Program Files\Microsoft\Exchange Server\<Version Number>\ClientAccess\ecp, we see that the validationKey and decryptionKey values are already set. These keys are used to secure the ViewState parameter.

web.config file fragment

One of the articles on the Microsoft website describes the ViewState parameter as follows:

On the ASP.NET pages View State presents the state of the page when it was last processed on the server. This parameter is used to create a call context and store values in two consecutive requests for the same page. By default, the state is saved on the client using a hidden field added to the page and restored on the server before the page request is processed. View State moves back and forth with the page itself, but does not represent or contain any information relating to the display of the page on the client side.

As such, pre-shared keys allow an authenticated user to send a deliberate ViewState parameter to the ECP application, which when deserialised will cause malicious code to be executed on the Exchange server in the context of System.

The ysoserialutility which exploits insecure deserialisation in .NET applications can help us create a malicious object.

Below is an example of ViewState generation, its payload in turn runs whoami.

Running ysoserial utility

The validationkey and generator parameters, as described earlier, are preset and cannot be changed. The viewstateuserkey value must be taken from the ASP.NET_SessionId value of the user authorised on the ECP service.

Cookie settings for the user authorised on the ECP service

Once the ViewState has been generated, a request is sent to the vulnerable ECP service, resulting in the server returning an error code 500.

Server response when CVE-2020–0688 is exploited

If you run the request through the BurpSuite utility, you can see in the ViewState decoder that the payload is passed in the <System> tag along with other user parameters:

ViewState decoded

If the vulnerability is successfully exploited, the w3wp.exe process responsible for the ECP (MSExchangeECPAppPool) will execute the payload transferred in the ViewState parameter. Below is the correlation rule to detect cmd.exe commands or the PowerShell interpreter being executed by a w3wp.exe web server process:

  • event_log_source:'Security' AND event_id:'4688' AND proc_parent_file_path end with:'\w3wp.exe' AND proc_file_path end with:('\cmd.exe' OR '\powershell.exe')

The IIS access logs contain a request for the URL /ecp/default.aspx to which the server responded with status 500 (internal server error). Below is the rule for detecting the exploitation of CVE-2020-0688 using IIS events:

  • event_log_source:’IIS’ AND http_method=’GET’ AND http_status_code=’500’ AND url_path=’/ecp/default.aspx’ AND url_query contains ‘__VIEWSTATEGENERATOR’ AND hurl _query contains ‘__VIEWSTATE’
CVE-2020–0688 (IIS) exploitation event

The Application log contains an event which indicates an error in the MSExchange Control Panel application with Event ID = 4.

CVE-2020–0688 (Application log) exploitation result

Below is the rule for detecting CVE-2020–0688 exploitation using Application log events:

  • event_log_source:’Application’ AND event_id=’4’ AND (Message contains ‘__VIEWSTATE’)

Detecting Exploitation of CVE-2020–16875

Successful exploitation of the CVE-2020–16875 vulnerability allows an attacker to execute arbitrary code on the Exchange server in the context of the System user. The attacker can then escalate their domain privileges and compromise the entire company network.

Successful authentication requires a domain account from a corporate mailbox that is a member of a group with Data Loss Prevention (DLP) privileges. The exploitation itself is done through the DLP component. DLP is configured through the ECP interface. The DLP engine allows you to filter mail flow according to predefined patterns and rules for content analysis of emails and attachments.

Since we already know that in order for the exploit to succeed, the attacker must be a member of the DLP group, a rule can be implemented to create a new group with the Data Loss Prevention role, and a new user can be added to that group. This can be done from either the ECP interface or from the Exchange Management Shell using the following commands:

  • New-RoleGroup -Name "dlp users" -Roles "Data Loss Prevention" -Members "user1" (create group dlp users with role Data Loss Prevention and add user1 to the group);
  • Update-RoleGroupMember -Members "dadmin" -identity "dlp users" (add dadmin to group dlp users).

The screenshot below shows the event of adding the user dadmin to the group using the ECP interface. This activity can also be traced back to PowerShell audit events (Event ID 800 and 4104).

Adding user dadmin to group dlp users (MSExchange Management log)

The new Data Loss Prevention creation event can be dected in PowerShell and MSExchange Management log events using the following rule:

Use the rule below to track down events of Data Loss Prevention rights being issued using PowerShell audit events and MSExchange Management logs:

  • event_log_source:('PowershellAudit' OR 'MSExchange Management') AND event_id:('1' OR ’800’ OR '4104') AND ((Message contains ‘New-RoleGroup’ AND Message contains ‘Data Loss Prevention’) OR (Message contains ‘Update-RoleGroupMember’ AND Message contains ‘<Group with DLP rights>’ AND Message contains '-Members'))

The exploit for this vulnerability performs the following steps in sequence:

  1. Authenticate under a given account to retrieve a session through OWA.
  2. Obtain the ViewState parameter by accessing the DLP policy management functionality.
  3. Add a new malicious DLP policy that contains an executable command that runs from PowerShell.

Let’s run the utility and see what the Exchange events look like. Below you can see that the exploit run under the dadmin account was successful.

Successful exploitation of CVE-2020–16875

The access logs of ECP contain an event of a new DLP policy being successfully added:

  • 2021-03-09 12:03:31 10.3.132.20 POST /ecp/DLPPolicy/ManagePolicyFromISV.aspx ActID=3b6c5adc-c7d0-4aeb-82ec-711c2257ece6 444 LAB\dadmin 192.168.1.20 python-requests/2.22.0 - 200 0 0 863

The rule to create a new DLP policy using IIS events:

  • event_log_source:’IIS’ AND http_method=’POST’ AND http_code='200' AND url_path='/ecp/DLPPolicy/ManagePolicyFromISV.aspx'

To exploit the vulnerability, we have to create a new policy, this will come up in the MSExchange Management log as a new event with a random name that contains a malicious payload in the TemplateData parameter:

New DLP policy creation event (MSExchange Management log)

The creation of a new DLP policy can be dected in PowerShell and MSExchange Management log events using the following rule:

  • event_log_source:('PowershellAudit' OR 'MSExchange Management') AND event_id:('1' OR ’800’ OR '4104') AND (Message contains ‘New-DlpPolicy’ AND Message contains '-TemplateData')

The exploition of this vulnerability launches Notepad. Looking at the process start events in the Security log, we see that the Notepad process is initiated by the parent process w3wp.exe with System privileges.

Process start event (Security log)

Use the rules above to detect a successful exploitation of the CVE-2020–16875 vulnerability:

  • event_log_source:'Security' AND event_id:'4688' AND proc_parent_file_path end with:'\w3wp.exe' AND proc_file_path end with:('\cmd.exe' OR '\powershell.exe')

Another variant of the PowerShell exploit has similar logic and performs the following actions:

  1. It creates a remote PowerShell session using the PowerShell component of the Exchange server. The account attempting the connection must have the Data Loss Prevention role.
Code snippet for creating a remote PowerShell session

2. It creates a new policy using the New-DlpPolicy commandlet. The payload is stored in the variable $xml:

Running New-DlpPolicy within a remote PowerShell session

Below is the result of running the PowerShell exploit, successfully connecting as user1 with no privileges and running the whoami command with System privileges.

IIS events show the creation of a remote session:

  • 2021-03-09 13:47:04 10.3.132.20 POST /powershell serializationLevel=Full;ExchClientVer=15.1.1591.10;clientApplication=ManagementShell;TargetServer=;PSVersion=5.1.14393.693&sessionID=Version_15.1_(Build_1590.10)=rJqNiZqNgZqHnJeekZia0bO+vdGzsLy+s4HOxsvNz8nNycvIgc3Pzc7Sz8zSz8arzszFysvFz8s= 444 lab\dadmin 192.168.1.20 Microsoft+WinRM+Client - 500 687 0 180002

The rule that detects this activity is as follows:

  • event_log_source:’IIS’ AND http_method=’POST’ AND url_path='/powershell' AND (Message contains ‘serializationLevel=Full AND Message contains 'clientApplication=ManagementShell') AND user_agent='Microsoft+WinRM+Client'

The Security log detects a successful start of the whoami process with w3wp.exe as the parent process. Execution of the New-DlpPolicy command can be detected in the PowerShell audit log using one of the previously mentioned rules.

whoami process start event

Detecting Exploitation of CVE-2021–24085

The process for exploiting CVE-2021–24085 is more complex. The following steps are required to execute the attack successfully:

  1. Compromise an arbitrary domain account that has a mailbox.
  2. Use the ECP interface to export the certificate.
  3. Using the certificate obtained, generate a CSRF token, aka the msExchEcpCanary parameter.
  4. Get the Exchange administrator to go to the attacker’s malicious page, which will send a request to the Exchange server with the preset token value on behalf of the administrator.

A successful exploitation would allow the attacker to escalate their privileges to Exchange administrator.

A GitHub project can be used to implement the attack, where the poc.py file is responsible for obtaining the certificate that will be used to generate the CSRF token.

YellowCanary — a project coded in C# that is responsible for generating the token.
Poc.js— the JavaScript payload placed by the attacker on a monitored web server designed to lure the Exchange administrator.

The screenshot below shows that the poc.py script has successfully exported the certificate to the testcert.der file.

Successful export of the certificate

An ECP access-log event that contains traces of a certificate being saved:

  • 2021-03-09 15:52:55 10.3.132.20 POST /ecp/DDI/DDIService.svc/SetObject schema=ExportCertificate&msExchEcpCanary=yylkJJJocUWa3HVCEcQli7B3FcF--tgI2nbpJpHLcFZ60E9sZ2gmDpi_sFqf3jl9YcG9qcRMzek.&ActID=cf99b7d2-4eac-4435-a041-f0adaa44ed94 444 LAB\dadmin 192.168.1.20 python-requests/2.22.0 - 200 0 0 500

The certificate is saved in the Exchange server file system — in the poc.png file located in the IIS directory and then downloaded successfully using the same poc.py script.

Certificate download event:

  • 2021-03-09 15:52:55 10.3.132.20 GET /ecp/poc.png - 444 LAB\EXCHANGE$ 192.168.1.20 python-requests/2.22.0 - 200 0 0 7

In this way, we can implement a rule that detects the event of a certificate export in the IIS access logs:

  • event_log_source:’IIS’ AND http_method=’POST’ AND http_code='200' AND url_path='/ecp/DDI/DDIService.svc/SetObject' AND (Message contains 'schema=ExportCertificate')

Once the certificate is obtained, the attacker uses the YellowCanary utility to generate the msExchEcpCanary parameter needed to implement the CSRF attack. The first parameter is the SID of the user on whose behalf we want to perform an action on the ECP:

Generating the msExchEcpCanary parameter

The attacker must then trick a privileged user (ideally an Exchange administrator) into clicking on a prepared link containing the malicious JavaScript code. This code can send requests to the ECP on behalf of the administrator. This could, for example, be used to exploit the CVE-2021–27065 vulnerability, which we covered in the previous article. As a result, the attacker would gain access to the Exchange server with System privileges via the downloaded web shell.

In addition to the above technique, this attack can be performed by adding a malicious MS Outlook add-in, an application that provides users with advanced capabilities.

There are three ways to add an Outlook add-in:

  • Add via the URL where the add-in is located.
  • Download from the Office Store.
  • Download a new add-in from file.
Adding a new add-in via the ECP interface

The add-in is an XML format configuration file. An attacker can create a malicious config that will, for example, forward the contents of client emails to an attacker’s controlled server. The /ecp/Handlers/UploadHandler.ashx interface is used to upload the config file.

Below is a snippet of the JavaScript code that will be executed by the Exchange administrator after being redirected to the attacker’s website. This code fetches the content of the malicious evil.xml add-in, which is also located on the attacker's website, and sends it with a POST request to /ecp/Handlers/UploadHandler.ashx. The msExchEcpCanary parameter contains the CSRF token that was generated in the previous step. It is also worth keeping in mind that when the administrator accesses the attacker's website, their ECP session must still be active.

Adding an add-in using JavaScript

The following rule can be used to detect the loading of an add-in:

  • event_log_source:’IIS’ AND http_method=’POST’ AND http_code='200' AND url_path='/ecp/Handlers/UploadHandler.ashx'

Conclusion

The vulnerabilities discussed in this article are still being exploited today. Most of the time they are unsuccessful, but there are exceptions. Collecting significant security events and implementing detection rules will allow you to react to a possible attack in time to eliminate the fallout from the incident at an early stage.

In the next article, we will talk about Windows domain privilege escalation vectors through the MS Exchange server and how to detect them.

Hunting Down MS Exchange Attacks. Part 1. ProxyLogon (CVE-2021–26855, 26858, 27065, 26857)

By Anton Medvedev, Demyan Sokolin, Vadim Khrykov

Microsoft Exchange is one of the most common mail servers used by hundreds of thousands of companies around the world. Its popularity and accessibility from the Internet make it an attractive target for attackers.

Since the end of 2020, we have recorded a sharp increase in the number of incidents related to the compromise of MS Exchange server and its various components, in particular OWA (Outlook Web Access). Given the MS Exchange’s 24-year history, the complexity of its architecture, its location on the perimeter, and the increased interest in it among security researchers, we can assume that the number of vulnerabilities found in the popular mail server will only increase over time. This is evidenced by the recent discovery by DEVCORE researchers of a chain of critical vulnerabilities known collectively as ProxyLogon.

All this led us to write a series of articles that will focus on MS Exchange security: server attacks and detection techniques.

In the first article in the series, we will take a brief look at the MS Exchange server architecture and move on to the most relevant topic for everyone, i.e. detecting the exploitation of ProxyLogon. We will show how to use standard operating system events and Exchange logs to detect ProxyLogon, both in real time, using proactive threat hunting approaches, and attacks that have already happened in the past.

MS Exchange Architecture and Primary Attack Vectors

The main components of the MS Exchange server and the links between them are shown in the diagram below.

MS Exchange architecture
Source: microsoft.com

Depending on the version, MS Exchange may have the following roles:

  • Mailbox server.
  • A Client Access server, which is a frontend service that proxies client requests to the backend servers.
  • Transport, which is responsible for managing mail traffic.
  • Unified Messaging, which allows voice messaging and other telephony features (the role is not available on version 2019 servers).
  • Management role, which is concerned with administration and flexible configuration of MS Exchange components.

Table 1. Basic protocols used by MS Exchange

The main components of Exchange and their brief descriptions are given below:

  • Outlook Web Access (OWA) — a web interface for mailbox access and management (read/send/delete mail, edit calendar, etc.).
  • Exchange Control Panel (ECP) — a web interface to administer Exchange components: manage mailboxes, create various policies to manage mail traffic, connect new mail servers, etc.
  • Autodiscover — a service that allows customers to retrieve information about the location of various Exchange server components such as the URL for the EWS service. A user needs to be authenticated before the information can be retrieved.
  • Exchange Web Services (EWS) — an API to provide various applications with access to mailbox components.
  • Exchange ActiveSync (EAS) — a service that allows mobile device users to access and manage their email, calendar, contacts, tasks, etc. without an internet connection.
  • RPC — a client access service that uses the RPC protocol, which runs on top of HTTP.
  • Offline Address Book (OAB) — an offline address book service on the Exchange server that allows Outlook users to cache the contents of the Global Address List (GAL) and access it even when not connected to Exchange.

All of the components described above function as applications on the Microsoft IIS web server.

Attackers typically target MS Exchange servers for the following purposes:

  • to gain access to confidential information in corporate emails
  • to launch a malicious mailing from the victim company’s addresses to infiltrate the infrastructure of another organisation
  • to compromise user accounts with the the use of Exchange components (successful bruteforce attack or detection of credentials in email correspondence) to infiltrate the company’s network via one of the corporate services
  • to gain foothold into the company network (e.g. by using a web shell on the OWA service)
  • to escalate privileges in the domain by using the Exchange server
  • to disable the Exchange server in order to disrupt internal business processes (e.g. by fully encrypting server data)

Logs and Useful Events

The source events listed in Table 2 will be useful for detecting various attacks against the MS Exchange server.

Table 2. Event source profile

ProxyLogon Vulnerabilities

On 2 March 2021, Microsoft released security updates for a number of critical MS Exchange server vulnerabilities. The updates included a chain of critical vulnerabilities CVE-2021–26857, CVE-2021–26855, CVE-2021–26858, CVE-2021–27065, commonly referred to as ProxyLogon. After security updates were released and the first articles about these vulnerabilities were published, cyberattacks that exploited these vulnerabilities started being detected all over the world. Most of the attacks were aimed at uploading the initial web shell to the server to develop the attack in the future. While US companies took the brunt of the attack, we also recorded a number of similar attacks targeting our customers in Russia and Asia.

ProxyLogon vulnerability chain

Let us take a closer look at the ProxyLogon vulnerability chain. CVE-2021–26857 is not actually part of this chain, as it leads to code execution on the server and does not require other vulnerabilities to be exploited beforehand. Vulnerability CVE-2021–26857 is related to insecure data deserialisation in the Unified Messaging service. Exploiting this vulnerability requires that the Unified Messaging role be installed and configured on the Exchange server. As this role is rarely used, no exploitation of this vulnerability has been reported so far. Instead, attackers exploit the CVE-2021–26855, CVE-2021–26858 and CVE-2021–27065 vulnerability chain, which also allows remote arbitrary code execution on the mail server but is easier to exploit.

ProxyLogon is the name of CVE-2021–26855 (SSRF) vulnerability that allows an external attacker to bypass the MS Exchange authentication mechanism and impersonate any user. By forging a server-side request, an attacker can send an arbitrary HTTP request that will be redirected to another internal service on behalf of the mail server computer account. To exploit the vulnerability, the attacker must generate a special POST request for a static file in a directory which is readable without authentication, such as /ecp/x.js, where the presence of the file in the directory is not required. The body of the POST request will also be redirected to the service specified in the cookie named X-BEResource.

An attacker using ProxyLogon can impersonate, for example, an administrator and authenticate into the Exchange Control Panel (ECP) and then overwrite any file on the system using the CVE-2021–26858 or CVE-2021–27065 vulnerabilities.

The greatest effect of overwriting files is achieved by creating a web shell in publicly accessible directories. To create a web shell, an attacker exploits a vulnerability in the built-in virtual directory mechanism. When creating a new virtual directory (for example, for an OAB service) an attacker can specify an address that includes a simple web shell as its external address. The attacker must then reset the virtual directory and specify the path to a file on the server where the current virtual directory settings should be saved as a backup. After resetting, the file to which the virtual directory backup will be saved will contain the web shell specified in the previous step.

Once the chain of vulnerabilities have been exploited, an attacker is able to execute commands through a web shell on the Exchange server with the privileges of the account that is used to run the application pool on the IIS server (NT AUTHORITY\SYSTEM by default). In order to exploit the vulnerability chain successfully, an attacker must have network access on port 443 to MS Exchange with Client Access role installed and know the email account name of a user with administrative privileges.

Detection of CVE-2021–26855 Vulnerability

The CVE-2021–26855 vulnerability allows an external attacker to send an arbitrary HTTP request that will be redirected to the specified internal service from the mail server computer account. In this way, the vulnerability allows the attacker to bypass the authentication mechanism of the Exchange server and perform the request with the highest privileges.

Since the attacker can specify the service to which an arbitrary HTTP request is to be redirected, this SSRF vulnerability can be exploited in different ways. Let us look at two ways to exploit this vulnerability: reading emails via EWS and downloading web shells via ECP (CVE-2021–26858 and CVE-2021–27065).

CVE-2021–26855 makes it easy to download any user’s email, just by knowing their email address. The exploitation requires at least two MS Exchange servers in the attacked infrastructure. For example, the request is sent to exchange.lab.local and from there it is redirected via SSRF to exchange02.lab.local. The screenshot below shows an example of this request to the EWS API using a SOAP request to get the last 10 emails from the [email protected] mailbox. The response from the server contains email IDs and other information about the emails (e.g. header or date received).

SOAP request for a list of emails

The attacker can retrieve the original email message by inserting its identifier into another SOAP request.

SOAP request to retrieve an email message

The response from the server will contain a base64 representation of the original email message.

Decoded contents of the email message

In this way, all emails from any given email account can be downloaded from the server without authentication. Email is often used to transmit sensitive information such as payment orders, configuration files, credentials or instructions for connecting to VPN servers, etc. Attackers can use the information obtained from compromised email correspondence for phishing mailings and other cybercrimes. This attack vector is no less dangerous than downloading a web shell to a server.

Such requests are logged by EWS. Accordingly, a rule to detect the described attack might look like this:

  • event_log_source:'EWS' AND AuthenticatedUser end with:'$' AND SoapAction IS NOT NULL AND UserAgent contains:'ExchangeWebServicesProxy/CrossSite/' AND NOT (SoapAction = 'GetUserOofSettings')

The second way to exploit the SSRF vulnerability is by authenticating into the ECP and then exploiting the CVE-2021–26858/CVE-2021–27065 vulnerabilities to upload the web shell to the server. In order to make requests to the ECP, a full session must be established in the ECP. For the attacker to impersonate an administrator when setting up a session, they need to know the SID of the mail server administrator’s account.

First of all, from the response to the NTLM request to /rpc/rpcproxy.dll, an attacker can find out the FQDN of the mail server, which will be needed in the following stages: it will be specified in the NTLM response to be decoded.

Obtaining the FQDN of the mail server

The next step is to obtain the LegacyDN and the email account ID by making an HTTP request to Autodiscover. The FQDN of the mail server obtained in the previous step is specified in a cookie named X-BEResource.

Query Autodiscover for admin email account information

The attacker can then retrieve the SID of the targeted user by sending an HTTP request to MAPI. The attacker sends a request to delegate access to the email account. This request is also forwarded to MAPI on behalf of the computer account user and causes an access error. The error contains the SID of the targeted user.

Query MAPI to retrieve the admin SID

Finally, having obtained the user’s SID, the attacker can authenticate themselves on the server by posing as the administrator by sending a specially crafted POST request to /ecp/proxyLogon.ecp.

Authenticating in ECP as an administrator

The request includes a header named msExchLogonMailBox with the SID of the user to be authenticated. The body of the POST request also contains the SID of that user. In response, the server returns two cookies named ASP.NET_SessionId and msExchEcpCanary that the attacker can use for any future ECP requests. Obtaining these cookies is the end result of the attacker exploiting the ProxyLogon vulnerability (CVE-2021-26855) if they plan to exploit CVE-2021-26858 and CVE-2021-27065 to upload a web shell to the server.

Such requests are logged in the IIS log. Accordingly, a rule to detect this activity can be as follows:

  • event_log_source:'IIS' AND cs-method:'POST' AND cs-uri-stem:'/ecp/proxyLogon.ecp' AND cs-username end with:'$'

Detection of CVE-2021–26858, CVE-2021–27065 Vulnerabilities

Successful exploitation of CVE-2021–27065 allows a malicious file to be uploaded to an Exchange server using the ECP interface, which can then be used as a web shell. Exploitation of this vulnerability requires pre-authentication, which can be performed using CVE-2021–26855. Let us take a closer look at the exploitation of CVE-2021–27065.

We start by logging into the ECP interface and going to Servers → Virtual directories. Editing the virtual directories allows the Exchange application to migrate by changing the current application directory to IIS.

By navigating to the OAB (Default Web Site) edit box in the External URL, an attacker can insert a web shell code, e.g. China Chopper:

Changing virtual directory settings for OAB (Default Web Site)

After setting the new virtual directory configuration parameters, the following event may be seen in the MSExchange Management log:

Setting new parameters for the OAB virtual directory (MSExchange Management log)

The following rule can be implemented to detect such activity:

  • event_log_source:('PowershellAudit' OR 'MSExchangeCMDExec') AND event_id:('1' OR ’800’ OR '4104') AND (Message contains ‘Set-’ AND Message contains ‘VirtualDirectory AND Message contains ‘-ExternalUrl’ AND Message contains ‘script’)

The next step resets the virtual directory settings. In the interface that appears, we see that before resetting we are prompted to save the current virtual directory settings to a selected file:

OAB virtual directory reset interface

After resetting the virtual directory in the MSExchange Management log we can see two events with EventID 1 where first the Remove-OabVirtualDirectory command is used, which is followed by the New-OabVirtualDirectory command in the next event. These events can be used as additional indicators in case the rule described above is triggered.

Let us save the configuration as test.aspx file in C:\Program Files\Microsoft\Exchange Server\V15\FrontEnd\HttpProxy\ecp\auth. In the IIS ECP events, we can see an event telling us that the settings for the application virtual directory have been reset. Example of the event:

2021-03-10 08:16:52 10.3.132.20 POST /ecp/DDI/DDIService.svc/SetObject ActivityCorrelationID=d874fdcd-bd9d-9545-af02-677d356f1aa9&schema=ResetOABVirtualDirectory
&msExchEcpCanary=xkdU4icLzEazuIzEhSZaYgDLNVmW49gIjMvzJCs7TmzJoNU9rXLN15tkY5JGHwEOROWXGGq9_NM.&ActID=113cbd79-1e40-4635-8bae-8c8af6731267
444 LAB\dadmin 192.168.1.20 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/89.0.4389.82+Safari/537.36
https://exchange/ecp/VDirMgmt/ResetVirtualDirectory.aspx?pwmcid=6&ReturnObjectType=1&id=7a466ca6-419b-4445-9cc8-ae66a6bff719&schema=ResetOABVirtualDirectory 200 0 0 7

The following rule detects attempts to reset virtual directories based on IIS log events:

  • event_log_source:’IIS’ AND http_method:’POST’ AND http_code:'200' AND url_path:'/ecp/DDI/DDIService.svc/SetObject' AND (Message contains 'schema=Reset' AND Message contains 'VirtualDirectory')

When exploiting this vulnerability with CVE-2021–26858, an SSRF attack is used to manipulate virtual directories. For this reason, the Username field will contain the computer account, in our case lab.local\EXCHANGE$, as the request is initiated by the Exchange server itself. Given this fact, another rule can be implemented:

  • event_log_source:’IIS’ AND http_method:’POST’ AND http_code:'200' AND url_path:'/ecp/DDI/DDIService.svc/SetObject' AND (Message contains 'schema=Reset' AND Message contains 'VirtualDirectory') AND Username contains '$'

The contents of the test.aspx configuration file can be seen in the screenshot below, where the ExternalUrl parameter contains the specified China Chopper.

Contents of test.aspx

Let us try to execute the command using the downloaded web shell. With Burp Suite we specify the command of interest in the POST parameter a. The result of the command is added to the response from the server, followed by the contents of the configuration file.

Executing commands using a downloaded web shell.

If we look at the start events of the processes, we can see the execution of our command in the IIS work process, which runs the cmd.exe command line interpreter with the corresponding arguments.

By supplementing the detection logic with the PowerShell interpreter, we get the following rule:

  • event_log_source:'Security' AND event_id:'4688' AND proc_parent_file_path end with:'\w3wp.exe' AND proc_file_path end with:('\cmd.exe' OR '\powershell.exe')

Detection of this activity will be described in more detail in one of our upcoming articles.

Web shell activity in Security log

In practice, this CVE was used as a payload after authentication was bypassed using the CVE-2021–26855 vulnerability.

The CVE-2021–26858 vulnerability also allows writing an arbitrary file to an Exchange server, but requires pre-authentication for successful exploitation. This vulnerability can also be used in conjunction with SSRF (CVE-2021–26858).

There are no publicly available PoCs or other sources detailing its exploitation. Nevertheless, Microsoft has reported how this activity can be detected. To do so, we implement the following rule using events from the OAB Generator service:

  • event_log_source:'OABGenerator' AND Message contains 'Download failed and temporary file'

Files must only be uploaded to the %PROGRAMFILES%\Microsoft\Exchange Server\V15\ClientAccess\OAB\Temp directory, writing the file to any other directory is considered illegitimate.

Detection of CVE-2021–26857 Vulnerability

CVE-2021–26857 is an insecure deserialisation vulnerability in a Unified Messaging service.

Unified Messaging allows voice messaging and other features, including Outlook Voice Access and Call Answering Rules. The service must be preconfigured for it to work properly, and is rarely used. For this reason, attackers more often exploit CVE-2021–27065 in real-world attacks.

The problem is contained in the Base64Deserialize method of the CommonUtil class, and the class itself in the Microsoft.Exchange.UM.UMCommon namespace of the Microsoft.Exchange.UM.UMCommon.dll library.

Base64Deserialize method code

This method is called upon in the main library of the Unified Messaging service — Microsoft.Exchange.UM.UMCore.dll, more specifically within the method FromHeaderFile, classed as PipelineContext with namespaces Microsoft.Exchange.UM.UMCore. This way, the attacker can generate their serialised object, for example using the ysoserial.net utility, and remotely execute their code on the Exchange server in the SYSTEM context.

A snippet of the FromHeaderFile method

The new version of the Microsoft.Exchange.UM.UMCore.dll library (after installing the update) has many additional checks on the incoming object types before the deserialisation process. As you can see in the screenshot below, the library is loaded into the UMWorkerProcess.exe process. Consequently, if the vulnerability is exploited, this process will initiate abnormal activity.

Using the Microsoft.Exchange.UM.UMCore.dll library

A rule to detect suspicious child processes being started by UMWorkerProcess.exe (cmd/powershell start, by Security and Sysmon log events):

  • event_log_source:'Security' AND event_id:'4688' AND proc_parent_file_path end with:'\UMWorkerProcess.exe' AND proc_file_path end with:('\cmd.exe' OR '\powershell.exe')

A malicious file may be created as a payload on the file system, such as a reverse shell in the autostart directory or a web shell in one of the IIS directories. The following rule can be implemented to detect this activity:

  • event_log_source:’Sysmon’ AND event_id:'11' AND proc_file_path end with:'\UMWorkerProcess.exe' AND file_name end with:(*.asp OR *.aspx) AND file_path contains:("\ClientAccess\Owa\" OR "\HttpProxy\Owa\" OR "\inetpub\wwwroot\" OR "\www\")

Conclusion

According to Microsoft, at the time of writing about 92% of MS Exchange servers have already been patched and are no longer vulnerable to ProxyLogon. Those who haven’t yet installed the patches should do so as a matter of urgency.

Even if the servers are already patched it is worth checking them for signs of ProxyLogon exploitation and repair the consequences if needed. This is quite easy to do with the standard operating system and Exchange server log events at hand.

Discovering new vulnerabilities in the Exchange server and new attacks are just a matter of time, so it is important to not only protect your mail servers properly, but also to collect and monitor important security events in advance.

We hope you have enjoyed our first article in this series. In the next article, we will explore how to detect the exploitation of other notorious MS Exchange vulnerabilities.

Dynamic Office Template Injection

Sevro Security
Dynamic Office Template Injection

You’ve sent your phishing email with a malicious Microsoft Office document. You pored your blood, sweat, and tears into that sexy Macro of yours. However, modern appliances can easily run that macro in a sandbox and determine if it’s evil or benign.

Sure, you could use common techniques to enumerate if you’re in a sandbox or not but, that requires more code and for the love of god, we’ve all written too much VBA as is. Or, you could encrypt the document and supply the password within the email/title but, some sandboxes have caught on to that as well or maybe the user is too lazy. Another option is to use Dynamic Office Template Injection.


Template Injection

There are some massive benefits to using template injection such as:

  • Ability to send a Docx and not a Docm
  • Macro does not “Live” within the Docx
  • Can “Hot Swap” payloads
  • Can remotely turn macros on and off

Template injection works via the following process (for the example moving forward, I will be using Microsoft Word):

  1. Build your malicious macro into a .Dotm (Microsoft Template containing a Macro).
  2. Host your .Dotm publicly via an S3 bucket, GCP Bucket, DO Space, etc.
  3. Create a .Docx document with a Microsoft Template.
  4. Unzip the .Docx and modify a single XML file
  5. Zip contents back up and change .zip to .Docx

Create the Dotm Document

Here is the Macro that we will add to the .dotm document:

Sub AutoOpen()

    Dim Execute As Variant
    Execute = Shell("calc.exe", vbNormalFocus)

End Sub

In the example case, the Macro simply opens up calc.exe, as all good malware does in its infancy. Once we have the Macro working, we make sure to save the Word Document as a .dotm.

Create and test your macro
Calc.exe Macro

Create the Docx Document

When creating the .docx document, you need to select a real Microsoft Template. I like to use a resume template as they usually do not contain images or extremely fancy formatting.

Select an office template
Select a Template

Now that we have both documents created [example.dotm, resume.docx], let’s host example.dotm on a Digital Ocean space.

Host the macro enabled template
Host the example.dotm

Get the URI to example.dotm and move back to where we have the resume.docx. If you have 7-zip, winzip, etc., right click resume.docx and select Extract Here. If successful, you will be presented with a few new folders and a single xml file as seen below.

Unzip the .docx document
After resume.docx Unzipping

Navigate to word –> _rels –> and open the settings.xml.rels in any text editor. We are going to replace the Target variables data with our example.dotm URI.

settings.xml.rels before the edit.
Before Replacement
settings.xml.rels after the edit.
After Replacement

Save settings.xml.rels and go back to the root directory of the original .docx. Select all the files/directories that were generated from the unzipping:

  • _rels
  • customXml
  • docProps
  • word
  • [Content_Types].xml

Add them all to a single .zip archive and then change the .zip suffix to a .docx suffix to complete the transformation.

Zip the contents of the docx back up
Data to be Zipped
the zip successfully completed.
After Zipping
Rename the.zip to .docx
Change .zip to .docx

The resulting resume.docx will now attempt to pull down the example.dotm template from our Digital Ocean Space each and every time it is opened. The fun part is, we can change the permissions on the example.dotm URI to be Public or Private.


Dynamic Macro Enabling/Disabling

What makes this interesting is the fact that we can change access to the example.dotm file hosted on Digital Ocean simply by making the URI Private or Public.

Resume.docx does not crash when it attempts to navigate to the non-existent example.dotm URI, it just doesn’t load a macro because there’s not one there. Simply put, it looks like any standard docx should.

When we change the example.dotm URI back to Public, and re-open resume.docx, we are presented with a macro enabled document since the URI is alive.

Disable Docx Macro:

By “disable” I simple mean change access to the URI where the .dotm document is located. If the .docx can’t find it, then there’s no macro.

Setting the remote office macro to private
Example.dotm Set to Private
Template Document disabled, no macro is loaded.
Docx Opens Normally

Enable Docx Macro:

Setting the example.dotm to Public and re-opening resume.docx will give us a macro enabled docx that opens calc.exe when we click Enable Content.

Host the Office template on w VPS
Example.dotm Set to Public
Docx loading a macro from office template.
We Get The “Enable Content” Warning
Word Macro Executing Calc.exe
Enabling Content Opens Calc.exe

Use Case

At the top of this post I outlines four (4) of the positives when using this technique. The most objective one being bypassing Email filtering by sending a truly benign docx. Yes, you risk a user opening the document without detonating your macro if they’re really motivated to open everything in their email immediately. But hell, send the phish, wait 5-7min, and arm the link.

It’s also worth noting that an attacker can easily change payloads. For example, if for some reason your initial C2 has been burned but the infection point is undetermined, you can swap out the example.dotm with one of your backup C2’s.


Similar Blog Posts

I am not the originator of this technique and nor do I claim to be. Here are some other blogs describing this same exact technique if you’re interested!

Dynamic Office Template Injection
Joshua

❌