Monday, September 5, 2016

Virtual File Systems for Beginners

A virtual File System (VFS), sometimes referred to as a Hidden File System, is a storage technique most commonly used by kernel mode malware, usually to store components outside of the existing filesystem. By using a virtual filesystem, malware developers can both bypass antivirus scanners as well as complicating work for forensic experts.

Filesystem Basics

If you’re running Windows and not using hardware from the 90s, or have your OS installed on a flash drive; chances are, you’re using the New Technology File System (NTFS). In order to understand how a VFS benefits malware developers, first we need to dive into a bit of filesystem basics. 
In this example we have a disk containing only one partition (which runs Windows).
  • The Master Boot Record (MBR) gives the system information about the partition, such as its start sector and size.
  • The Volume Boot Record (VBR) is the primary boot code and will load and Windows bootloader and execute it; The VBR is the first sector within the NTFS partition. 
  • $BOOT is the boot area and contains the Windows boot loader.
  • $MFT is the Master File Table and tells the system where to find files within the filesystem.
Antivirus Scans
A full system scan will go through every file in the master file table and scan it, additionally the antivirus can hook the filesystem driver and scan files on creation / write. If somebody didn’t want a file to be scanned, not adding an entry to the MFT would be a good start. Unfortunately, if sectors within the partition are not referenced by the MFT, they are assumed unused and likely to be overwritten as more files are written to the disk.
Malware Forensics
There are lots of techniques used when analyzing an infected system; however, looking for new/modified files is a common starting point for an analyst. To speed up file deletion, the system simply deletes the file’s record in the MFT but leaves the actual file intact, this way the sectors can be overwritten by an new file and the system doesn’t have to waste time zeroing out the old one. Due to the fact there’s going to be random data left by deleted files all over the disk, it’s very easy for an encrypted virtual filesystem to hide, further complicating analysis.
Obviously if we can’t write directly to free sectors within the partition for fear of them being overwritten, then we’re going to have to write our VFS outside of the partition; What makes this possible is the fact that there is unused reserves space on both ends of the disk. 

Disk Basics

For people who are interested in the (very technical) reasons behind the reserved space at the beginning and end of the disk, I suggest reading this section. If you’re not interested or easily confused, skip to Virtual File Systems.
A hard disk platter
Space after the MBR
A disk platter is divided into tracks which are divided into sectors; a single sector is 512 bytes in size and there are a fixed number of sectors per a track. As technology advanced the physical size of sectors got smaller so more sectors could be fit onto a single track; however, the MBR field that describes the number of sectors is 6 bits in size, thus can only support numbers 0 – 63, limiting the sectors per track to 63.
Eventually, someone figured out that the the closer to the edge of the disk you get, the longer the tracks are and the more sectors the can hold. Nowadays the number of sectors per a track varies depending on how far away from the spindle the track is, making the sectors per a track field of the MBR totally meaningless; For compatibility reason, disks with more than 63 sectors per a track will just leave the value set at 63, the same goes for SSDs or other media that doesn’t have tracks. 
For optimization reasons when partitioning the disk, the Windows partition manager will read the sectors per track value and align the partition on the track boundary (63 sectors per track vmeans that the MBR will be sector 0 track 0, while the start of the partition will be sector 0 track 1, leaving 62 sectors of unused space between the MBR and first partition).
The only problem with aligning the partition to 63 virtual (512kb) sectors is if the disk internally used 4kb sectors, then there’s going to be a huge performance penalty because 63 * 512 is not a multiple of 4kb, so the OS will constantly be writing across sector boundaries and wasting time with unnecessary Read-Modify-Write cycles. In Windows Vista and onward Microsoft addresses this issue by starting the partition on the 2048th sector (leaving 1 MB of reserved space and 4kb aligning the partition), nobody is exactly sure why they chose to leave so much space, but when it comes to malware, 1 MB is a lot of storage. 
Space at then end of the disk
Because the space at the start of the disk can be pretty small and isn’t guaranteed on GPT systems, the space at the end may be a better bet. When allocating a partition, the Windows partition manager will end the partition before the end of the disk to leave space for dynamic disk information. As it happens, dynamic disks are incredibly rare on most computers because they’re only used for software RAID and other black magic, which leave between 1 mb and 100 mb of space at the end of the disk. 

Virtual File System

The location of the Virtual File System depends on the space needed and the system specifications, here’s a quick overview of the reserved space.
Start Of Disk
  • On XP systems using the MBR partition format you are guaranteed 62 sectors (31.7 KB) of space between the MBR and the first partition.
  • On Vista+ systems using the MBR partition format you are guaranteed 2047 sectors (1 MB) of space between the MBR and the first partition. 
  • Because the GUID Partition Table (GPT) is of variable size and not restricted to 1 sector like the MBR, it is uncertain how much space will be available on systems using the GPT.
  • Other than by the GPT, this space is never used by windows. 
End Of Disk
  • Between 1 MB and 100 MB, there doesn’t appear to be any OS specifications for the exact size so the variation is likely to do with disk geometry (Ex: 1 disk track is reserved).
  • Some of the space can be used for dynamic disk information (most system do not use dynamic disks unless using software RAID).
Contrary to popular belief, a VFS can be created and accessed by a user mode application, as long as it is running as administrator. To prevent malware from bypassing kernel code signing, raw disk access was “disabled” in vista and onward; however, there is an exception for boot sectors and sectors residing outside of the filesystem (both reserved areas reside outside the filesystem), enabling user mode access to the VFS. Although, direct user mode access is possible, most malware tends to manage the VFS from a kernel driver and expose an API to user mode components for reading/writing via the driver; This allows the VFS to be hidden from normal applications and other drivers.
It’s quite common for a VFS driver to send requests directly to the lowest level disk driver (the disk miniport), as a result the disk read/write requests cannot be intercepted by the antivirus or any standard disk monitors, providing better stealth. Although you could write standard files using this method, ntfs.sys handles the NTFS specification, so you’d have to create your own ntfs driver which would be a lot of work especially as NTFS is not fully documented by Microsoft. 
The actual format of the VFS is entirely dependent on the developer, some have chosen to use FAT32 with RC4 encryption, whilst others use custom file systems with modified encryption algorithms. Almost always the VFS is encrypted in an attempt to make the data look like random leftover bytes and not executables or log files.
Bootkits most commonly use a VFS because it reduces the attack surface to a single point of attack: The infected bootloader reads the rootkit driver from the VFS and loads it into the kernel long before the antivirus, leaving the kernel driver time to install hooks and cover its tracks before the OS even initializes. A bootkit using a VFS driver has only one weakness: The infected boot record; this can be easily resolved by using the bootkit’s driver to hook the disk miniport and spoof read/write requests to the boot sector, tricking the AV into thinking the boot sector contains the original Windows boot code, the same method can also be used to just display empty sectors if something other than the rootkit tries to read the VFS

Device Guard – The Beginning of the End for Malware?

Finally I manage to put together a computer capable of running Device Guard and I’ve had a little bit of time to play around with the code signing part. Everyone is probably already familiar with x64 driver signature enforcement (64-bit Windows systems can only load signed drivers); Well, now Microsoft has introduced a similar feature for user mode code, which is a huge deal when it comes to malware (Currently the feature is only present on Windows 10 Enterprise, but I’m fairly certain as it matures it will make it’s way to home systems).

Device Guard Code Integrity Policy

Device Guard not only adds customizable user mode code integrity checks (UMCI), but re-works a lot of the kernel mode code integrity (KMCI) allowing far more flexibility than just allowing all signed drivers. The policy can either be deployed locally by and administrator or from a domain controller, making it scalable for enterprise networks.
Something I was actually quite surprised by is the fact that the user mode code integrity is not simply limited to executable (I was expecting Device Guard to be just another throw away pseudo-security feature like UAC, but it’s clear some real thought has gone into this). 

Scope

Executables 
As already explained, Device Guard isn’t just a more flexible version of Kernel Mode Code Signing, it goes the whole nine yards with customizable code integrity policy for executables. Rather than using a flimsy software restriction policy, Device Guard can use an array of different settings to make sure only trusted executables are run. 
Executables violating the policy are simply blocked from running at all.
Dynamic Link Libraries
One of my favorite attacks against HIPS, firewalls, and software restriction policies is DLL hijacking. Simply put, when an application calls LoadLibrary(“somedll.dll”), the system first looks for the DLL in the KnowDlls registry key, followed by the applications working folder (where the application was run from), and finally system paths like System32. If you copied a legitimate system application to another folder, then placed an arbitrary DLL in the same folder and gave it the name of a DLL the application dynamically loads, it would load your DLL instead of the real one. Using this method you can bypass all kinds security checks by loading code inside a legitimate system application, without using code injection (which normally triggers HIPS).
Well, it seems Microsoft considered DLL hijacking this time around as all DLLs loaded by an application are checked against the code integrity policy; If a DLL violates the policy, the DLL and application will fail to load (the check is implemented in MiCreateSection, so should apply to any code loaded with NtCreateSection and SEC_IMAGE).
Trying to hijack explorer.exe with an unsigned DLL results in STATUS_SYSTEM_INTEGRITY_POLICY_VIOLATION
Windows Script Hosts & PowerShell
Another long standing issue with antiviruses is malicious scripts; Engines like PowerShell have the ability to access the Win32 API, allowing malware to leverage scripts in order to bypass binary scanning and perform almost all malicious tasks without the need for an executable. 
Device Guard introduces signing of of Windows Script Host scripts, as well as PowerShell to prevent malicious use. Unsigned PowerShell scripts are blocked and PowerShell itself is run in “constrained mode” which prevents it from executing arbitrary code via .NET scripting, COM interface, WinAPI, etc.
PowerShell is in constrained mode and blocks unsigned script.s

Flexibility

Device Guard provides a multitude of mix & match ways to define which applications and drivers can be run (known as file rules), allowing administrators to fine tune policies to their needs. 
Here’s a list of some file rule levels currently available:
  • PCA Certificate – All files signed with a leaf certificate belong to the whitelisted PCA Certificate (Ex: Any file signed with a VeriSign Extended Validation certificate).
  • Leaf Certificate – All files signed with a specific code signing certificate (the ones issued to vendors).
  • Hash – Allow a single file by its SHA2 hash (Good for unsigned applications).
  • FileName – Just…just don’t.
  • Publisher – Like PCA, but with the ability to only allow applications from certain publishers (the “common name” of the leaf certificate Ex: Only leaf certificates issued to Microsoft).
  • WHQL – Allow kernel drivers which are signed & verified by WHQL.
  • WHQL Publisher – Same as Publisher but only for signed & verified WHQL drivers.
Also allowed is the ability to specify a minimum file version with most of the rules, which is great for stopping malware exploiting old signed drivers to gain kernel mode execution. 
To start off, a policy can be created by scanning the current system and building a list of all all installed applications, then whitelisting them using whichever rule required (it’s also possibly to fall back to hashes or file names for unsigned files). By default policies are created with “Audit Mode” enabled, which means when the policy is installed, it won’t be enforced but will instead log all files which would have been blocked to the event log.
Example of a CodeIntegrity event
A very handy feature is the ability to create a second policy using the event log, then merge it with a first. This would allow the administrator to set up a test system and build a list of files which would be blocked by the current policy, then review and whitelist  them in a future policy.

Virtualization Based Protection of Code Integrity

This is where Device Guard really comes into its own: If the system is capable of Virtualization Based Security (VBS), Device Guard can be configured to use hypervisor technology in order to isolate parts of the kernel involved in security checks from the rest. With VBS enabled, even if malicious code does somehow manage to get into kernel mode, it would be unable to patch the code responsible for UMCI / KMCI, therefore incapable of installing any code to persist across reboot (or disable the code integrity policy altogether). 

Conclusion

If properly implemented, Device Guard can be used to create a system which is highly resilient to common malware (assuming UMCI, KMCI, and VBPCI are enabled and well configured).
  • UMCI prevents an adversary social engineering the victim into running malware (unless they can get hold of a whitelisted certificate). 
  • On Windows 10 Google Chrome & Internet Explorer run inside an isolated container known as AppContainer, so even if the browser was exploited, it’d be run in total isolation.
  • If the code somehow escapes AppContainer, it’d need a method of persisting across reboot, bearing in mind the UMCI policy prevents unsigned code being added to start-up and it’s kind of hard to exploit applications during boot.
Although it’s still early days, Device Guard is definitely a huge leap in the right direction towards putting an end to malware. Though it’s likely going to take some time for such a feature to evolve from a complex set of configurations aimed at experienced network administrators, to an out-of-the-box security system for end users.

Advanced Desktop Application Sandboxing via AppContainer

This post is kind of a follow on from my previous article Usermode Sandboxing, so if you’ve not yet read that you should do so first.

AppContainer was a fairly quietly introduced feature in Windows 8, which is a shame as it provides some great features which can be used for desktop application security too (Few people are aware that it’s not just used for Apps as the name might suggest). I’ll go over some of the features which stood out to me.
Network Restrictions
A feature previously lacking in the Windows integrity mechanism was proper network restrictions. Low integrity processes could still freely create sockets, which would allow malicious code to escape a sandbox by exploiting a vulnerable higher integrity process listening on the host.
AppContainer introduces some new network restrictions such as:
  • WinCapabilityInternetClientSid – Application can make outbound connections but not listen on sockets.
  • WinCapabilityInternetClientServerSid – Application can create listening sockets but not make outbound connections.
  • WinCapabilityPrivateNetworkClientServerSid – Application can listen or make outbound connections to IPs within the host’s local network (not to external networks i.e the internet), but only if the network is set to Work or Private. 
An additional restriction I’ve noticed is that by default the application can connect to localhost, but cannot interact with listening sockets created by applications outside of its container (Services, other Apps, etc), which would prevent the application from exploiting anything listening on localhost. 
Filesystem & Registry Restrictions
Inside the AppContainer variable such as %temp% and %localappdata% are reassigned to directories within that container (%localappdata%Packages), which is the only writable path by default. For registry the default accessible path is: HKEY_CURRENT_USERSoftwareClassesLocal SettingsSoftwareMicrosoftWindows CurrentVersionAppContainerStorage.
Although Apps can be assigned privileges such as WinCapabilityDocumentsLibrarySid (access to My Documents), this is implemented by the App broker process and will not work for desktop applications, instead one must explicitly add the AppContainer’s SID to the file/folder’s ACL’s from the process creating the container (Same goes for other objects such as sections and registry keys).
Process Isolation
Previously low integrity processes could interfere with other low integrity processes, but with AppContainer this is no longer the case. Listing processes will only show the system pseudo-process and any processes running inside that specific container (no desktop processes, services, or other applications), and it’s the same story for any other objects created outside of the container. This is pretty handy as browser worker processes usually run as low integrity, which meant that any malware run inside a sandbox would still be able to inject the browser and exfil data.
Kernel Mode Checks
All the actual access checks are part of the Windows kernel, so it’s not a case of just removing a few user mode hooks or performing direct system calls, access is restricted at kernel level making AppContainer a great improvement over old sandboxing methods.

Example Code

I’ve created a little example and test of the AppContainer capabilities in C, it creates a container and executes itself inside the container in order to test the restrictions (Obviously this will only work on Windows 8+ where AppContainer is available).
The test container is given permission to connect to network IPs (but not the internet), the broker also create a text file (%userprofile%Desktopallowed_test.txt) and grants the AppContainer access. Other than connecting to network IPs and accessing the App’s install directory or the explicitly allowed file, everything else is restricted.

Usermode Sandboxing

User mode Sandboxing

A lot of people (including myself, until recently) think that effective sandboxing requires a filter driver or kernel hooking, but this is no longer the case. A new security feature introduced in Windows Vista known as the Windows Integrity Mechanism can be used to create sandboxes that run entirely in usermode. Although the mechanism was not designed to be used this way, it makes for great driverless sandboxing.

The Windows Integrity Mechanism
Similar to User Account Contorl (UAC), the Windows Integrity Mechanism allows the system to restricted applications from accessing certain resources; however, it’s more defined than simply elevated/unelevated. There are 4 main levels provided, which can be set by a parent process prior to execution.
System Integrity (Mandatory LabelSystem Mandatory Level)
This is the highest integrity level and is used by processes and services running under the Local Service, Network Service, and System account. The purpose of this level is to provide a security layer between Administrator and System, even a process running as full Administrator cannot interact with with System integrity level processes (The only exception to this rule is if the administrator account is granted SE_DEBUG_NAME privilege, then the process can enables this privilege in its token to interact with processes across integrity and user boundaries).


High Integrity (Mandatory LabelHigh Mandatory Level)
The default integrity level assigned to processes running under the Administrator account, if User Account Control is enabled this level will only be given to elevated processes.
Medium Integrity (Mandatory LabelMedium Mandatory Level)
Given to processes running under a limited (non-Administrator) user account or processes on an Administrator account with UAC enabled. Processes assigned this integrity level can only modify HKEY_CURRENT_USER registry keys, files in non protected folders, and processes with the same or lower integrity.

Low Integrity (Mandatory LabelLow Mandatory Level)
The lowest integrity level is not assigned to processes by default, it is either assigned through inheritance (given to processes created by other low integrity processes) or set by the parent process. A process running with low integrity level can only create/modify keys under HKEY_CURRENT_USERSoftwareAppDataLow and write files to %USER PROFILE%AppDataLocalLow. It is practically impossible for a low integrity process to make any changes to the system; However, it can still read most data.
The windows integrity mechanism has a strict set of rules which makes it a nice system for process isolation (when used properly).

·         A process cannot change its own integrity level.
·         Once a process is running, the integrity level cannot be changed (even by a higher integrity process).
·         A process can create processes with the same (or lower) integrity level, but not higher.
·         Processes cannot modify/write processes/files with a higher integrity level.
There are a few (fairly low risk) exceptions to the above rules.
·         A high integrity process granted SE_DEBUG_NAME can modify processes of higher integrity level. 

·         A medium integrity process that is signed by Microsoft can elevate some COM objects from medium to high integrity (this is what gets leveraged by the auto-elevated process UAC exploit).
·         A process can request elevation from medium to high integrity, but only on execution (spawns UAC prompt). 
Communication between a low and higher integrity process (IPC) is possible when explicitly enabled by the higher integrity process. Any of the following methods can be used:

·         Shared Memory
·         Sockets
·         RPC
·         Windows Messages
·         Named Pipes

Usermode Sandboxing

In the past usermode sandboxes would inject a dll into sandboxed processes and hook various functions within ntdll, although this was generally quite effective, applications could escape the sandbox by reading ntdll from the disk and using it to restore the hooks. Now usermode hooks are making a comeback in sandboxing, but without the previous fallbacks.

Processes can be spawned as low integrity to preventthem making changes to the system; However, in order for the sandboxed process to continue functioning normally, it may need to make some (limited) changes to the system, this is where the hooks come in. 
The sandbox creates a broker process which runs with a normal integrity level, this process then uses CreateProcessAsUser to spawn the target (sandboxed) process at low integrity. Before the target process begins execution, the sandbox dll is loaded and hooks ntdll so the hooks can be used to pass information about any calls (target function, parameter addresses, number of parameters) to the broker process via IPC. The broker process will read the parameters from the sandboxed process and filter/process calls on its behalf. Unlike with previous usermode sandboxes, removal of the hooks will result in the process not being able to modify system resources as it requires the broker process to do so on its behalf. 

This type of sandboxing is already used by some applications (Such as Chrome, Internet Explorer, and Flash Player) to reduce the attack surface for exploits. Low integrity processes are used for processing and handling of untrusted data such as javascript or flash (As a result an exploit would first have to exploit the low integrity process and then exploit the sandbox process to gain full execution on the system).  

For malware sandboxing, things are a bit different: Because low integrity processes can still manipulate other low integrity processes (most browsers run as low integrity), sandboxed malware would still be able to inject into a browser process and pass data back to a command and control server. Low integrity processes are also not very restricted in terms of reading data and could log documents and program data. To protect malware from injecting into browsers or reading personal documents, it would be possible to run the sandboxed and broker process under a different user account (CreateProcessAsUser), aslLow and medium integrity processes cannot read documents from other user’s directories or interact with processes across user boundaries; However, they could still read from Program Files and System32. 

Conclusion

Although the Windows Integrity Mechanism is by no means perfect for malware sandboxing, it is definitely a considerable alternative to maintaining complex filter drivers and paying for code signing certificates. Windows 8 even introduces a new features, AppContainer, which nicely complements the Windows Integrity Mechanism by allowing processes to be restricting to only reading and writing within their install folder. If Microsoft could just manage to stop making Fisher Price user interfaces for one operating system, we may see anti-malware sandboxes shifting to usermode as people move away from Windows 7.

Automatic Transfer Systems (ATS) for Beginners

ATS is one of the newer techniques employed by banking malware that not many people are familiar with so I thought I’d do a small post explaining it. To fully appreciate the complexity of ATS we have to take a look at a brief history of financial malware and how they harvest financial information such as bank logins, I did write some individual posts about formgrabbers, and webinjects but figured a quick recap would be better.
FormgrabbingA formgrabber is a malicious module that is injected into the user’s browser and modifies the code flow to intercept POST requests between form submission and SSL/TLS encryption; as a result formgrabbing malware is capable of intercepting HTTPS requests before they are encrypted, thus can log usernames and passwords for HTTPS sites such as PayPal. All intercepted credentials would then be sent back to the C&C server where they would most likely be sold in bulk to other criminals willing to use them. Although formgrabbers work fine for most sites which only require usernames an passwords, banks generally require extra information during log in to prevent use of stolen credentials.
WebinjectsWebinjects are an extension to formgrabbing which adds the ability to intercept web responses, which nicely compliments the formgrabber’s ability to harvest credentials by intercepting requests. A response can be modified after the browser has decrypted it but prior to it being displayed to the user, allowing malware to modify any and all page content for any site the user visits. The main purpose of webinjects are to add fields on bank login forms to requests extra information that is required to log in, then when the form is submitted it is picked up by the formgrabber. Here’s an example of when webinjects are useful: My personal bank account requires a second password to log in and it’ll say something like “enter character 2, 6, and 7”, if the request was intercepted then the C&C would only have characters 2, 6, and 7 stored but next time the bank might ask for characters 1, 3, and 5, making it impossible for someone to log in until all characters have been logged (At the rate I log into online banking, this would take many months). A solution to this problem would be for the webinjects to add a message to the login page which says “To confirm your identity, please enter your full secondary password” followed by a text box, then upon log in all required information would be intercepted by the formgrabber and sent to the C&C.
The main problem with standard webinjects is they are completely useless for banks which use two factor authentication (2FA). If a bank texts a unique one-time code to a customer’s phone which they have to enter in order to log in, there’s no extra information that can be requested by the webinjects which would allow someone else to log in, other than the physical phone, though modifying the webpage to request that the victim mails their phone and pin code to a shady address in Russia is unlikely to fool most people.

Automatic Transfer System (ATS)

Under the hood ATS are simply just webinjects wearing a different hat, the purpose is shifted from gathering credentials for use/sale to automatically initiating wire transfers from the victims own computer (all without needing to log their credentials, bypassing 2FA and all anti-fraud measures).
Once the victim logs into their account normally, the webinjects would inject a script which would callback to the C&C with information such as account number, bank balanced, and bot unique ID; from here a decision on if to initiate a transfer would be made based on factors like bank balance and if any mules are available to receive the transfer (mules are people responsible for handling and laundering stolen funds). If the transfer is authorized, the script would then automatically fill out a transfer with an amount and mule’s bank account number, then submit the request from the victim’s logged in bank account (transfers could be initiated via XMLHttpRequest or by modifying something like a welcome page to contain the pre-filled transfer form hidden from view, which would then be submitted when the user clicks the “Close” button). A real major benefit of ATS comes in when cybercriminals are looking to steal money from secure corporate accounts; If an account were to require transfers to be approved using another one-time code, because the account owner is currently logged in it would be fairly simple for the ATS script to inject a pop up saying something along the lines of “your session has timed out, we’ve sent you a new one-time code which you can enter here to continue”, then pass that code on to the ATS script to silently approve the transfer. It’s also possible for ATS/Webinjects to “correct” the account balance and any pages containing information about the transfer to conceal any funds stolen by the system, leaving the victim completely unaware that anything happened until they log in on a computer that isn’t infected.

Conclusion

Due to the fact ATS scripts must be individually tailored and maintained for each bank, and the large amount of money mules required to maintain cash flow, malware making use of ATS is still fairly uncommon and mostly restricted to large groups such as the one behind the Dridex malware. It may also be possible that ATS becomes even more uncommon with criminals opting to just ransomware the victims and have them handle the sending of funds themselves, rather than stealing them.

Windows Integrity Mechanism Resources