Phishing – Ask and ye shall receive

During penetration tests, our primary goal is to identify the difference in paths that can be used to obtain the goal(s) as agreed upon with our customers. This often succeeds due to insufficient hardening, lack of awareness or poor password hygiene. Sometimes we do get access to a resource, but do not have access to the username or password of the user that is logged on. In this case, a solution can be to just ask for credentials in order to increase your access or escalate our privileges throughout the network. This blogpost will go into the details of how the default credential gathering module in a pentesting framework like MetaSploit can be further improved and introduces a new tool and a Cobalt Strike module that demonstrates these improvements.

Current situation

Let’s say that we have a meterpreter running on our target system but were unable to extract user credentials. Since the meterpreter is not running with sufficient privileges, we also cannot access the part of the memory where the passwords reside. To ask the user for their credentials, we can use a post module to spawn a credential box on the user’s desktop that asks for their credentials. This credential box looks like the one in the image below.

old_pwd_prompt

While this often works in practice, a few problems arise with using this technique:

  • The style of the input box stems from Windows XP. When newer versions of Windows ask for your credentials, a different type of input box is used;
  • The credential box spawns out-of-the-blue. Even though a message and a title can be provided, it does not really look genuine; it misses a scenario where a credential box asking for your credentials can be justified.

A better solution

Because of these issues, this technique will perhaps not work on more security aware users. These users can be interesting targets as well, so we created a new script that solves the aforementioned problems. For creating a realistic scenario, the main approach was: “What would work on us?” The answer to this question must at least entail the following:

  • The credential box should be genuine and the same as the one that Windows uses;
  • The credential box should not be spawned out-of-the-blue; the user must be persuaded or should expect a credential box;
  • If (error) messages are used, the messages should be realistic. Real life examples are even better;
  • No or limited visible indications that the scenario is not real.

As a proof of concept, Fox-IT created a tool that uses the following two scenario’s:

  • Notifications that stem from an (installed) application;
  • System notifications that can be postponed.

With this, the attacker can use his creativity to deceive the user. Below are some examples that were created during the development of this tool:

Outlook lost connection to Microsoft Exchange. In order to reconnect, the user must specify credentials to reestablish connection to Microsoft Exchange.

outlook_toast

Password that expires within a short period of time.

change_password

The second scenario imitates notifications from Windows itself, such as pending updates that need to be installed. The notification toast tricks the user into thinking that the updates can be postponed or dismissed. When the user clicks on the notification toast the user will be asked to supply their credentials.

updates_toast

If the user clicks on one of these notifications, the following credential box will pop up. The text of the credential box is fully customizable.

creds_outlook

Once the user has submitted their credentials, the result is printed on the console which can be intercepted with a tool of your choosing, such as Cobalt strike. We created an aggressor script for Cobalt Strike that extends the user interface with a variety of phishing options.

cs

Clicking on one of these options will launch the phishing attack on the remote computer. And if users enter their credentials, the aggressor script will store these in Cobalt Strike as well. The tool as well as the Cobalt Strike aggressor script are available on Fox-IT’s GitHub page: https://github.com/fox-it/Invoke-CredentialPhisher

 

Technical details

During the development of this tool, there were some hurdles that we needed to take. At first, we created a tool that pops a notification balloon. That worked quite well, however, the originating source of the balloon was mentioned in the balloon as well. It’s not really genuine when Windows Powershell ISE asks for Outlook credentials, so that was not a solution that satisfied us.

balloon_powershell

In recent versions of Windows, toast notifications were introduced. These notifications look almost the same as a notification balloon that we used earlier, but work entirely different. By using toast notifications, the problem that the originating source was shown was solved. However, it proved not possible to use event handlers on the toast notifications with native PowerShell. We needed an additional library that acts as a wrapper, which can be found on the following GitHub page: https://github.com/rkeithhill/PoshWinRT

That library solved one part of the issue, but needed to be present on the filesystem of the target computer. That leaves traces of our attack which we do not want, plus, we want to leave the least amount of traces of our malicious code. Therefore, we encoded the library as base64 and stored that in the PowerShell script. The base64 equivalent of the library is evaluated and loaded from memory during runtime and will leave no trace on the filesystem once the tool has been executed. So, now we had a tool capable of sending toast notifications that look genuine. Because of how Windows works, we could also create an extra layer of trust by using an application ID as the source of the notification toast. That way, if you were able to find the corresponding AppID, it looks like the toast notification was issued by the application rather than an attacker.

The notifcation toasts supports the following:

  • Custom toast notification title;
  • Custom credential box title;
  • Custom multiline toast notification message.

To make it more personal, it is possible to use references to attributes that are part of the System.DirectoryServices.AccountManagement.UserPrincipal object. These attributes can be found on the following Technet article: https://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.userprincipal_properties(v=vs.110).aspx. Additionally, the application scenario supports the following extra features when an application name is provided and can be found by the tool:

  • AppID lookup for adding extra layer of credibility. If no AppID is found, the tool will default to control panel;
  • Extraction of the application icon. The extracted icon will be used in the notification toast;
  • If no process is given or the process cannot be found, the tool will extract the information icon from the C:\Windows\system32\shell32.dll library. By modifying the script, it is easy to incorporate icons from other libraries as well;
  • Hiding of application processes. All windows will be hidden from the user for extra persuasion. The visibility will be restored once the tool is finished or when the user supplied their credentials.

Cmdline examples

For the examples above, the following onliners were used:

Outlook connection:

.\Invoke-CredentialPhisher.ps1 -ToastTitle "Microsoft Office Outlook" -ToastMessage "Connection to Microsoft Exchange has been lost.`r`nClick here to restore the connection" -Application "Outlook" -credBoxTitle "Microsoft Outlook" -credBoxMessage "Enter password for user ‘{emailaddress|samaccountname}'" -ToastType Application -HideProcesses

Updates are available:

.\Invoke-CredentialPhisher.ps1 -ToastTitle "Updates are available" -ToastMessage "Your computer will restart in 5 minutes to install the updates" -credBoxTitle "Credentials needed" -credBoxMessage "Please specify your credentials in order to postpone the updates" -ToastType System -Application "System Configuration"

Password expires:

.\Invoke-CredentialPhisher.ps1 -ToastTitle "Consider changing your password" -ToastMessage "Your password will expire in 5 minutes.`r`nTo change your password, click here or press CTRL+ALT+DELETE and then click 'Change a password'." -Application "Control Panel" -credBoxTitle "Windows Password reset" -credBoxMessage "Enter password for user '{samaccountname}'" -ToastType Application

Recommendations

There are no specific recommendations that are applicable to this phishing technique, however, some more generic recommendations are still applicable:

  • Check if PowerShell script logging and transcript logging is enabled;
  • Raise security awareness;
  • Although it is quite hard to distinguish a fake notification toast from a genuine notification toast, users should have a paranoid approach when it comes to processes asking for their credentials.

Bokbot: The (re)birth of a banker

This blogpost is a follow-up to a presentation with the same name, given at SecurityFest in Sweden by Alfred Klason.

Summary

Bokbot (aka: IcedID) came to Fox-IT’s attention around the end of May 2017 when we identified an unknown sample in our lab that appeared to be a banker. This sample was also provided by a customer at a later stage.

Having looked into the bot and the operation, the analysis quickly revealed that it’s connected to a well-known actor group that was behind an operation publically known as 76service and later Neverquest/Vawtrak, dating back to 2006.

Neverquest operated for a number of years before an arrest lead to its downfall in January 2017. Just a few months afterwards we discovered a new bot, with a completely new code base but based on ideas and strategies from the days of Neverquest. Their business ties remains intact as they still utilize services from the same groups as seen before but also expanded to use new services.

This suggests that at least parts of the group behind Neverquest is still operating using Bokbot. It’s however unclear how many of the people from the core group that have continued on with Bokbot.

Bokbot is still a relatively new bot, just recently reaching a production state where they have streamlined and tested their creation. Even though it’s a new bot, they still have strong connections within the cybercrime underworld which enables them to maintain and grow their operation such as distributing their bot to a larger number of victims.

By looking back in history and the people who are behind this, it is highly likely that this is a threat that is not going away anytime soon. Fox-IT rather expects an expansion of both the botnet size and their target list.

76service and Neverquest

76service was, what one could call, a big-data mining service for fraud, powered by CRM (aka: Gozi). It was able to gather huge amounts of data from its victims using, for example, formgrabbing where authorization and log-in credentials are retrieved from forms submitted to websites by the infected victim.

76service panel login page (source: krebsonsecurity.com)

76service login page (source: krebsonsecurity.com)

The service was initially spotted in 2006 and was put into production in 2007, where the authors started to rent out access to their platform. When given access to the platform, the fraudulent customers of this service could free-text search in the stolen data for credentials that provide access to online services, such as internet banking, email accounts and other online platforms.

76service operated uninterrupted until November 2010, when an Ukrainian national named Nikita Kuzmin got arrested in connection with the operation. This marked the end of the 76service service.

Nice Catch! – The real name of Neverquest

A few months before the arrest of Nikita he shared the source code of CRM within a private group of people which would enable them to continue the development of the malware. This, over time, lead to the appearance of multiple Gozi strains, but there was one which stood out more than the others, namely: Catch.

Catch was the name given internally by the malware authors, but to the security community and the public it was known as Vawtrak or Neverquest.

During this investigation into Catch it became clear that 76service and Catch shared several characteristics. They both, for example, separated their botnets into projects within the panel they used for administering their infrastructure and botnets. Instead of having one huge botnet, they assigned every bot build with a project ID that would be used by the bot to let the Command & Control (C2) server know which specific project the bot belonged to.

76service and Catch also shared the same business model, where they shifted back and forth between a private and rented model.

The private business model meant that they made use of their own botnet, for their own gain, and the rented business model meant that they rented out access to their botnet to customers. This provided them with an additional income stream, instead of only performing the fraud themselves.

The shift between business models could usually be correlated with either: backend servers being seized or people with business ties to the group being arrested. These types of events might have spooked the group as they limited their infrastructure, closing down access for customers.

For the sake of simplicity, Catch will from here on be referred to as Neverquest in this post.

“Quest means business” – Affiliations

If one would identify a Neverquest infection it might not be the only malware that is lurking on the infected system. Neverquest has been known to cooperate with other crimeware groups, either to distribute additional malware or use existing botnets to distribute Neverquest.

During the investigation and tracking of Neverquest Fox-IT identified the following ties:

Crimeware/malware group Usage/functionality
Dyre Download and execute Dyre on Neverquest infections
TinyLoader & AbaddonPOS Download and execute TinyLoader on Neverquest infections. TinyLoader was later seen downloading AbaddonPOS (as mentioned by Proofpoint)
Chanitor/Hancitor Neverquest leverages Chanitor to infect new victims.

By leveraging these business connections, especially the connection with Dyre, Neverquest is able to maximize the monetization of the bots. This since Neverquest could see if a bot was of interest to the group and if not, it could be handed off to Dyre which could cast a wider net, targeting for example a bigger or different geographical region and utilize a bot in a different way.

More on these affiliations in a later section.

The never ending quest comes to an end

Neverquest remained at large from around 2010, causing huge amounts of financial losses, ranging from ticket fraud to wire fraud to credit card fraud. Nevertheless, in January 2017 the quest came to an end, as an individual named Stanislav Lisov was arrested in Spain. This individual was proven to be a key player in the operation: soon after the arrest the backend servers of Neverquest went offline, never to come back online, marking the end of a 6 year long fraud operation.

A more detailed background on 76service and Neverquest can be found in a blogpost by PhishLabs.

A wild Bokbot appears!

Early samples of Bokbot were identified in our lab in May 2017 and also provided to us by a customer. At this time the malware was being distributed to US infections by the Geodo (aka: Emotet) spam botnet. The name Bokbot is based on a researcher who worked on the very early versions of the malware (you know who you are 😉 ).

Initial thoughts were that this was a new banking module for Geodo, as this group had not been involved in banking/fraud since May 2015. This scenario was quickly dismissed after having discovered evidence that linked Bokbot to Neverquest, which will be further outlined hereafter.

Bokbot internals

First, let’s do some housekeeping and look into some of the technical aspects of Bokbot.

Communication

All communication between a victim and the C2 server is sent over HTTPS using POST- and GET-requests. The initial request sent to the C2 is a POST-request containing some basic information about the machine it’s running on, as seen in the example below. Any additional requests like requesting configs or modules are sent using GET-requests, except for the uploading of any stolen data such as files, HTML code, screenshots or credentials which the victim submits using POST-requests.

bokbot_post_request
Even though the above request is from a very early version (14) of the bot, the principle still applies to the current version (101), first seen 2018-07-17.

URL param. Comment
b Bot identifier, contains the information needed to identify the individual bot and where it belongs. More information on this in later a section.
d Type of uploaded information. For example screenshot, grabbed form, HTML or a file
e Bot build version
i System uptime
POST-data param. Comment
k Computer name (Unicode, URL-encoded)
l Member of domain… (Unicode, URL-encoded)
j Bot requires signature verification for C2 domains and self-updates
n Bot running with privilege level…
m Windows build information (version, arch., build, etc.)

The parameters that are not included in the table above are used to report stolen data to the C2.

The C2 response of this particular bot version is a simple set of integers which tells the bot which command(s) that should be executed. This is the only C2 response that is unencrypted, all other responses are encrypted using RC4. Some responses are, like the configs, also compressed using LZMAT.

After a response is decrypted, the bot will check if the first 4 bytes equal “zeus”.

bokbot_zeus_sig

If the first 4 bytes are equal to “zeus”, it will decompress the rest of the data.

The reason for choosing “zeus” as the signature remains unknown, it could be an intentional false flag, in an attempt to trick analysts into thinking that this might be a new ZeuS strain. Similar elusive techniques have been used before to trick analysts. A simpler explanation could be that the developer simply had an ironic sense of humor, and chose the first malware name that came to mind as the 4 byte signature.

Configs

Bokbot supports three different types of configs, which all are in a binary format rather than some structured format like XML, which is, for example, used by TheTrick.

Config Comment
Bot The latest C2 domains
Injects Contains targets which are subject to web injects and redirection attacks
Reporting Contains targets related to HTML grabbing and screenshots

The first config, which includes the bot C2 domains, is signed. This to prevent that a takeover of any of the C2 domains would result in a sinkholing of the bots. The updates of the bot itself are also signed.

The other two configs are used to control how the bot will interact with the targeted entities, such as redirecting and modifying web traffic related to for example internet banking and/or email providers, for the purpose of harvesting credentials and account information.

The reporting config is used for a more generic purpose, where it’s not only used for screenshots but also for HTML grabbing, which would grab a complete HTML page if a victim browses to an “interesting” website, or if the page contains a specific keyword. This enables the actors to conduct some reconnaissance for future attacks, like being able to write web injects for a previously unknown target.

Geographical foothold

Ever since the appearance Bokbot has been heavily focused on targeting financial institutions in the US even though they’re still gathering any data that they deem interesting such as credentials for online services.

Based on Fox-IT’s observation of the malware spread and the accompanied configs we find that North America seems to be Bokbot’s primary hunting ground while high infection counts have been seen in the following countries:

  • United States
  • Canada
  • India
  • Germany
  • Netherlands
  • France
  • United Kingdom
  • Italy
  • Japan

“I can name fingers and point names!” – Connecting the two groups

The two bots, on a binary level, do not show much similarity other than the fact that they’re both communicating over HTTPS and use RC4 in combination with LZMAT compression. But this wouldn’t be much of an attribution as it’s also a combination used in for example ZeuS Gameover, Citadel and Corebot v1.

The below tables provides a short summary of the similarities between the groups.

Connection Comment
Bot and project ID format The usage of projects and the bot ID generation are unique to these groups along with the format that this information is communicated to the C2.
Inject config The injects and redirection entries are very similar and the format haven’t been seen in any other malware family.
Reporting config The targeted URLs and “interesting” keywords are almost identical between the two.
Affiliations The two group share business affiliations with other crimeware groups.

Bot ID, URL pattern and project IDs

When both Neverquest and Bokbot communicate with their C2 servers, they have to identify themselves by sending their unique bot ID along with a project ID.

An example of the string that the server uses in order to identify a specific bot from its C2 communication is shown below:

bokbot_id_format

The placement of this string is of course different between the families, where Neverquest (in the latest version) placed it, encoded, in the Cookie header field. Older version of Neverquest sent this information in the URL. Bokbot on the other hand sends it in the URL as shown in a previous section.

One important difference is that Neverquest used a simple number for their project ID, 7, in the example above. Bokbot on the other hand is using a different, unknown format for its project ID. A theory is that this could be the CRC checksum of the project name to prevent any leakage of the number of projects or their names, but this is pure speculation.

Another difference is that Bokbot has implemented an 8 bit checksum that is calculated using the project ID and the bot ID. This checksum is then validated on the server side and if it doesn’t match, no commands will be returned.

To this date there has been a total of 20 projects over 25 build versions observed, numbers that keeps on growing.

Inject config – Dynamic redirect structure

The inject config not only contain web injects but also redirects. Bokbot supports both static redirects which redirects a static URL but also dynamic redirects which redirects a request based on a target matched using a regular expression.

The above example is a redirect attack from a Neverquest config. They use a regular expression to match on the requested URL. If it should match they will extract the name of the requested file along with its extension. The two strings are then used to construct a redirect URL controlled by the actors. Thereby, the $1 will be replaced with the file name and $2 will be replaced with the file extension.

bokbot_neverquest_target_format

How does this compare with Bokbot?

bokbot_target_format

Notice how the redirect URL contains $1 and $2, just as with Neverquest. This could of course be a coincidence but it should be mentioned that this is something that has only been observed in Neverquest and Bokbot.

Reporting config

This config was one of the very first things that hinted about a connection between the two groups. By comparing the configs it becomes quite clear that there is a big overlap in interesting keywords and URLs:

bokbot_reporting_targets

Neverquest is on the left and Bokbot on the right. Note that this is a simple string comparison between the configs which also includes URLs that are to be excluded from reporting.

“Guilt by association” – Affiliations

None of these groups are short on connections in the cybercrime underworld. It’s already mentioned that Neverquest had ties with Dyre, a group which by itself caused substantial financial losses. But it’s also important to take into account that Dyre didn’t completely go away after the group got dismantled but was rather replaced with TheTrick which gives a further hint of a connection.

Neverquest affil. Bokbot affil. Comment
Dyre TheTrick Neverquest downloads & executes Dyre
Bokbot downloads & executes TheTrick
TinyLoader TinyLoader Neverquest downloads & executes TinyLoader which downloads AbaddosPOS
Bokbot downloads & executes TinyLoader, additional payload remains unknown at this time
Chanitor Chanitor Neverquest utilizes Chanitor for distribution of Neverquest
Bokbot utilizes Chanitor for distribution of Bokbot, downloads SendSafe spam malware to older infections.
Geodo Bokbot utilizes Geodo for distributing Bokbot
Gozi-ISFB Bokbot utilizes Gozi-ISFB for distributing Bokbot

There are a few interesting observations with the above affiliations. The first is for the Chanitor affiliation.

When Bokbot was being distributed by Chanitor, an existing Bokbot infection that was running an older version than the one being distributed by Chanitor, would receive a download & execute command which pointed to the SendSafe spambot, used by the Chanitor group to send spam. Suggesting that they may have exchanged “infections for infections”.

The Bokbot affiliation with Geodo is something that cannot be linked to Neverquest, mostly due to the fact that Geodo has not been running its spam operation long enough to overlap with Neverquest.

The below graph show all the observed affiliations to date.

bokbot_attributions

Events over time

All of the above information have been collected over time during the development and tracking of Bokbot. The events and observations can be observed on the below timeline.

bokbot_event_timeline

The first occurrence of TheTrick being downloaded was in July 2017 but Bokbot has since been downloading TheTrick at different occasions.

At the end of December 2017 there was little Bokbot activity, likely due to the fact that it was holidays. It’s not uncommon for cybercriminals to decrease their activity during the turn of the year, supposedly everyone needs holidays, even cybercriminals. They did however push an inject config to some bots which targeted *.com with the goal of injecting Javascript to mine Monero cryptocurrency. As soon as an infected user visits a website with a .com top-level domain (TLD), the browser would start mining Monero for the Bokbot actors.  This was likely an attempt to passively monetize the bots while the actors was on holiday.

Bokbot remains active and shows no signs of slowing down. Fox-IT will continue to monitor these actors closely.

Introducing Team Foundation Server decryption tool

During penetration tests we sometimes encounter servers running software that use sensitive information as part of the underlying process, such as Microsoft’s Team Foundation Server (TFS). TFS can be used for developing code, version control and automatic deployment to target systems. This blogpost provides two tools to decrypt sensitive information that is stored in the TFS database.

Decrypting TFS secrets

Within Team Foundation Server (TFS), it is possible to automate the build, testing and deployment of new releases. With the use of variables it is possible to create a generic deployment process once and customize it per environment.1 Sometimes specific tasks need a set of credentials or other sensitive information and therefor TFS supports encrypted variables. With an encrypted variable the contents of the variables is encrypted in the database and not visible for the user of TFS.

TFS_Variable

However, with the correct amount of access rights to the database it is possible to decrypt the encrypted content. Sebastian Solnica wrote a blogpost about this, which can be read on the following link: https://lowleveldesign.org/2017/07/04/decrypting-tfs-secret-variables/

Fox-IT wrote a PowerShell script that uses the information mentioned in the blogpost. While the blogpost mainly focused on the decryption technique, the PowerShell script is built with usability in mind. The script will query all needed values and display the decrypted values. An example can be seen in the following screenshot:

tfs_decrypted

The script can be downloaded from Fox-IT’s Github repository: https://github.com/fox-it/Decrypt-TFSSecretVariables

It is also possible to use the script in Metasploit. Fox-IT wrote a post module that can be used through a meterpreter session. The result of the script can be seen in the screenshot below.

msf_tfs

There is a pull request pending and hopefully the module will be part of the Metasploit Framework soon. The pull request can be found here: https://github.com/rapid7/metasploit-framework/pull/9930

References

[1] https://docs.microsoft.com/en-us/vsts/build-release/concepts/definitions/release/variables?view=vsts&tabs=batch
[2] https://lowleveldesign.org/2017/07/04/decrypting-tfs-secret-variables

Introducing Orchestrator decryption tool

Researched and written by Donny Maasland and Rindert Kramer

Introduction

During penetration tests we sometimes encounter servers running software that use sensitive information as part of the underlying process, such as Microsoft’s System Center Orchestrator.
According to Microsoft, Orchestrator is a workflow management solution for data centers and can be used to automate the creation, monitoring and deployment of resources in your environment.1 This blogpost covers the encryption aspect of Orchestrator and new tools to decrypt sensitive information that is stored in the Orchestrator database.

Orchestrator, variables, encryption and SQL

In Orchestrator, it is possible to create variables that can be used in runbooks. One of the possibilities is to store credentials in these variables. These variables can then be used to authenticate with other systems. Runbooks can use these variables to create an authenticated session towards the target system and run all the steps that are defined in the runbook in the context of the credentials that are specified in the variable.

Information, such as passwords, that is of a sensitive nature can be encrypted by using encrypted variables. The contents of these variables are stored encrypted in the database when they are created and are decrypted when they are used in the runbooks. The picture below displays the dialog to create an encrypted variable.

dialog

Orchestrator uses the internal encryption functionality of Microsoft SQL server2 (MSSQL). The decryption keys are stored in the SYS database and have to be loaded in to the SQL session in order to decrypt data.

To decypt the data, we need the encrypted content first. The following query returns the encrypted content:

SELECT VARIABLES.value, objects.Name FROM VARIABLES INNER JOIN OBJECTS ON OBJECTS.UniqueID = VARIABLES.UniqueID;

If there are secret variables stored in the database, this will result in encrypted data, such as:
\`d.T.~De/00F04DA615688A4C96C2891105226AE90100000059A187C285E8AC6C1090F48D0BFD2775165F9558EAE37729DA43BE92AD133CF697D2C5CC1E6E27E534754099780A0362C794C95F3747A1E65E869D2D43EC3597\`d.T.~De/

The data between \`d.T.~De/ is the data we are interested in, which leaves us with the following string:
00F04DA615688A4C96C2891105226AE90100000059A187C285E8AC6C1090F48D0BFD2775165F9558EAE37729DA43BE92AD133CF697D2C5CC1E6E27E534754099780A0362C794C95F3747A1E65E869D2D43EC3597
Please note that the \`d.T.~De/ value might differ per data type.

Since this data is encrypted, the decryption key needs to be loaded in the SQL session. To establish this, we open an SQL session and run the following query:

OPEN SYMMETRIC KEY ORCHESTRATOR_SYM_KEY DECRYPTION BY ASYMMETRIC KEY ORCHESTRATOR_ASYM_KEY;

This will load the decryption key into the SQL session.

Now we run this string against the decryptbykey function in MSSQL3 to decrypt the content with the encryption key that was loaded earlier in the SQL session. If successful, this will result in a varbinary object that we need to convert to nvarchar for human readable output.

The complete SQL query will look like this:

SELECT convert(nvarchar, decryptbykey(0x00F04DA615688A4C96C2891105226AE90100000059A187C285E8AC6C1090F48D0BFD2775165F9558EAE37729DA43BE92AD133CF697D2C5CC1E6E27E534754099780A0362C794C95F3747A1E65E869D2D43EC3597));

Executing this query will return the unencrypted value of the variable, as can be seen in the following screenshot.
orch_result_sql

Automating the process

Fox-IT created a script that automates this process. The script queries the secrets and decrypts them automatically. The result of the script can be seen in the screenshot below.
orch_tool_result

The script can be downloaded from Fox-IT’s Github repository: https://github.com/fox-it/Decrypt-OrchestratorSecretVariables

Fox-IT also wrote a Metasploit post module to run this script through a meterpreter.
msf_output

The Metasploit module supports integrated login. Optionally, it is possible to use MSSQL authentication by specifying the username and password parameters. By default, the script will use the ‘Orchestrator’ database, but it is also possible to specify another database with the database parameter. Fox-IT did a pull request to add this module to Metasploit, so hopefully the module will be available soon. The pull request can be found here: https://github.com/rapid7/metasploit-framework/pull/9929

References

[1] https://technet.microsoft.com/en-us/library/hh237242(v=sc.12).aspx
[2] https://technet.microsoft.com/en-us/library/hh912316(v=sc.12).aspx
[3] https://docs.microsoft.com/en-us/sql/t-sql/functions/decryptbykey-transact-sql?view=sql-server-2017

Escalating privileges with ACLs in Active Directory

Researched and written by Rindert Kramer and Dirk-jan Mollema

Introduction

During internal penetration tests, it happens quite often that we manage to obtain Domain Administrative access within a few hours. Contributing to this are insufficient system hardening and the use of insecure Active Directory defaults. In such scenarios publicly available tools help in finding and exploiting these issues and often result in obtaining domain administrative privileges. This blogpost describes a scenario where our standard attack methods did not work and where we had to dig deeper in order to gain high privileges in the domain. We describe more advanced privilege escalation attacks using Access Control Lists and introduce a new tool called Invoke-Aclpwn and an extension to ntlmrelayx that automate the steps for this advanced attack.

AD, ACLs and ACEs

As organizations become more mature and aware when it comes to cyber security, we have to dig deeper in order to escalate our privileges within an Active Directory (AD) domain. Enumeration is key in these kind of scenarios. Often overlooked are the Access Control Lists (ACL) in AD.An ACL is a set of rules that define which entities have which permissions on a specific AD object. These objects can be user accounts, groups, computer accounts, the domain itself and many more. The ACL can be configured on an individual object such as a user account, but can also be configured on an Organizational Unit (OU), which is like a directory within AD. The main advantage of configuring the ACL on an OU is that when configured correctly, all descendent objects will inherit the ACL.The ACL of the Organizational Unit (OU) wherein the objects reside, contains an Access Control Entry (ACE) that defines the identity and the corresponding permissions that are applied on the OU and/or descending objects.The identity that is specified in the ACE does not necessarily need to be the user account itself; it is a common practice to apply permissions to AD security groups. By adding the user account as a member of this security group, the user account is granted the permissions that are configured within the ACE, because the user is a member of that security group.

Group memberships within AD are applied recursively. Let’s say that we have three groups:

  • Group_A
    • Group_B
      • Group_C

Group_C is a member of Group_B which itself is a member of Group_A. When we add Bob as a member of Group_C, Bob will not only be a member of Group_C, but also be an indirect member of Group_B and Group_A. That means that when access to an object or a resource is granted to Group_A, Bob will also have access to that specific resource. This resource can be an NTFS file share, printer or an AD object, such as a user, computer, group or even the domain itself.
Providing permissions and access rights with AD security groups is a great way for maintaining and managing (access to) IT infrastructure. However, it may also lead to potential security risks when groups are nested too often. As written, a user account will inherit all permissions to resources that are set on the group of which the user is a (direct or indirect) member. If Group_A is granted access to modify the domain object in AD, it is quite trivial to discover that Bob inherited these permissions. However, if the user is a direct member of only 1 group and that group is indirectly a member of 50 other groups, it will take much more effort to discover these inherited permissions.

Escalating privileges in AD with Exchange

During a recent penetration test, we managed to obtain a user account that was a member of the Organization Management security group. This group is created when Exchange is installed and provided access to Exchange-related activities. Besides access to these Exchange settings, it also allows its members to modify the group membership of other Exchange security groups, such as the Exchange Trusted Subsystem security group. This group is a member of the Exchange Windows Permissions security group.

grpMembershp

By default, the Exchange Windows Permissions security group has writeDACL permission on the domain object of the domain where Exchange was installed. 1

domain_permission

The writeDACL permissions allows an identity to modify permissions on the designated object (in other words: modify the ACL) which means that by being a member of the Organization Management group we were able to escalate out privileges to that of a domain administrator.
To exploit this, we added our user account that we obtained earlier to the Exchange Trusted Subsystem group. We logged on again (because security group memberships are only loaded during login) and now we were a member of the Exchange Trusted Subsystem group and the Exchange Windows Permission group, which allowed us to modify the ACL of the domain.

If you have access to modify the ACL of an AD object, you can assign permissions to an identity that allows them to write to a certain attribute, such as the attribute that contains the telephone number. Besides assigning read/write permissions to these kinds of attributes, it is also possible to assign permissions to extended rights. These rights are predefined tasks, such as the right of changing a password, sending email to a mailbox and many more2. It is also possible to add any given account as a replication partner of the domain by applying the following extended rights:

  • Replicating Directory Changes
  • Replicating Directory Changes All

When we set these permissions for our user account, we were able to request the password hash of any user in the domain, including that of the krbtgt account of the domain. More information about this privilege escalation technique can be found on the following GitHub page: https://github.com/gdedrouas/Exchange-AD-Privesc

Obtaining a user account that is a member of the Organization Management group is not something that happens quite often. Nonetheless, this technique can be used on a broader basis. It is possible that the Organization Management group is managed by another group. That group may be managed by another group, et cetera. That means that it is possible that there is a chain throughout the domain that is difficult to discover but, if correlated correctly, might lead to full compromise of the domain.

To help exploit this chain of security risks, Fox-IT wrote two tools. The first tool is written in PowerShell and can be run within or outside an AD environment. The second tool is an extension to the ntlmrelayx tool. This extension allows the attacker to relay identities (user accounts and computer accounts) to Active Directory and modify the ACL of the domain object.

Invoke-ACLPwn

Invoke-ACLPwn is a Powershell script that is designed to run with integrated credentials as well as with specified credentials. The tool works by creating an export with SharpHound3 of all ACLs in the domain as well as the group membership of the user account that the tool is running under. If the user does not already have writeDACL permissions on the domain object, the tool will enumerate all ACEs of the ACL of the domain. Every identity in an ACE has an ACL of its own, which is added to the enumeration queue. If the identity is a group and the group has members, every group member is added to the enumeration queue as well. As you can imagine, this takes some time to enumerate but could end up with a chain to obtain writeDACL permission on the domain object.

help

When the chain has been calculated, the script will then start to exploit every step in the chain:

  • The user is added to the necessary groups
  • Two ACEs are added to the ACL of the domain object:
    • Replicating Directory Changes
    • Replicating Directory Changes All
  • Optionally, Mimkatz’ DCSync feature is invoked and the hash of the given user account is requested. By default the krbtgt account will be used.

After the exploitation is done, the script will remove the group memberships that were added during exploitation as well as the ACEs in the ACL of the domain object.

To test the script, we created 26 security groups. Every group was member of another group (testgroup_a was a member of testgroup_b, which itself was a member of testgroup_c, et cetera, up until testgroup_z.)
The security group testgroup_z had the permission to modify the membership of the Organization Management security group. As written earlier, this group had the permission to modify the group membership of the Exchange Trusted Subsystem security group. Being a member of this group will give you the permission to modify the ACL of the domain object in Active Directory.

We now had a chain of 31 links:

  • Indirect member of 26 security groups
  • Permission to modify the group membership of the Organization Management security group
  • Membership of the Organization Management
  • Permission to modify the group membership of the Exchange Trusted Subsystem security group
  • Membership of the Exchange Trusted Subsystem and the Exchange Windows Permission security groups

The result of the tool can be seen in the following screenshot:

exploit

Please note that in this example we used the ACL configuration that was configured
during the installation of Exchange. However, the tool does not rely on Exchange
or any other product to find and exploit a chain.

Currently, only the writeDACL permission on the domain object is enumerated
and exploited. There are other types of access rights such as owner, writeOwner, genericAll, et cetera, that can be exploited on other object as well.
These access rights are explained in depth in this whitepaper by the BloodHound team.
Updates to the tool that also exploit these privileges will be developed and released in the future.
The Invoke-ACLPwn tool can be downloaded from our GitHub here: https://github.com/fox-it/Invoke-ACLPwn

NTLMRelayx

Last year we wrote about new additions to ntlmrelayx allowing relaying to LDAP, which allows for domain enumeration and escalation to Domain Admin by adding a new user to the Directory. Previously, the LDAP attack in ntlmrelayx would check if the relayed account was a member of the Domain Admins or Enterprise Admins group, and escalate privileges if this was the case. It did this by adding a new user to the Domain and adding this user to the Domain Admins group.
While this works, this does not take into account any special privileges that a relayed user might have. With the research presented in this post, we introduce a new attack method in ntlmrelayx. This attack involves first requesting the ACLs of important Domain objects, which are then parsed from their binary format into structures the tool can understand, after which the permissions of the relayed account are enumerated.
This takes into account all the groups the relayed account is a member of (including recursive group memberships). Once the privileges are enumerated, ntlmrelayx will check if the user has high enough privileges to allow for a privilege escalation of either a new or an existing user.
For this privilege escalation there are two different attacks. The first attack is called the ACL attack in which the ACL on the Domain object is modified and a user under the attackers control is granted Replication-Get-Changes-All privileges on the domain, which allows for using DCSync as desribed in the previous sections. If modifying the domain ACL is not possible, the access to add members to several high privilege groups in the domain is considered for a Group attack:

  • Enterprise Admins
  • Domain Admins
  • Backup Operators (who can back up critical files on the Domain Controller)
  • Account Operators (who have control over almost all groups in the domain)

If an existing user was specified using the --escalate-user flag, this user will be given the Replication privileges if an ACL attack can be performed, and added to a high-privilege group if a Group attack is used. If no existing user is specified, the options to create new users are considered. This can either be in the Users container (the default place for user accounts), or in an OrganizationalUnit for which control was delegated to for example IT department members.

One may have noticed that we mentioned relayed accounts here instead of relayed users. This is because the attack also works against computer accounts that have high privileges. An example for such an account is the computer account of an Exchange server, which is a member of the Exchange Windows Permissions group in the default configuration. If an attacker is in a position to convince the Exchange server to authenticate to the attacker’s machine, for example by using mitm6 for a network level attack, privileges can be instantly escalated to Domain Admin.

Relaying Exchange account

The NTDS.dit hashes can now be dumped by using impacket’s secretsdump.py or with Mimikatz:

secretsdump-2

Similarly if an attacker has Administrative privileges on the Exchange Server, it is possible to escalate privilege in the domain without the need to dump any passwords or machine account hashes from the system.
Connecting to the attacker from the NT Authority\SYSTEM perspective and authenticating with NTLM is sufficient to authenticate to LDAP. The screenshot below shows the PowerShell function Invoke-Webrequest being called with psexec.py, which will run from a SYSTEM perspective. The flag -UseDefaultCredentials will enable automatic authentication with NTLM.

psexec-relay

The 404 error here is expected as ntlmrelayx.py serves a 404 page if the relaying attack is complete

It should be noted that relaying attacks against LDAP are possible in the default configuration of Active Directory, since LDAP signing, which partially mitigates this attack, is disabled by default. Even if LDAP signing is enabled, it is still possible to relay to LDAPS (LDAP over SSL/TLS) since LDAPS is considered a signed channel. The only mitigation for this is enabling channel binding for LDAP in the registry.
To get the new features in ntlmrelayx, simply update to the latest version of impacket from GitHub: https://github.com/CoreSecurity/impacket

Recommendation

As for mitigation, Fox-IT has a few recommendations.

Remove dangerous ACLs
Check for dangerous ACLs with tools such as Bloodhound. 3
Bloodhound can make an export of all ACLs in the domain which helps identifying
dangerous ACLs.

Remove writeDACL permission for the Exchange Windows Permissions group
Remove the writeDACL permission for the Exchange Windows Permissions group. The following GitHub page contains a PowerShell script which can assist with this: https://github.com/gdedrouas/Exchange-AD-Privesc

Monitor security groups
Monitor (the membership of) security groups that can have a high impact on the domain, such as the Exchange Trusted Subsystem and the Exchange Windows Permissions.

Audit and monitor changes to the ACL.
Audit changes to the ACL of the domain. If not done already, it may be necessary to modify the domain controller policy. More information about this can be found on the following TechNet article: https://blogs.technet.microsoft.com/canitpro/2017/03/29/step-by-step-enabling-advanced-security-audit-policy-via-ds-access/

When the ACL of the domain object is modified, an event will be created with event ID 5136. The Windows event log can be queried with PowerShell, so here is a one-liner to get all events from the Security event log with ID 5136:

Get-WinEvent -FilterHashtable @{logname='security'; id=5136}

This event contains the account name and the ACL in a Security Descriptor Definition Language (SDDL) format.

event

Since this is unreadable for humans, there is a PowerShell cmdlet in Windows 10,
ConvertFrom-SDDL4, which converts the SDDL string into a more readable ACL object.

sddl

If the server runs Windows Server 2016 as operating system, it is also possible to see the original and modified descriptors. For more information: https://docs.microsoft.com/en-us/windows/security/threat-protection/auditing/event-4715

With this information you should be able to start an investigation to discover what was modified, when that happened and the reason behind that.

References

[1] https://technet.microsoft.com/en-us/library/ee681663.aspx
[2] https://technet.microsoft.com/en-us/library/ff405676.aspx
[3] https://github.com/BloodHoundAD/SharpHound
[4] https://docs.microsoft.com/en-us/powershell/module/Microsoft.powershell.utility/convertfrom-sddlstring

Compromising Citrix ShareFile on-premise via 7 chained vulnerabilities

A while ago we investigated a setup of Citrix ShareFile with an on-premise StorageZone controller. ShareFile is a file sync and sharing solution aimed at enterprises. While there are versions of ShareFile that are fully managed in the cloud, Citrix offers a hybrid version where the data is stored on-premise via StorageZone controllers. This blog describes how Fox-IT identified several vulnerabilities, which together allowed any account to (from the internet) access any file stored within ShareFile. Fox-IT disclosed these vulnerabilities to Citrix, which mitigated them via updates to their cloud platform. The vulnerabilities identified were all present in the StorageZone controller component, and thus cloud-only deployments were not affected. According to Citrix, several fortune-500 enterprises and organisations in the government, tech, healthcare, banking and critical infrastructure sectors use ShareFile (either fully in the Cloud or with an on-premise component).

Sharefile

Gaining initial access

After mapping the application surface and the flows, we decided to investigate the upload flow and the connection between the cloud and on-premise components of ShareFile. There are two main ways to upload files to ShareFile: one based on HTML5 and one based on a Java Applet. In the following examples we are using the Java based uploader. All requests are configured to go through Burp, our go-to tool for assessing web applications.
When an upload is initialized, a request is posted to the ShareFile cloud component, which is hosted at name.sharefile.eu (where name is the name of the company using the solution):

Initialize upload

We can see the request contains information about the upload, among which is the filename, the size (in bytes), the tool used to upload (in this case the Java uploader) and whether we want to unzip the upload (more about that later). The response to this request is as follows:

Initialize upload response

In this response we see two different upload URLs. Both use the URL prefix (which is redacted here) that points to the address of the on-premise StorageZone controller. The cloud component thus generates a URL that is used to upload the files to the on-premise component.

The first URL is the ChunkUri, to which the individual chunks are uploaded. When the filetransfer is complete, the FinishUri is used to finalize the upload on the server. In both URLs we see the parameters that we submitted in the request such as the filename, file size, et cetera. It also contains an uploadid which is used to identify the upload. Lastly we see a h= parameter, followed by a base64 encoded hash. This hash is used to verify that the parameters in the URL have not been modified.

The unzip parameter immediately drew our attention. As visible in the screenshot below, the uploader offers the user the option to automatically extract archives (such as .zip files) when they are uploaded.

Extract feature

A common mistake made when extracting zip files is not correctly validating the path in the zip file. By using a relative path it may be possible to traverse to a different directory than intended by the script. This kind of vulnerability is known as a directory traversal or path traversal.

The following python code creates a special zip file called out.zip, which contains two files, one of which has a relative path.

import sys, zipfile
#the name of the zip file to generate
zf = zipfile.ZipFile('out.zip', 'w')
#the name of the malicious file that will overwrite the origial file (must exist on disk)
fname = 'xxe_oob.xml'
#destination path of the file
zf.write(fname, '../../../../testbestand_fox.tmp')
#random extra file (not required)
#example: dd if=/dev/urandom of=test.file bs=1024 count=600
fname = 'test.file'
zf.write(fname, 'tfile')

When we upload this file to ShareFile, we get the following message:

ERROR: Unhandled exception in upload-threaded-3.aspx - 'Access to the path '\\company.internal\data\testbestand_fox.tmp' is denied.'

This indicates that the StorageZone controller attempted to extract our file to a directory for which we lacked permissions, but that we were able to successfully change the directory to which the file was extracted. This vulnerability can be used to write user controlled files to arbitrary directories, provided the StorageZone controller has privileges to write to those directories. Imagine the default extraction path would be c:\appdata\citrix\sharefile\temp\ and we want to write to c:\appdata\citrix\sharefile\storage\subdirectory\ we can add a file with the name ../storage/subdirectory/filename.txt which will then be written to the target directory. The ../ part indicates that the Operating System should go one directory higher in the directory tree and use the rest of the path from that location.

Vulnerability 1: Path traversal in archive extraction

From arbitrary write to arbitrary read

While the ability to write arbitrary files to locations within the storage directories is a high-risk vulnerability, the impact of this vulnerability depends on how the files on disk are used by the application and if there are sufficient integrity checks on those files. To determine the full impact of being able to write files to the disk we decided to look at the way the StorageZone controller works. There are three main folders in which interesting data is stored:

  • files
  • persistenstorage
  • tokens

The first folder, files, is used to store temporary data related to uploads. Files already uploaded to ShareFile are stored in the persistentstorage directory. Lastly the tokens folder contains data related to tokens which are used to control the downloads of files.

When a new upload was initialized, the URLs contained a parameter called uploadid. As the name already indicates this is the ID assigned to the upload, in this case it is rsu-2351e6ffe2fc462492d0501414479b95. In the files directory, there are folders for each upload matching with this ID.

In each of these folders there is a file called info.txt, which contains information about our upload:

Info.txt

In the info.txt file we see several parameters that we saw previously, such as the uploadid, the file name, the file size (13 bytes), as well as some parameters that are new. At the end, we see a 32 character long uppercase string, which hints at an integrity hash for the data.
We see two other IDs, fi591ac5-9cd0-4eb7-a5e9-e5e28a7faa90 and fo9252b1-1f49-4024-aec4-6fe0c27ce1e6, which correspond with the file ID for the upload and folder ID to which the file is uploaded respectively.

After trying to figure out for a while what kind of hashing algorithm was used for the integrity check of this file, it turned out that it is a simple md5 hash of the rest of the data in the info.txt file. The twist here is that the data is encoded with UTF-16-LE, which is default for Unicode strings in Windows.

Armed with this knowledge we can write a simple python script which calculates the correct hash over a modified info.txt file and write this back to disk:

import md5
with open('info_modified.txt','r') as infile:
instr = infile.read().strip().split('|')
instr2 = u'|'.join(instr[:-1])
outhash = md5.new(instr2.encode('utf-16-le')).hexdigest().upper()
with open('info_out.txt','w') as outfile:
outfile.write('%s|%s' % (instr2, outhash))

Here we find our second vulnerability: the info.txt file is not verified for integrity using a secret only known by the application, but is only validated with an md5 hash against corruption. This gives an attacker that can write to the storage folders the possibility to alter the upload information.

Vulnerability 2: Integrity of data files (info.txt) not verified

Since our previous vulnerability enabled us to write files to arbitrary locations, we can upload our own info.txt and thus modify the upload information.
It turns out that when uploading data, the file ID fi591ac5-9cd0-4eb7-a5e9-e5e28a7faa90 is used as temporary name for the file. The data that is uploaded is written to this file, and when the upload is finilized this file is added to the users ShareFile account. We are going to attempt another path traversal here. Using the script above, we modify the file ID to a different filename to attempt to extract a test file called secret.txt which we placed in the files directory (one directory above the regular location of the temporary file). The (somewhat redacted) info.txt then becomes:

modified info.txt

When we subsequently post to the upload-threaded-3.aspx page to finalize the upload, we are presented with the following descriptive error:

File size does not match

Apparently, the filesize of the secret.txt file we are trying to extract is 14 bytes instead of 13 as the modified info.txt indicated. We can upload a new info.txt file which does have the correct filesize, and the secret.txt file is succesfully added to our ShareFile account:

File extraction POC

And thus we’ve successfully exploited a second path traversal, which is in the info.txt file.

Vulnerability 3: Path traversal in info.txt data

By now we’ve turned our ability to write arbitrary files to the system into the ability to read arbitrary files, as long as we do know the filename. It should be noted that all the information in the info.txt file can be found by investigating traffic in the web interface, and thus an attacker does not need to have an info.txt file to perform this attack.

Investigating file downloads

So far, we’ve only looked at uploading new files. The downloading of files is also controlled by the ShareFile cloud component, which instructs the StorageZone controller to serve the frequested files. A typical download link looks as follows:

Download URL

Here we see the dt parameter which contains the download token. Additionally there is a h parameter which contains a HMAC of the rest of the URL, to prove to the StorageZone controller that we are authorized to download this file.

The information for the download token is stored in an XML file in the tokens directory. An example file is shown below:

<!--?xml version="1.0" encoding="utf-8"?--><!--?xml version="1.0" encoding="utf-8"?--><?xml version="1.0" encoding="utf-8"?>
<ShareFileDownloadInfo authSignature="866f075b373968fcd2ec057c3a92d4332c8f3060" authTimestamp="636343218053146994">
<DownloadTokenID>dt6bbd1e278a634e1bbde9b94ff8460b24</DownloadTokenID>
<RequestType>single</RequestType>
<BaseUrl>https://redacted.sf-api.eu/</BaseUrl>
<ErrorUrl>https://redacted.sf-api.eu//error.aspx?type=storagecenter-downloadprep</ErrorUrl>
<StorageBasePath>\\s3\sf-eu-1\;</StorageBasePath>
<BatchID>dt6bbd1e278a634e1bbde9b94ff8460b24</BatchID>
<ZipFileName>tfile</ZipFileName>
<UserAgent>Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0</UserAgent>
<Metadata>
<Item key="operatingsystem" value="Linux" />
</Metadata>
<IrmEnabled>false</IrmEnabled>
<IrmPolicyServerUrl />
<IrmAccessId />
<IrmAccessKey />
<Items>
<File name="testfile" path="a4ea881a-a4d5-433a-fa44-41acd5ed5a5f\0f\0f\fi0f0f2e_3477_4647_9cdd_e89758c21c37" size="61" id="" />
</Items>
<Log>
<EventID>fif11465-ba81-8b77-7dd9-4256bc375017</EventID>
<UserID>c7add7af-91ac-4331-b48a-0aeed4a58687</UserID>
<OwnerID>c7add7af-91ac-4331-b48a-0aeed4a58687</OwnerID>
<AccountID>a4ea881a-a4d5-433a-fa44-41acd5ed5a5f</AccountID>
<UserEmailAddress>fox-it@redacted</UserEmailAddress>
<Name>tfile</Name>
<FileCount>1</FileCount>
<AdditionalInfo>fif11465-ba81-8b77-7dd9-4256bc375017</AdditionalInfo>
<FolderID>foh160ab-aa5a-4e43-96fd-e41caed36cea</FolderID>
<ParentID>foh160ab-aa5a-4e43-96fd-e41caed36cea</ParentID>
<Path>/root/a4ea881a-a4d5-433a-fa44-41acd5ed5a5f/foh160ab-aa5a-4e43-96fd-e41caed36cea</Path>
<IncrementDownloadCount>false</IncrementDownloadCount>
<ShareID />
</Log>
</ShareFileDownloadInfo>

Two things are of interest here. The first is the path property of the File element, which specifies which file the token is valid for. The path starts with the ID a4ea881a-a4d5-433a-fa44-41acd5ed5a5f which is the ShareFile AccountID, which is unique per ShareFile instance. Then the second ID fi0f0f2e_3477_4647_9cdd_e89758c21c37 is unique for the file (hence the fi prefix), with two 0f subdirectories for the first characters of the ID (presumably to prevent huge folder listings).

The second noteworthy point is the authSignature property on the ShareFileDownloadInfo element. This suggests that the XML is signed to ensure its authenticity, and to prevent malicious tokens from being downloaded.

At this point we started looking at the StorageZone controller software itself. Since it is a program written in .NET and running under IIS, it is trivial to decompile the binaries with toos such as JustDecompile. While we obtained the StorageZone controller binaries from the server the software was running on, Citrix also offers this component as a download on their website.

In the decompiled code, the functions responsible for verifying the token can quickly be found. The feature to have XML files with a signature is called AuthenticatedXml by Citrix. In the code we find that a static key is used to verify the integrity of the XML file (which is the same for all StorageZone controllers):

Static MAC secret

Vulnerability 4: Token XML files integrity integrity not verified

During our research we of course attempted to simply edit the XML file without changing the signature, and it turned out that it is not nessecary to calculate the signature as an attacker, since the application simply tells you what correct signature is if it doesn’t match:

Signature disclosure

Vulnerability 5: Debug information disclosure

Furthermore, when we looked at the code which calculates the signature, it turned out that the signature is calculated by prepending the secret to the data and calculating a sha1 hash over this. This makes the signature potentially vulnerable to a hash length extension attack, though we did not verify this in the time available.

Hashing of secret prepended

Even though we didn’t use it in the attack chain, it turned out that the XML files were also vulnerable to XML External Entity (XXE) injection:

XXE error

Vulnerability 6 (not used in the chain): Token XML files vulnerable to XXE

In summary, it turns out that the token files offer another avenue to download arbitrary files from ShareFile. Additionally, the integrity of these files is insufficiently verified to protect against attackers. Unlike the previously described method which altered the upload data, this method will also decrypt encrypted files if encrypted storage is enabled within ShareFile.

Getting tokens and files

At this point we are able to write arbitrary files to any directory we want and to download files if the path is known. The file path however consists of random IDs which cannot be guessed in a realistic timeframe. It is thus still necessary for an attacker to find a method to enumerate the files stored in ShareFile and their corresponding IDs.

For this last step, we go back to the unzip functionality. The code responsible for extracting the zip file is (partially) shown below.

Unzip code

What we see here is that the code creates a temporary directory to which it extracts the files from the archive. The uploadId parameter is used here in the name of the temporary directory. Since we do not see any validation taking place of this path, this operation is possibly vulnerable to yet another path traversal. Earlier we saw that the uploadId parameter is submitted in the URL when uploading files, but the URL also contains a HMAC, which makes modifying this parameter seemingly impossible:

HMAC Url

However, let’s have a look at the implementation first. The request initially passes through the ValidateRequest function below:

Validation part 1

Which then passes it to the second validation function:

Validation part 2

What happens here is that the h parameter is extracted from the request, which is then used to verify all parameters in the url before the h parameter. Thus any parameters following the h in the URL are completely unverified!

So what happens when we add another parameter after the HMAC? When we modify the URL as follows:

uploadid-double.png

We get the following message:

{"error":true,"errorMessage":"upload-threaded-2.aspx: ID='rsu-becc299a4b9c421ca024dec2b4de7376,foxtest' Unrecognized Upload ID.","errorCode":605}

So what happens here? Since the uploadid parameter is specified multiple times, IIS concatenates the values which are separated with a comma. Only the first uploadid parameter is verified by the HMAC, since it operates on the query string instead of the individual parameter values, and only verifies the portion of the string before the h parameter. This type of vulnerability is known as HTTP Parameter Polution.

Vulnerability 7: Incorrectly implemented URL verification (parameter pollution)

Looking at the upload logic again, the code calls the function UploadLogic.RecursiveIteratePath after the files are extracted to the temporary directory, which recursively adds all the files it can find to the ShareFile account of the attacker (some code was cut for readability):

Recursive iteration

To exploit this, we need to do the following:

  • Create a directory called rsu-becc299a4b9c421ca024dec2b4de7376, in the files directory.
  • Upload an info.txt file to this directory.
  • Create a temporary directory called ulz-rsu-becc299a4b9c421ca024dec2b4de7376,.
  • Perform an upload with an added uploadid parameter pointing us to the tokens directory.

The creation of directories can be performed with the directory traversal that was initially identified in the unzip operation, since this will create any non-existing directories. To perform the final step and exploit the third path traversal, we post the following URL:

Upload ID path traversal

Side note: we use tokens_backup here because we didn’t want to touch the original tokens directory.

Which returns the following result that indicates success:

Upload ID path traversal result

Going back to our ShareFile account, we now have hundreds of XML files with valid download tokens available, which all link to files stored within ShareFile.

Download tokens

Vulnerability 8: Path traversal in upload ID

We can download these files by modifying the path in our own download token files for which we have the authorized download URL.
The only side effect is that adding files to the attackers account this way also recursively deletes all files and folders in the temporary directory. By traversing the path to the persistentstorage directory it is thus also possible to delete all files stored in the ShareFile instance.

Conclusion

By abusing a chain of correlated vulnerabilities it was possible for an attacker with any account allowing file uploads to access all files stored by the ShareFile on-premise StorageZone controller.

Based on our research that was performed for a client, Fox-IT reported the following vulnerabilities to Citrix on July 4th 2017:

  1. Path traversal in archive extraction
  2. Integrity of data files (info.txt) not verified
  3. Path traversal in info.txt data
  4. Token XML files integrity integrity not verified
  5. Debug information disclosure (authentication signatures, hashes, file size, network paths)
  6. Token XML files vulnerable to XXE
  7. Incorrectly implemented URL verification (parameter pollution)
  8. Path traversal in upload ID

Citrix was quick with following up on the issues and rolling out mitigations by disabling the unzip functionality in the cloud component of ShareFile. While Fox-IT identified several major organisations and enterprises that use ShareFile, it is unknown if they were using the hybrid setup in a vulnerable configuration. Therefor, the number of affected installations and if these issues were abused is unknown.

Disclosure timeline

  • July 4th 2017: Fox-IT reports all vulnerabilities to Citrix
  • July 7th 2017: Citrix confirms they are able to reproduce vulnerability 1
  • July 11th 2017: Citrix confirms they are able to reproduce the majority of the other vulnerabilities
  • July 12th 2017: Citrix deploys an initial mitigation for vulnerability 1, breaking the attack chain. Citrix informs us the remaining findings will be fixed on a later date as defense-in-depth measures
  • October 31st 2017: Citrix deploys additional fixes to the cloud-based ShareFile components
  • April 6th 2018: Disclosure

CVE: To be assigned

mitm6 – compromising IPv4 networks via IPv6

While IPv6 adoption is increasing on the internet, company networks that use IPv6 internally are quite rare. However, most companies are unaware that while IPv6 might not be actively in use, all Windows versions since Windows Vista (including server variants) have IPv6 enabled and prefer it over IPv4. In this blog, an attack is presented that abuses the default IPv6 configuration in Windows networks to spoof DNS replies by acting as a malicious DNS server and redirect traffic to an attacker specified endpoint. In the second phase of this attack, a new method is outlined to exploit the (infamous) Windows Proxy Auto Discovery (WPAD) feature in order to relay credentials and authenticate to various services within the network. The tool Fox-IT created for this is called mitm6, and is available from the Fox-IT GitHub.

IPv6 attacks

Similar to the slow IPv6 adoption, resources about abusing IPv6 are much less prevalent than those describing IPv4 pentesting techniques. While every book and course mentions things such as ARP spoofing, IPv6 is rarely touched on and the tools available to test or abuse IPv6 configurations are limited. The THC IPV6 Attack toolkit is one of the available tools, and was an inspiration for mitm6. The attack described in this blog is a partial version of the SLAAC attack, which was first described by in 2011 by Alex Waters from the Infosec institute. The SLAAC attack sets up various services to man-in-the-middle all traffic in the network by setting up a rogue IPv6 router. The setup of this attack was later automated with a tool by Neohapsis called suddensix.

The downside of the SLAAC attack is that it attempts to create an IPv6 overlay network over the existing IPv4 network for all devices present. This is hardly a desired situation in a penetration test since this rapidly destabilizes the network. Additionally the attack requires quite a few external packages and services to work. mitm6 is a tool which focusses on an easy to setup solution that selectively attacks hosts and spoofs DNS replies, while minimizing the impact on the network’s regular operation. The result is a python script which requires almost no configuration to set up, and gets the attack running in seconds. When the attack is stopped, the network reverts itself to it’s previous state within minutes due to the tweaked timeouts set in the tool.

The mitm6 attack

Attack phase 1 – Primary DNS takeover

mitm6 starts with listening on the primary interface of the attacker machine for Windows clients requesting an IPv6 configuration via DHCPv6. By default every Windows machine since Windows Vista will request this configuration regularly. This can be seen in a packet capture from Wireshark:

dhcpv6_cropped

mitm6 will reply to those DHCPv6 requests, assigning the victim an IPv6 address within the link-local range. While in an actual IPv6 network these addresses are auto-assigned by the hosts themselves and do not need to be configured by a DHCP server, this gives us the opportunity to set the attackers IP as the default IPv6 DNS server for the victims. It should be noted that mitm6 currently only targets Windows based operating systems, since other operating systems like macOS and Linux do not use DHCPv6 for DNS server assignment.

mitm6 does not advertise itself as a gateway, and thus hosts will not actually attempt to communicate with IPv6 hosts outside their local network segment or VLAN. This limits the impact on the network as mitm6 does not attempt to man-in-the-middle all traffic in the network, but instead selectively spoofs hosts (the domain which is filtered on can be specified when running mitm6).

The screenshot below shows mitm6 in action. The tool automatically detects the IP configuration of the attacker machine and replies to DHCPv6 requests sent by clients in the network with a DHCPv6 reply containing the attacker’s IP as DNS server. Optionally it will periodically send Router Advertisment (RA) messages to alert client that there is an IPv6 network in place and that clients should request an IPv6 adddress via DHCPv6. This will in some cases speed up the attack but is not required for the attack to work, making it possible to execute this attack on networks that have protection against the SLAAC attack with features such as RA Guard.

mitm6_cropped

Attack phase 2 – DNS spoofing

On the victim machine we see that our server is configured as DNS server. Due to the preference of Windows regarding IP protocols, the IPv6 DNS server will be preferred to the IPv4 DNS server. The IPv6 DNS server will be used to query both for A (IPv4) and AAAA (IPv6) records.

ipconfig_fixed

Now our next step is to get clients to connect to the attacker machine instead of the legitimate servers. Our end goal is getting the user or browser to automatically authenticate to the attacker machine, which is why we are spoofing URLs in the internal domain testsegment.local. On the screenshot in step 1 you see the client started requesting information about wpad.testsegment.local immediately after it was assigned an IPv6 address. This is the part we will be exploiting during this attack.

Exploiting WPAD

A (short) history of WPAD abuse

The Windows Proxy Auto Detection feature has been a much debated one, and one that has been abused by penetration testers for years. Its legitimate use is to automatically detect a network proxy used for connecting to the internet in corporate environments. Historically, the address of the server providing the wpad.dat file (which provides this information) would be resolved using DNS, and if no entry was returned, the address would be resolved via insecure broadcast protocols such as Link-Local Multicast Name Resolution (LLMNR). An attacker could reply to these broadcast name resolution protocols, pretend the WPAD file was located on the attackers server, and then prompt for authentication to access the WPAD file. This authentication was provided by default by Windows without requiring user interaction. This could provide the attacker with NTLM credentials from the user logged in on that computer, which could be used to authenticate to services in a process called NTLM relaying.

In 2016 however, Microsoft published a security bulletin MS16-077, which mitigated this attack by adding two important protections:
– The location of the WPAD file is no longer requested via broadcast protocols, but only via DNS.
– Authentication does not occur automatically anymore even if this is requested by the server.

While it is common to encounter machines in networks that are not fully patched and are still displaying the old behaviour of requesting WPAD via LLMNR and automatically authenticating, we come across more and more companies where exploiting WPAD the old-fashioned way does not work anymore.

Exploiting WPAD post MS16-077

The first protection, where WPAD is only requested via DNS, can be easily bypassed with mitm6. As soon as the victim machine has set the attacker as IPv6 DNS server, it will start querying for the WPAD configuration of the network. Since these DNS queries are sent to the attacker, it can just reply with its own IP address (either IPv4 or IPv6 depending on what the victim’s machine asks for). This also works if the organization is already using a WPAD file (though in this case it will break any connections from reaching the internet).

To bypass the second protection, where credentials are no longer provided by default, we need to do a little more work. When the victim requests a WPAD file we won’t request authentication, but instead provide it with a valid WPAD file where the attacker’s machine is set as a proxy. When the victim now runs any application that uses the Windows API to connect to the internet or simply starts browsing the web, it will use the attackers machine as a proxy. This works in Edge, Internet Explorer, Firefox and Chrome, since they all respect the WPAD system settings by default.
Now when the victim connects to our “proxy” server, which we can identify by the use of the CONNECT HTTP verb, or the presence of a full URI after the GET verb, we reply with a HTTP 407 Proxy Authentication required. This is different from the HTTP code normally used to request authentication, HTTP 401.
IE/Edge and Chrome (which uses IEs settings) will automatically authenticate to the proxy, even on the latest Windows versions. In Firefox this setting can be configured, but it is enabled by default.

auth-proxies_fixed

Windows will now happily send the NTLM challenge/response to the attacker, who can relay it to different services. With this relaying attack, the attacker can authenticate as the victim on services, access information on websites and shares, and if the victim has enough privileges, the attacker can even execute code on computers or even take over the entire Windows Domain. Some of the possibilities of NTLM relaying were explained in one of our previous blogs, which can be found here.

The full attack

The previous sections described the global idea behind the attack. Running the attack itself is quite straightforward. First we start mitm6, which will start replying to DHCPv6 requests and afterwards to DNS queries requesting names in the internal network. For the second part of our attack, we use our favorite relaying tool, ntlmrelayx. This tool is part of the impacket Python library by Core Security and is an improvement on the well-known smbrelayx tool, supporting several protocols to relay to. Core Security and Fox-IT recently worked together on improving ntlmrelayx, adding several new features which (among others) enable it to relay via IPv6, serve the WPAD file, automatically detect proxy requests and prompt the victim for the correct authentication. If you want to check out some of the new features, have a look at the relay-experimental branch.

To serve the WPAD file, all we need to add to the command prompt is the host is the -wh parameter and with it specify the host that the WPAD file resides on. Since mitm6 gives us control over the DNS, any non-existing hostname in the victim network will do. To make sure ntlmrelayx listens on both IPv4 and IPv6, use the -6 parameter. The screenshots below show both tools in action, mitm6 selectively spoofing DNS replies and ntlmrelayx serving the WPAD file and then relaying authentication to other servers in the network.

ntlmrelay_finalmitm6_cropped

Defenses and mitigations

The only defense against this attack that we are currently aware of is disabling IPv6 if it is not used on your internal network. This will stop Windows clients querying for a DHCPv6 server and make it impossible to take over the DNS server with the above described method.
For the WPAD exploit, the best solution is to disable the Proxy Auto detection via Group Policy. If your company uses a proxy configuration file internally (PAC file) it is recommended to explicitly configure the PAC url instead of relying on WPAD to detect it automatically.
While writing this blog, Google Project Zero also discovered vulnerabilities in WPAD, and their blog post mentions that disabling the WinHttpAutoProxySvc is the only reliable way that in their experience disabled WPAD.

Lastly, the only complete solution to prevent NTLM relaying is to disable it entirely and switch to Kerberos. If this is not possible, our last blog post on NTLM relaying mentions several mitigations to minimize the risk of relaying attacks.

Detection

The Fox-IT Security Research Team team has released Snort and Suricata signatures to detect rogue DHCPv6 traffic and WPAD replies over IPv6:

Where to get the tools

mitm6 is available from the Fox-IT GitHub. The updated version of ntlmrelayx is available from the impacket repository.

Lessons learned from a Man-in-the-Middle attack

It’s become a widely accepted mantra that experiencing a cyber breach is a question of ‘when’ and not ‘if’. For Fox-IT ‘if’ became ‘when’ on Tuesday, September 19 2017, when we fell victim to a “Man-in-the-Middle” attack. As a result of the multi-layered security protection, detection and response mechanisms we had in place, the incident was both small and contained, but as a cyber security specialist it has made us look long and hard at ourselves. While the police investigation is still on-going, we are sharing details of this incident with the public now that we feel confident that most details are sufficiently clear. This is about who we are and what we do. We believe that ultimately in these cases, transparency builds more trust than secrecy and there are lessons to be learned, both good and bad, that we want to share.

So what happened?

In the early morning of September 19 2017, an attacker accessed the DNS records for the Fox-IT.com domain at our third party domain registrar. The attacker initially modified a DNS record for one particular server to point to a server in their possession and to intercept and forward the traffic to the original server that belongs to Fox-IT. This type of attack is called a Man-in-the-Middle (MitM) attack. The attack was specifically aimed at ClientPortal, Fox-IT’s document exchange web application, which we use for secure exchange of files with customers, suppliers and other organizations. We believe that the attacker’s goal was to carry out a sustained MitM attack.

Because we detected and addressed the breach quickly we limited the total effective MitM time to 10 hours and 24 minutes. In the scheme of the industry average time of detection of weeks this was a short exposure, but we couldn’t prevent the attacker from intercepting a small number of files and information that they should not have had access to. An important first step in our response was to contact Law Enforcement and share the necessary information with them to enable them to start a criminal investigation.

The incident unfolded as follows (all times are CEST):

Sept 16 2017 First reconnaissance activities against our infrastructure that we believe are attributable to the attacker. These included regular port scans, vulnerability scans and other scanning activities.
Sept 19 2017, 00:38 The attacker changed DNS records for fox-it.com domain at a third party provider.
Sept 19 2017, 02:02 Latest moment in time that we have been able to determine that clientportal.fox-it.com still pointed to our legitimate ClientPortal server. This means that traffic destined for the ClientPortal was not being intercepted yet.
Sept 19 2017, 02:05-02:15 Maximum 10-minute time window during which the attacker temporarily rerouted and intercepted Fox-IT email for the specific purpose of proving that they owned our domain in the process of fraudulently registering an SSL certificate for our ClientPortal.
Sept 19 2017, 02:21 The actual MitM against our ClientPortal starts. At this point, the fraudulent SSL certificate for ClientPortal was in place and the IP DNS record for clientportal.fox-it.com was changed to point to a VPS provider abroad.
Sept 19 2017, 07:25 We determined that our name servers for the fox-it.com domain had been redirected and that this change was not authorized. We changed the DNS settings back to our own name servers and changed the password to the account at our domain registrar. This change will have taken time to have full effect, due to caching and the distributed nature of the domain name system.
Sept 19 2017, 12:45 We disabled the second factor authentication for our ClientPortal login authentication system (text messages), effectively preventing users of ClientPortal from successfully logging in and having their traffic intercepted. Other than that, we kept ClientPortal functional in order not to disclose to the attacker that we knew what they were doing, and to give ourselves more time to investigate. At this point, the MitM against ClientPortal was still active technically, but would no longer receive traffic to intercept as users would not be able to perform two factor authentication and log in.
Sept 19 – Sept 20 2017 A full investigation into the incident was undertaken, along with notification of all clients that had files intercepted and the relevant authorities, including the Dutch Data Protection Authority. A police investigation was launched and is still ongoing. Based on the outcome of our investigation, we understood the scope of the incident, we knew that the attack was fully countered and we were prepared to re-enable two factor authentication on ClientPortal in order to make it fully functional again.
Sept 20, 15:38 ClientPortal fully functional again. Our internal investigation into the incident continued.

What kind of information did the attacker intercept?

As mentioned, the attacker was able to redirect inbound traffic to ClientPortal and emails going to the fox-it.com domain for a short period of time. At no stage did they have access to any external or internal Fox-IT system, or indeed system level access to our ClientPortal.

When investigating the attack, we made heavy use of our own technology. For all Fox-IT traffic, we employ CTMp network sensors to detect anomalies and alert us of attacks. All our sensors do full packet capture and this is what allowed us to determine precisely, beyond any doubt, which information was intercepted by the attacker, the timeline of the event and who was affected by the attack.

Because of this we know the following about the information that the attacker was able to intercept:

  • We know the following facts about the information that the attacker intercepted:
    1. Nine individual users logged in and their credentials were intercepted and all users were contacted immediately. Because we use two factor authentication, these credentials alone were not enough for the attacker to log in to ClientPortal.
    2. Twelve files (of which ten were unique) were transferred and intercepted.
      • Of these, three files were client confidential in nature, none were classified as state secret. Files classified as state secret are never transferred through our ClientPortal.
      • Other files were in the public domain and not confidential.
      • All affected clients in respect of these files were contacted immediately.
    3. One mobile phone number was intercepted and this person was informed.
    4. A subset of names and email addresses of ClientPortal users were intercepted.
      • We determined that this information alone would not be considered sensitive, but we have nevertheless informed those people affected.
    5. The names of accounts in ClientPortal were intercepted.
      • This is a list of the names of organizations that we have exchanged files with in the past. This includes organizations such as customers, partners and suppliers.
      • After review, we determined that the names alone would not be considered sensitive.
  • Email: we know that the attacker intercepted Fox-IT email for a maximum of 10 minutes, and that during those 10 minutes, emails destined for Fox-IT were redirected to an external email provider. Since email distribution is decentralized on the internet, we have no way of determining which emails were intercepted by the attacker during that time.

The start of the incident response process

We have determined that the attacker successfully logged in to the DNS control panel of our third party domain registrar provider using valid credentials. This raises two key questions:

  • How were valid credentials obtained?
  • Why was access to the domain registrar possible with single factor rather than multi factor authentication?

On the question of how the credentials were obtained we have conducted extensive internal investigations alongside those conducted by the police investigating the incident. We interviewed people that had access to the vault, carried out extensive forensic investigation of all the systems that the password could been used on, and performed additional network forensics. We currently have no evidence that the password was stolen from any of our own internal systems. Right now, based on our own and the police investigation, we have strong evidence that supports our hypothesis that the adversary gained access to our credentials through the compromise of a third party provider. Investigations are ongoing.

A factor which possibly helped the attacker was that the password had not been changed since 2013. While our password is considered strong and can withstand brute force attacks, it was not changed because it was hardly ever used: DNS settings in general change very rarely. Nevertheless, this was something we could clearly have improved in our process.

The infrequency of our engagement with our domain registrar is also behind the answer to the second question, as to how the attacker was able to gain access to the DNS records solely using a username/password combination. Two factor authentication (2FA) – whereby the initial attempt to log-on can only be completed once a code sent to an authorized device is entered as second factor authentication – should be standard practice here. We chose our domain name registrar provider 18 years ago when 2FA was neither a consideration nor a possibility. We were surprised to find that the registrar still does not support 2FA. It is always worth asking: does your DNS registrar support 2FA? The answer may surprise you.

Reasonably quick detection but room for improvement

We hold our hands up to a number of errors on prevention, but we did decidedly better in the areas of detection and response. Once the attack was ongoing, we detected it reasonably quickly: within a few hours compared to the typical industry average of weeks before an attack is detected.

Our Security Operations Center (SOC) had noticed that a number of scans for weaknesses on our infrastructure were made in the days leading up to the attack. These were treated as regular “background noise on the internet” and not followed up on. While paying attention to those scans would probably not have helped us predict the following attack, it would certainly have raised our attention and we have now established mechanisms to improve early warning of suspicious security probing of this nature.

Effective response, containment and scope determination

In general, once an incident is detected, the most important goal becomes to limit the incident and determine the impact of the attack. Once we knew about the incident, we acted quickly and we were able to limit the impact of the incident quite effectively and in a timely manner.

The most important action that we took in order to limit the impact of the attack was to disable 2FA, in lieu of disabling login functionality altogether. We did this specifically to prevent people from successfully logging in but so as not to alert the attacker to the fact that we knew of the attack. This allowed us to better understand the modus operandi and scope of the attack before taking specific actions to mitigate it, an approach which is standard operating procedure for our CERT team. From that moment on, nobody could log in, effectively preventing traffic to our ClientPortal from being intercepted. Note that this did not directly stop the attack, but it stopped its effectiveness.

The use of full packet capture and CTMp network sensors was crucial in determining the scope of the attack. We could, within a few hours of finding out about the attack, determine exactly who was affected and what the scope of the attacker was. This helped us to understand the incident with confidence and to quickly notify those directly affected and the Dutch Data Protection Authority.

Lessons learned and recommendations

Looking back on this incident, we learned the following lessons and have the following recommendations:

  • Choose a DNS provider that doesn’t allow changes through a control panel but requires a more manual process, considering that name servers are very stable and hardly every change. If you do require more frequent changes, use 2FA.
  • Ensure that all system access passwords are reviewed regularly and changed, even those which are used rarely.
  • Deploy certificate transparency monitoring in order to detect, track and respond to fraudulent certificates.
  • Deploy full packet capture capabilities with good retention in crucial points of your infrastructure, such as the DMZ and border gateways.
  • Always inform Law Enforcement at an early stage, so that they can help you with your investigations, as we did in our case.
  • Make it a management decision to first understand an attack before taking specific actions to mitigate it. This may include letting an attack continue for a short period of time. We consciously made that decision.

Looking back in conclusion

While we deeply regret the incident and the shortcomings on our part which contributed to it, we also acknowledge that a number of the measures we had in place enabled us to detect the attack, respond quickly and confidently and thereby limited the scale and length of the incident. And that’s why the twin mantras in security should always be followed:

  • layered security; and
  • prevention, detection and response.

At the time that ‘if’ becomes ‘when’, it is the combination of these that ultimately determines your overall resilience and cyber security stance.

Criminals in a festive mood

This morning the Fox-IT Security Operations Center observed a large number of phishing e-mails that contained a link to a downloadable zip file. Anyone downloading and opening that zip file would infect themselves with banking malware, that would subsequently try to lure the victim into divulging their credit card information.

So far nothing new: e-mail as attack vector, distribution of the Zeus Panda banking trojan, targeting the same institutions.

Except that this time, it appears the criminals are preparing for the festive season. What stood out to us is the inclusion of a number of local retailers that are now targeted by this banking trojan. Some targeted websites which were extracted from the configuration are:

  • Coolblue
  • Booking.com
  • Otto
  • Amazon
  • De Volksbank (SNS, ASN & Regiobank)
  • ING
  • ABN Amro
  • Knab
  • Triodos

So now, when someone has infected themselves with this malware by opening the malicious zip file, not only will the malware ask for their credit card details when they visit their bank’s website, but also when they visit an online retailer for (Christmas) shopping.

Read on for recommendations, notable observations, stats and screenshots and technical details including indicators of compromise.

Recommendations
The usual recommendations for end users apply: be alert for criminals attacking you by sending legitimate looking e-mails with links and attachments. And be alert for websites behaving differently and asking for credit card details or other personal data where they normally don’t. If you suspect an infection, you may check out a website from a different device to see if it behaves the same. If it doesn’t, you may be infected.

The e-mail itself is nothing out of the ordinary. It appears to be targeting the Netherlands and Germany, using Dutch text and faking the Dutch DHL Group. This is what it looks like:

Beste heer/mevrouw,
UW ZENDING IS ONDERWEG ,Informatie Over Uw Zending is in dokument.

Controleer hieronder uw zending- en contactgegevens. Klik op om te bevestigen.
Bedankt dat u heeft gekozen voor On Demand Delivery.
DHL Express – Excellence. Simply delivered.
Nederlandse Post DHL Group

For organisations, the recommendations are also familiar: isolate any infected systems prior to cleaning them, change any password that was used after infection and consider client certificates on that system compromised. You may refer to the indicators of compromise later on in this post.

Additional interesting observations
The malware that is being distributed is called Zeus Panda, which we’ve followed for almost two years now. This is a variant of the Zeus family of malware that Fox-IT has observed since around 2006, for the purpose of protecting its own customers. The name Zeus Panda comes from the web panel used by the malware operators.

At the time of writing, the two malicious zip file referred in the emails received a little over 48 thousand clicks, mostly in the Netherlands, but also in other parts of Western Europe and some in North America. Out of those 48 thousand clicks, only 11 thousand came from a Window system, which is the only platform that the malware runs on. The other 37 thousands people were safe! A clear example and proof of the shotgun approach that criminals still successfully use.

Also interesting is the clunky nature of the injects. As shown in the screenshots below, the code that the criminals inject into the website on the infected system looks, well, unfinished.

Full statistics
The link in the email is a Google Shortened URL, which downloads the zip-file from
hxxp://partytimeevents.nl/contactgegevens%2012_2017_10_00_.zip
hxxp://stegengaweb.nl/files/contactgegevens%2012_2017_10_00_.zip

By default Google shortened URL’s keeps track of the following statistics:
– Amount of clicks
– Used Browsers
– Referrers
– Countries
– Platforms

Requesting the statistics of the shortened URL results in the following statistics for:

 

Screenshot of the inject asking for credit card details
From an infected system, Zeus Panda will inject extra code into a website. Once the code is injected into one of the targeted web pages, an extra form is added for creditcard information. For example, Coolblue’s webshop page would look like this, clunky and unfinished. Please note that Coolblue has no control over the fact that criminals attempt to inject code into their website from infected machines.

coolblue_main

Zeus Panda Banker web inject

EDIT: the total click count for both domains has increased to a total of 66 thousand, even though both ZIP-files are not available anymore.

Indicators of Compromise
—Dropper—
hxxp://partytimeevents.nl/contactgegevens%2012_2017_10_00_.zip (compromised website)
hxxp://stegengaweb.nl/files/contactgegevens%2012_2017_10_00_.zip (compromised website)
hxxp://axprofessional.it/onenl.exe

—Command-and-Control—
hxxps://avimart.ru/3inexowtoqiyzlonyunku.dat
hxxps://astronatal.ru/2odirnaogfaugdoxiwoex.dat
hxxps://abci.ru/1yhubydnopyakleqinyyx.dat
185.224.133.57 (SSL connection)

—External panel for injects—
hxxps://adsfun.club/

—Hashes—
contactgegevens 2012_2017_10_00.zip
MD5: aefc0fe15836165291cb66eac5ffd177
SHA256: 588e31ac96bd6318f787602e87f86b75d4b5537679e11ba5a509589148033275

contactgegevens 12_2017_10_00_.js
MD5: deb9a0aa69270a0b263b80ed13880b24
SHA256: eb65b1d5f5b3ccc263a4984275c084b63b0a262a87d55887d6a4d744a75e4112

onenl.exe
MD5: 4ac38a4efa276f8d64c1ed39a53e7ab8
SHA256: e556273db50d4588d7e4b5183d06d39b0ebedbb094fc2a39b59416212c829324

Detection and recovery of NSA’s covered up tracks

Part of the NSA cyber weapon framework DanderSpritz is eventlogedit, a piece of software capable of removing individual lines from Windows Event Log files. Now that this tool is leaked and public, any criminal willing to remove its traces on a hacked computer can use it. Fox-IT has looked at the software and found a unique way to detect the use of it and to recover the removed event log entries.

Introduction

A group known as The Shadow Brokers published a collection of software, which allegedly was part of the cyber weapon arsenal of the NSA. Part of the published software was the exploitation framework FuzzBunch and post-exploitation framework DanderSpritz. DanderSpritz is a full-blown command and control server, or listening post in NSA terms. It can be used to stealthy perform various actions on hacked computers, like finding and exfiltrating data or move laterally through the target network. Its GUI is built on Java and contains plugins written in Python. The plugins contain functionality in the framework to perform specific actions on the target machine. One specific plugin in DanderSpritz caught the eye of the Forensics & Incident Response team at Fox-IT: eventlogedit.

DanderSpritz with eventlogedit in action

Figure 1: DanderSpritz with eventlogedit in action

eventlogedit

Normally, the content of Windows Event Log files is useful for system administrators troubleshooting system performance, security teams monitoring for incidents, and forensic and incident response teams investigating a breach or fraud case. A single event record can alert the security team or be the smoking gun during an investigation. Various other artefacts found on the target system usually corroborate findings in Windows Event Log files during an investigation, but a missing event record could reduce the chances of detection of an attack, or impede investigation.

Fox-IT has encountered event log editing by attackers before, but eventlogedit appeared to be more sophisticated. Investigative methods able to spot other methods of event log manipulation were not able to show indicators of edited log files after the use of eventlogedit. Using eventlogedit, an attacker is able to remove individual event log entries from the Security, Application and System log on a target Windows system. After forensic analysis of systems where eventlogedit was used, the Forensics & Incident Response team of Fox-IT was able to create a Python script to detect the use of eventlogedit and fully recover the removed event log entries by the attacker.

Analysing recovered event records, deleted by an attacker, gives great insight into what an attacker wanted to hide and ultimately wanted to achieve. This provides security and response teams with more prevention and detection possibilities, and investigative leads during an investigation.

Before (back) and after (front) eventlogedit

Figure 2: Before (back) and after (front) eventlogedit

eventlogedit in use

Starting with Windows Vista, Windows Event Log files are stored in the Windows XML Eventlog format. The files on the disk have the file extension .evtx and are stored in the folder \Windows\System32\winevt\Logs\ on the system disk, by default. The file structure consists of a file header followed by one or more chunks. A chunk itself starts with a header followed by one or more individual event records. The event record starts with a signature, followed by record size, record number, timestamp, the actual event message, and the record size once again. The event message is encoded in a proprietary binary XML format, binXml. BinXml is a token representation of text XML.

Fox-IT discovered that when eventlogedit is used, the to-be-removed event record itself isn’t edited or removed at all: the record is only unreferenced. This is achieved by manipulation of the record header of the preceding record. Eventlogedit adds the size of the to-be-removed-record to the size of the previous record, thereby merging the two records. The removed record including its record header is now simply seen as excess data of the preceding record. In Figure 3 this is illustrated. You might think that an event viewer would show this excess or garbage data, but no. Apparently, all tested viewers parse the record binXml message data until the first end-tag and then move on to the next record. Tested viewers include Windows Event Viewer as well as various other forensic event log viewers and parsers. None of them was able to show a removed record.

Untouched event records (left) and deleted event record (right)

Figure 3: Untouched event records (left) and deleted event record (right). Note: not all field are displayed here.

Merely changing the record size would not be enough to prevent detection: various fields in the file and chunk header need to be changed. Eventlogedit makes sure that all following event records numbers are renumbered and that checksums are recalculated in both the file and chunk header. Doing so, it makes sure that obvious anomalies like missing record numbers or checksum errors are prevented and will not raise an alarm at the system user, or the security department.

Organizations which send event log records on the fly to a central log server (e.g. a SIEM), should be able to see the removed record on their server. However, an advanced attacker will most likely compromise the log server before continuing the operation on the target computer.

Recovering removed records

As eventlogedit leaves the removed record and record header in its original state, their content can be recovered. This allows the full recovery of all the data that was originally in the record, including record number, event id, timestamps, and event message.

Fox-IT’s Forensics & Incident Response department has created a Python script that finds and exports any removed event log records from an event log file. This script also works in the scenario when consecutive event records have been removed, when the first record of the file is removed, or the first record of a chunk is removed. In Figure 4 an example is shown.

Recovering removed event records

Figure 4: Recovering removed event records

We have decided to open source the script. It can be found on our GitHub and works like this:

$ python danderspritz_evtx.py -h
usage: danderspritz_evtx.py [-h] -i INPUT_PATH [-o OUTPUT_PATH]
 [-e EXPORT_PATH]

danderspritz_evtx.py - Parse evtx files and detect the use of the danderspritz
module that deletes evtx entries

optional arguments:
 -h, --help show this help message and exit
 -i INPUT_PATH, --input INPUT_PATH
 Path to evtx file
 -o OUTPUT_PATH, --output OUTPUT_PATH
 Path to corrected evtx file
 -e EXPORT_PATH, --export EXPORT_PATH
 Path to location to store exported xml records

The script requires the python-evtx library from Willi Ballenthin.

Additionally, we have created an easy to use standalone executable for Windows systems which can be found on our GitHub as well.

Danderspritz_evtx.exe

Hashes:
md5    c07f6a5b27e6db7b43a84c724a2f61be 
sha1   6d10d80cb8643d780d0f1fa84891a2447f34627c
sha256 6c0f3cd832871ba4eb0ac93e241811fd982f1804d8009d1e50af948858d75f6b

 

Recommendations

To detect if the NSA or someone else has used this to cover up his tracks using the eventlogedit tool on your systems, it is recommended to use the script on event log files from your Windows servers and computers. As the NSA very likely changed their tools after the leaks, it might be farfetched to detect their current operations with this script. But you might find traces of it in older event log files. It is recommended to run the script on archived event log files from back-ups or central log servers.

If you find traces of eventlogedit, and would like assistance in analysis and remediation for a possible breach, feel free to contact us. Our Forensics & Incident Response department during business hours or FoxCERT 24/7.

Wouter Jansen
Fox-IT Forensics & Incident Response