Normal view

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

Mark-of-the-Web from a red team’s perspective

By: Stan
30 March 2020 at 09:37

Zone Identifier Alternate Data Stream information, commonly referred to as Mark-of-the-Web (abbreviated MOTW), can be a significant hurdle for red teamers and penetration testers, especially when attempting to gain an initial foothold.

Your payload in the format of an executable, MS Office file or CHM file is likely to receive extra scrutiny from the Windows OS and security products when that file is marked as downloaded from the internet. In this blog post we will explain how this mechanism works and we will explore offensive techniques that can help evade or get rid of MOTW.

Note that the techniques described in this blog post are not new. We have witnessed all of them being abused in the wild. Hence, this blog post serves to raise awareness on these techniques for both red teamers (for more realistic adversary simulations) and blue teamers (for better countermeasures and understanding of attacker techniques).

Introduction to MOTW

Mark-of-the-Web (MOTW) is a security feature originally introduced by Internet Explorer to force saved webpages to run in the security zone of the location the page was saved from. Back in the days, this was achieved by adding an HTML comment in the form of <!-–saved from url=> at the beginning of a saved web page.

This mechanism was later extended to other file types than HTML. This was achieved by creating an alternate data stream (ADS) for downloaded files. ADS is an NTFS file system feature that was added as early as Windows 3.1. This feature allows for more than one data stream to be associated with a filename, using the format “filename:streamname”.

When downloading a file, Internet Explorer creates an ADS named Zone.Identifier and adds a ZoneId to this stream in order to indicate from which zone the file originates. Although it is not an official name, many people still refer to this functionality as Mark-of-the-Web.

Listing and viewing alternate data streams is trivial using PowerShell: both the Get-Item and Get-Content cmdlets take a “Stream” parameter, as can be seen in the following screenshot.

The following ZoneId values may be used in a Zone.Identifier ADS:

  • 0. Local computer
  • 1. Local intranet
  • 2. Trusted sites
  • 3. Internet
  • 4. Restricted sites

Nowadays all major software on the Windows platform that deals with attachments or downloaded files generates a Zone.Identifier ADS, including Internet Explorer, Edge, Outlook, Chrome, FireFox, etc. How do these programs write this ADS? Either by creating the ADS directly or via the system’s implementation of the IAttachmentExecute interface. The behavior of the latter can be controlled via the SaveZoneInformation property in the Attachment Manager.

Note that Windows 10’s implementation of the IAttachmentExecute interface will also add URL information to the Zone.Identifier ADS:

For red teamers, it’s probably good to realize that MOTW will also get set when using the HTML smuggling technique (note the “blob” keyword in the screenshot above, which is an indicator of potential HTML smuggling).

The role of MOTW in security measures

The information from the Zone Identifier Alternate Data Stream is used by Windows, MS Office and various other programs to trigger security features on downloaded files. The following are the most notable ones from a red teamer’s perspective (but there are more – this list is far from complete).

Windows Defender SmartScreen

This feature works by checking downloaded executable files (based on Zone Identifier ADS) against a whitelist of files that are well known and downloaded by many Windows users. If the file is not on that list, Windows Defender SmartScreen shows the following warning:

MS Office protected view

The Protected View sandbox attempts to protect MS Office users against potential risks in files originating from the internet or other dangerous zones. By default, most MS Office file types flagged with MOTW will be opened in this sandbox. Many users know this feature as MS Office’s famous yellow bar with the “Enable Editing” button.

MWR (now F-Secure labs) has published a great technical write-up on this sandbox some years ago. Note that some MS Office file types cannot be loaded in the Protected View sandbox. SYLK is a famous example of this.

MS Office block macros downloaded from the internet

This feature was introduced in Office 2016 and later back-ported to Office 2013. If this setting is enabled, macros in MS Office files flagged with MOTW are disabled and a message is displayed to the user.

This warning message cannot be ignored by the end user, which makes it a very effective measure against mass-scale macro-based malware.

Visual Studio project files

Opening untrusted Visual Studio project files can be dangerous (see my presentation at Nullcon Goa 2020 for the reasons why). By default, Visual Studio will display a warning message for any project file which has the MOTW attribute set.

Application Guard for Office

This newly announced feature runs potentially malicious macros embedded in MS Office files in a small virtual machine (based on Application Guard technology) in order to protect the OS.

From the limited documentation available, the decision to run a document in a VM is based on MOTW. Unfortunately, I don’t have access to this technology yet, so I cannot confirm this statement through testing.

Strategies to get rid of MOTW

From a red teamer’s perspective, there are two strategies we can employ to evade MOTW. All of the techniques that we have witnessed in the wild can be categorized under the following two strategies:

  1. Abusing software that does not set MOTW – delivering your payload in a file format which is handled by software that does not set or propagate Zone Identifier information.
  2. Abusing container formats – delivering your payload in a container format which does not support NTFS’ alternate data stream feature.

Of course there is a third strategy: social engineering the user into removing the MOTW attribute (right click file -> properties -> unblock). But since this is a technical blog post, this strategy is out of scope for this write-up. And for the blue team: you can technically prevent your end-users from doing this by setting HideZoneInfoOnProperties via group policy.

Let’s explore the two technical strategies for getting rid of MOTW in more depth…

Strategy 1: abusing software that does not set MOTW

The first strategy is to deliver your payload via software that does not set (or propagate) the MOTW attribute.

A good example of this is the Git client. The following picture shows that a file cloned from GitHub with the Git client does not have a Zone.Identifier ADS.

For red teamers targeting developers, delivering your payloads via Git might be a good option to evade MOTW. This is especially relevant for payloads targeting Visual Studio, but that is material for a future blog post. 🙂

Another famous example of software that does not set a Zone.Identifier ADS is 7Zip. This archiving client only sets a MOTW flag when a file is double-clicked from the GUI, which means the file is extracted to the temp directory and opened from there. However, upon manual extraction of files to other locations (i.e. clicking the extract button instead of double-clicking), 7Zip does not propagate a Zone.Identifier ADS for extracted files. Note that this works regardless of the archiving file format: any extension handled by 7zip (7z, zip, rar, etc) will demonstrate this behavior.

This appears to be a conscious design decision by the 7Zip lead developer, as can be seen in the following excerpt from a discussion on SourceForge. More information can be found here.

As a side note, I wouldn’t recommend using 7Zip for extracting potentially dangerous files anyway, since it is a product known for making “odd” security decisions (such as the lack of ASLR…).

Strategy 2: abusing container formats

Remember that alternate data streams are an NTFS feature? This means that Zone Identifier ADS cannot be created on other file systems, such as FAT32. From a red teamer’s perspective we can exploit this behavior by embedding our payload in a file system container such as ISO or VHD(X).

When opening such a container with Windows Explorer, MOTW on the outside container will not be propagated to files inside the container. This is demonstrated in the screenshot below: the downloaded ISO is flagged with MOTW, but the payload inside the ISO is not.

Note that payload delivery via the ISO format is an evasion technique commonly observed in the wild. For example, TA505 is a prominent actor known to abuse this technique.

Message to the Blue Team

So, what does all of this mean when you are trying to defend your network?

First of all, the fact that a security measure can be circumvented does not render such a measure useless. There will be plenty of attackers that do not use the techniques described in this blog post. In particular, I am a big fan of the measure to block macros in files downloaded from the internet which is available in MS Office 2013 and subsequent versions.

Second, the techniques described in this blog post acknowledge a very important security paradigm: defense in depth. Do not engineer an environment in which your security depends on a single preventive measure (in this example MOTW).

Start thinking about which other measures you can take in case attackers are trying to evade MOTW. For example, if feasible for your organization, block container formats in your mail filter and proxy. Also, limit the impact of any malicious files that may have bypassed measures relying on MOTW, for example using Attack Surface Reduction rules.

I think you get the idea: don’t do coconut security – a single hard layer, but all soft when it’s cracked.

The post Mark-of-the-Web from a red team’s perspective appeared first on Outflank.

Abusing the SYLK file format

By: Stan
30 October 2019 at 09:10

This blog is about the SYLK file format, a file format from the 1980s that is still supported by the most recent MS Office versions. As it turns out, this file format is a very good candidate for creating weaponized documents that can be used by attackers to establish an initial foothold. In our presentation at DerbyCon 8 we already demonstrated some of the powers of SYLK.

In this blog post we will dive into additional details of this file format. We also provide recommendations for mitigations against weaponized SYLK files.

Introduction

SYLK stands for SYmbolic LinK, a file format that was introduced in the 1980s. Commonly, SYLK files have the file extension .slk. SYLK is a file format which uses only displayable ANSI characters and it was created to exchange data between applications (such as spreadsheets and databases).

The file format is hardly used nowadays and documentation on it is scarce. Wikipedia has limited details on SYLK. Probably the best documentation available is the file sylksum.doc, authored by Microsoft and last updated in 1986 (!). We have hosted a copy of this file here. The File Formats Handbook by Gunter Born describes additional details on SYLK (it’s a 1995 book, second hand copies available on Amazon).

Despite being an ancient file format, the file extension .slk is still mapped by default to Excel on the most recent MS Office versions (confirmed on 2010, 2013 and 2016).

We are not the first offensive security researchers to look into the SYLK file format. Previously, Matt Nelson has demonstrated how DDE attacks can be combined with SYLK. This method has been weaponized in various malware samples that were observed in the wild, such as this one and this one.

In this blog post we will demonstrate that the power of SYLK goes beyond DDE attacks. In particular, malicious macros can be embedded in this file type as well.

No protected mode

There is one important reason why the SYLK format is appealing to attackers: the Protected View sandbox does not apply to this file format. This means that if a weaponized SYLK file is delivered via email or web and the Mark-of-the-Web flag is applied, the target user is not bothered with this warning message.

In addition, SYLK files with the .slk extension have the following characteristics.

Altogether, this makes SYLK a good candidate for weaponization.

XLM macros in SYLK

This unanswered question on an Excel forum caught our eye. Would it be possible to embed macros in SYLK? Simply trying to save an Excel file with a VBA project to SYLK did not work: a warning message was displayed that the macro project would be lost in this file format. Repeating this attempt with Excel 4.0 / XLM macros didn’t work either.

After studying the scarce documentation that is available on SYLK and after countless hours of experiments, we finally achieved our goal: macros can be embedded in the SYLK file format.

Open notepad, paste the following text and save it to a file with the .slk extension:

ID;P
O;E
NN;NAuto_open;ER101C1
C;X1;Y101;EEXEC("CALC.EXE")
C;X1;Y102;EHALT()
E

Double click the file to open it in Excel. Click “Enable Content” to enable macros and calculator will pop.

Let’s dive into how this works. Each line of a SYLK input file must be no longer than 260 characters (otherwise Excel will display an error message and will not parse that line). Every line consists of one or more records marked with semicolons:

  • The first line with the “ID” and “P” records is a marker that indicates this file is a SYLK file.
  • The second line with the “O” record sets options for this document. “E” marks that it is a macro-enabled document.
  • The third line has a names record “NN”. We set the name “Auto_open” for the cell at row 101, column 1 (“ER101C1”).
  • The fourth and fifth lines define cell content (“C”). “X” and “Y” records mark row and columns (e.g. row 1, column 101 in the first “C” line). Record “E” defines an expression value for this cell, in our case two Excel 4.0 macro functions.
  • The last line holds the end of file record (“E”).

In short, this basic SYLK file example defines a cell named Auto_open that executes the EXEC() and HALT() Excel 4.0 macro functions (so this is not VBA!). If you target Excel in a different language, beware of localized Auto_open event names. For example, in Dutch this has to be renamed to “Auto_openen”.

Process injection with SYLK

Now that we can embed macros in SYLK, we can do much more than simply popping calculator. In our previous blog post on Excel 4.0 / XLM macros, we have already demonstrated the power of this macro type. The following proof of concept demonstrates shellcode injection using macros in SYLK:

The code for this proof of concept is available from our GitHub page.

  • Create shellcode without null bytes. Example with msfvenom:
    msfvenom -c messageBox -a x86 --platform windows -p windows/messagebox TEXT="Hello from shellcode!" -b "\x00" -f raw > messagebox.bin
  • Create a SYLK file that embeds and loads the shellcode:
    python shellcode_to_sylk.py messagebox.bin > file.slk

Based on proof of concept code that we shared with MDSec in an early stage of our research, Dominic Chell has also embedded process injection using SYLK payloads in his SharpShooter tool.

Disguising SYLK as CSV

An interesting feature is that SYLK files can be disguised as other Excel file types, including the comma-seperated values (CSV) type. Upon parsing of a file with the .csv extension, Excel will automatically detect if the file is a SYLK file when the file starts with the header “ID;P” which is typical for SYLK. If this is the case, the following dialogue will be presented to the user:

If the user clicks “Yes”, the file will be opened as a SYLK file instead of CSV. So, with one additional warning message we can embed a malicious macro in a text-based file with the .csv extension.

Abusing SYLK on Mac

The SYLK file format is also supported on MS Office for Mac. The .slk extension maps to Excel for Mac by default and Excel 4.0 / XLM macros are supported as well, rendering this file format a very good candidate for weaponization on Mac.

Things get even more interesting when a target uses an outdated version of MS Office for Mac. MS Office 2011 for Mac contains a vulnerability where no warning message is displayed before macro execution in SYLK files. My colleague Pieter has previously blogged about this. Since Microsoft does no longer support this version of MS Office, this vulnerability will not be fixed. Unfortunately, we still spot Mac users with this outdated MS Office version from time to time.

SYLK and antivirus

In theory, SYLK files are easy to scan for a security product since the file format is very simple. However, in practice, it appears that many antivirus products do not particularly bother about this file format. In our experience, detection signatures and heuristics for malicious SYLK files by most antivirus products are quite poor.

We hope that this blog post contributes to a better understanding of the dangers of SYLK files and that antivirus vendors will act upon this. With an increase of malicious SYLK samples in the wild there is definitely a motivation to do so.

Also, it should be noted that the Antimalware Scan Interface (AMSI) does not catch macros in SYLK. As the AMSI engine for macros only hooks into VBA, it is blind to Excel 4.0 / XLM based macros.

Mitigation

The best way to mitigate abuse is to completely block SYLK files in MS Office, which can be achieved through File Block settings in the MS Office Trust Center settings.

This GUI can be a bit confusing. A checkbox under “Open” means that a blocking action is defined for that filetype. So a checkbox under “Dif and Sylk Files” and selecting “Do not open selected file types” is what you need to configure in order to block opening of SYLK files.

Note that this setting can also be managed via Group policy:

  • The relevant policy can be configured under Microsoft Excel 2016\Excel Options\Security\Trust Center\File Block Settings.
  • Set “Dif and Sylk” to “Enabled: Open/Save blocked, use open policy” to prevent users from opening SYLK files in MS Office.

Another opportunity for mitigation is that macros in a SYLK document do adhere to macro security settings configured in MS Office. While completely disabling macros is not a viable option in many organisations, the following good practices can reduce the risk posed by malicious macros in SYLK and other MS Office file formats:

  • MS Office 2013 and 2016 have a feature to block macros in files that are downloaded from the internet. Set a DWORD value for blockcontentexecutionfrominternet to “1” under HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Word\Security. This setting can also be managed via GPO. Enable the setting “Block macros from running in Office files from the Internet” which can be found under Microsoft Excel 2016\Excel Options\Security\Trust Center.
  • In addition, Attack Surface Reduction rules can be used to set boundaries to what macros can do on a system.

Any feedback or additional ideas? Reach out on Twitter!

The post Abusing the SYLK file format appeared first on Outflank.

Knock, Knock – Who’s There?

11 February 2020 at 15:40

A Windows Linux Subsystem Interop Analysis

Following our research from Evil Twins and Windows Linux Subsystem, interoperability between different WSL versions was something that caught our attention. The protocol and mechanism to do file management from/to WSL is a must for Blue and Red Teams whose research will provide new ways to execute known techniques to achieve tactics such as Persistence, Defense Evasion and Execution, among others.

It is important (even if not seen today in regular arsenals) to understand how to protect, detect and react to this attack surface which could be widely spread in the future where WSL could be a de-facto component in every Enterprise machine.

Since Windows 10 version 1903, it is possible to access Linux files from Windows by using the \wsl$[DistroName] path syntax using 9P protocol. During our research, we found some design issues in WSLv1 that were propagated to WSLv2 — even though the core component differs. The main issue involves the lack of security control in the WSL communication object, leading to any user owning the instance to own the listening Planet 9 File System server. At first sight, this may look obvious, but once you control that communication, different ways of using the data being sent back and forth from Windows to the container begin to emerge.

It is important to mention that when running inside an isolated environment like WSLV2, certain activities not crossing boundaries may remain hidden for security products, but once an attempt to execute a malicious app on the Windows side is detected, the scanning mechanism provided by MVISION Endpoint and ENS will trigger to protect. MVISION EDR will provide visibility and detection on some of these artifacts. At the end of this article, we present certain objects to monitor to detect such cases in your organization.

Potential usages for Red Teams and  Researchers:

  • Persistence by hiding the real content, especially on WSLv2 where the root folder is a VHDX image.
  • Protocol fuzzing for discovering vulnerabilities on the implementation.
  • Security bypass by using \\wsl$ syntax in applications that have options to disable Network Folders scan and thus, do not consider this as a local path. (McAfee MVision Endpoint will consider this special path).
  • File tampering (the user accesses a file expecting some content, but it is changed during the transfer).

P9 Server Hijack Pre-Requisites:

  • WSL Enabled
  • Same user privileges as the WSL instance
  • A P9 compatible server

In the following section P9 (Planet 9 File System Protocol) and 9P (the protocol) are used interchangeably

WSLv1 and P9

The communication is done using an AF_UNIX socket (local file) that is currently owned by the user executing the WSL instance. The socket is created by the custom init process. Processes from the Windows side use a p9driver to access that socket by using an implementation of the P9 FileSystem instead of accessing the files as “Windows local”.

Note: Plan 9 has several implementations; currently the format supported by Windows is L / W.

A simple string on init shows that:

  1. The first WSL instance will open the p9 server for that distribution.
  2. Init has an embed server that creates a Unix socket into the distro path.
  3. The Unix socket is used to communicate.
  4. Whenever \\wsl$\ is accessed, P9 driver starts the communication.
  5. A P9 client communicates with the server.

Now, is that fsserver file protected? No! That means that we can hijack that socket and start our P9 server (in this case, I used DIOD as the main source) and from there… the options are endless from protocol fuzzers to trigger something unexpected, to protection bypass, to something very simple that just serves different content than expected.

To find programmatically the fsserver root location using PowerShell:

From there, the next step would be to start our p9 server from WSL (assuming the path was provided as the script argument as shown above):

In this example, next time we access \\wsl$\Debian, it will serve the files from mynewroot.

The below screenshot shows the full procedure using a modified P9 server:

  1. DIOD listening on the local socket.
  2. WSL directory listing before the hijack.
  3. WSL directory listing after the hijack.

At the time we were working on this, WSLv2 was announced and available in the latest Win10 Update. The next question was obvious—can we still do the same, given that the instance is now hosting a real kernel due to its nature of being hosted as a Hyper-V internal instance?

WSLv2 and P9

Now that there is a Linux Kernel the real “p9 Linux” module is activated. C: drive is mounted using P9 with several rdfd/wdfd arguments on top of drvfs.

The host is at CID:2, and ports  50000/1/2 are used for InterOp Messages and instance control.

Back to work — there are some steps to follow to determine whether we can achieve the same P9 Server Hijack or not.

  • Scan open ports listening on WSLv2 instance (a starting point could be modifying sample client code to became a scanner).
  1. Find the instance UID (an option is to check the task manager and wslhost.exe command line).
  2. Scan the instance!

3. Hey! Port 0x405(1029d) is open, let us Knock-Knock to find who is there.

  • P9 server port found… let us go hijack!!!
    1. Listening to the same port as with WSLv1 is not possible , unless we find a way to bypass the restrictions (app/module not using reuseaddr/port, not possible to close from user-space, etc.).
    2. We cannot kill init nor unload the module serving the files, so our best bet would be to close the port from the kernel. At the end of the day, it is our instance and we login as root .
    3. Let us create a vsock module that will:
      1. List current vsock connected sockets.
      2. Close a socket listening on a certain port.

  1. Compile the module using kernel source.
  2. Test it! (Note that same ports are not present and should be fixed, but for what we want the output is enough).

3)   Now, we are free to go, but still, we need to start our P9 DIODserver listening somehow on that port using a VSOCK socket. Since `socat` supports this type of socket it will be a piece of cake.

  • Access \\wsl$\DistributionName and voila!

Protection and Detection with McAfee Products

In Addition to rules related to WSL presented in previous posts, McAfee products provide several ways to detect and protect against P9 hijacking:

  • MVISION Endpoint will scan \\wsl$\ even if network scanning is disabled, so from the execution perspective on Windows side protection will still apply.
  • By using Endpoint Security Expert Rules it’s possible to block execution from WSL paths.
  • To configure Active Response (WSLv1) follow the below steps:
    • Setup a trigger to be notified of this situation a file fsserver is deleted.
      • File Trigger with condition: Files name equals fsserver”
    • Files collector if enabled, looking for fsserver modifications.
      • “Files where Files name equals fsserver”

In MVISION EDR (WSLv1), the file collector should be enabled and looking for wsl.conf modifications (files where files name equals “fsserver”

As a final note, we expect this post to provide new insights about the future exploration of these key areas, mostly considering that WSLv1 and WSLv2 can be converted online and both versions will be fairly used during the next years.

References:

  1. http://doc.cat-v.org/plan_9/misc/ubiquitous_fileserver/
  2. http://9p.io/magic/man2html/5/intro
  3. https://github.com/chaos/diod/blob/master/protocol.md
  4. https://w4mhi.wordpress.com/complete-hyper-v-socket-client-code/
  5. https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/user-guide/make-integration-service
  6. https://tyranidslair.blogspot.com/2019/07/digging-into-wsl-p9-file-system.html
  7. https://securingtomorrow.mcafee.com/other-blogs/mcafee-labs/using-expert-rules-in-ens-10-5-3-to-prevent-malicious-exploits/
  8. https://securingtomorrow.mcafee.com/other-blogs/mcafee-labs/the-twin-journey-part-1/

 

The post Knock, Knock – Who’s There? appeared first on McAfee Blog.

❌
❌