Hack the Box – #5 – Bashed

The last box I didn’t get root access on the first time I tried is Bashed, a Ubuntu Linux web server being used for what appears to be a personal blog. The blog is about a web shell that was developed by the author of the blog and seems to be in use on the server itself, possibly for testing as it’s in the /dev directory. Once we use this to get access to the machine, we find a /scripts directory that seems to run every file in it as root every so often and creating a file here leads to the eventual privilege escalation.

I liked this one and can see why I had issues with it last time as I ended up needing to bounce between multiple accounts and shells to eventually get root. Below is a rough outline of the path I took.

  • Web shell > User shell (www-data) > User-shell (scriptmanager) > root shell

As usual, I started with an nmap scan of the IP. It showed only one port open, HTTP on port 80.

nmap -sC -sV 10.10.10.68

Looking into the website itself, it appears to be a blog for someone tracking the development of a web shell project, even including a link to a github page.

Blog home page
Blog entry about the ‘phpbash’ project, a web shell on github

Looking around the blog and github page suggested the owner of the blog developed a web shell and had tested it on the same server the blog is hosted on. I ran gobuster to enumerate other directories and found a few promising ones, most notably the /dev directory.

gobuster results for the web server

When investigating /dev I found the same two files as were listed on the github page: phpbash.min.php and phpbash.php. This looks to be where the user was testing their project. If that’s the case, ‘phpbash.php’ should be a fully functional web shell for this server.

/dev directory found with gobuster

It looks like phpbash.php is the web shell we were looking for and allows us to run commands on the server directly from the browser as the www-data user.

Functional web shell found in /dev directory

This opens up some possibilities, but the first thing we need is an actual reverse shell to the machine for ease of access. The normal method of using netcat to connect to a listener on my machine and using the -e flag to execute bash did not work, so I had to find another way. I found an article from SANS on this exact subject that provided steps on how to create a new named pipe for use with netcat that essentially functions the same way as ‘-e /bin/bash’ without actually doing so.

Creating reverse shell without netcat -e functionality

When combining the two commands above with a netcat listener on my machine, I got a reverse shell as the www-data user.

Catching reverse shell from www-data user

Ok, so now we have a shell on the machine, but only as www-data. How do we escalate privileges? One of the first steps is checking what sudo privileges our current user has.

Sudo permissions for www-data user

Interestingly, this shows us we can sudo anything with no password needed as long as we run the command as the scriptmanager user. I transfered the LinEnum script over to the machine through netcat and ran it, but it didn’t give much useful information. However, I did find a folder in the root directory called “scripts” that was owned by the scriptmanager user.

Root directory showing folder owned by scriptmanager user

Using our sudo permissions to run commands as the scriptmanager user, I checked the contents of this folder. It had one python script that appeared to be writing to a text file in the same folder.

Contents of /scripts directory
Scriptmanager script to write to test.txt

The interesting part here is that the file being written to, test.txt, is owned by the root user and not scriptmanager. This means that, in order to have the necessary access to modify the test.txt file, the Python script is likely being executed by root automatically at some point (or more likely periodically). I was running into some permissions issues using “sudo -u scriptmanager” for every command, so I setup another shell using the same method as before (but this time with a pipe named “backpipe2”). The screenshots below show the commands and listener, albeit a little jumbled due to how the shell was reacting.

Creating another shell using same method as before
Catching reverse shell from scriptmanager user

Now that we have a shell as the scriptmanager user, we have access to add files to the /scripts directory that should then be executed by root. I created the Python file with the code below from the pentestmonkey.net site to create yet another shell back to my host machine, but this time hopefully as the root user.

Python file added to /scripts folder to create one more reverse shell

Once the shell.py file was saved and my listener was created, we got a connection and finally had root access.

Catching final reverse shell from root

That’s all for this one and the last root flag I missed from earlier this year. Next time will be on to another new machine I haven’t attempted before.

Recommendations

  1. Separate development projects/websites from production servers. If development code is required to be in a production environment, it should require a login before being accessible.
  2. Administrative functions requiring root level privileges should require an account with root access. The use of normal accounts, especially those running the web server (i.e. www-data), with additional sudo privileges provides attackers potential methods for privilege escalation.

Hack the Box – #4 – Optimum

I started doing Hack the Box about 8 or 9 months ago and, of the boxes I tried, I never managed to get root on two of them. Since it bothers me not seeing an equal number of user and root flags when I look nowadays, I went back and did them again to get the root flag.

The first was Optimum, a Windows Server 2012 machine running a vulnerable software called HTTP File Server. I think the first time I did this machine I got the user shell using a metasploit module for the vulnerability I’ll show later, but I’m going to do this one entirely without metasploit to practice for the OSCP.

The regular nmap scan shows only one open port, HTTP on port 80 running HTTPFileServer 2.3.

nmap -sC -sV 10.10.10.8

Visiting the page in a web browser gives a few options to work with and confirms the version of the software being used is HTTPFileServer 2.3 which, after a quick Google search, appears to be owned by a company called Rejetto.

HTTPFileServer 2.3 landing page

I tested the options and buttons on the page, but didn’t find anything useful for gaining a foothold on the machine. I moved on to using searchsploit for any exploits in the HFS software and found a few options. I settled on a python script that claims to give Remote Code Execution when used against HFS version 2.3, which the server is running.

Searchsploit results for HFS

Reading through the script, it says we need to have a web server hosting nc.exe, likely to transfer to the target machine and create a connection back to us. I also modified the IP address and port the script should connect back to for our reverse shell when the script is run.

Usage details in script found with Searchsploit

I setup a python SimpleHTTPServer in the Kali directory that stores Windows binaries for various files, including nc.exe, to serve the executable to the target.

Python SimpleHTTPServer to serve nc.exe to the target machine

I also used netcat in another tab to listen on the port designated in the script for the reverse shell to connect back to. When the script was run, nc.exe was copied from the directory above to the target and a command shell was opened back to my machine as the user ‘kostas’.

Netcat listener catching the reverse shell when script was run

Now that I have command line access to the machine, I poked around for a bit checking what software was installed and looking for anything useful stored on the file system. I didn’t find anything useful, so I moved on to a tool called “Windows Exploit Suggester” (here). To use this tool, I ran systeminfo on the target machine, pasted it into a file on my machine, and used it as input into the python script. The script reads the specific software operating system information and suggest exploits based on what it finds.

Results of Windows Exploit Suggester

Based on the results it gave, I settled on one for MS16-098 that exploits a vulnerability in the Win32k kernel-mode driver and was listed on exploit-db. I copied the script onto my machine, but then we had the question of how to get it onto the target machine to run. I decided to create a python SimpleHTTPServer again and use the Powershell method Invoke-WebRequest to download a copy to the server and name it test.exe.

Powershell command to download copy of script for privilege escalation

With the file now on the machine, I ran it, but didn’t see any noticeable change other than what seemed to be a new version of the command shell. However, when checking our access, we’re now running as SYSTEM.

Privilege Escalation script running and getting SYSTEM shell

That’s it for Optimum and the root flag that eluded me earlier this year. The last machine I have user, but not root on is Bashed, so that will be the next target.

Additional Notes

The version of Windows Exploit Suggester I used here hasn’t been updated in a few years and there’s a newer version of it made by someone else. I tried both and they both appear to work well, but I prefer the output of the older version.

Recommendations

  1. Enforce a regular patching cycle to keep up to date on important/critical Microsoft security updates.
  2. Upgrade to a more secure software to serve as an HTTP File Server. If not possible to replace, at least update the current implementation to the newest version (2.3m).
  3. Disable Powershell usage for non-administrator users.

Hack the Box – #3 – Bank

The next machine from Hack the Box is Bank, an Ubuntu web server hosting a website for a…wait for it… a bank.

Starting with the regular nmap scan, we see ports 22, 53, and 80 open, with the default Apache home page showing on the web site.

nmap -sC -sV 10.10.10.29

The first thing I checked was the web page and ran gobuster to try and find any useful sub-directories. However, there didn’t seem to be anything to work with. On a hunch (based on previous HTB machines), I added an entry to my host file to associate the machine’s IP with ‘bank.htb’. Once this was done, visiting bank.htb re-directs to the login page below for a fake bank.

bank.htb landing page

I tested a few common default credentials, but, not surprisingly, they didn’t work. I re-ran gobuster on http://bank.htb instead of the IP used earlier and found several new directories. Three just held the files used to load the website and nothing sensitive, one I didn’t have access to view, but /balance-transfer looked interesting.

gobuster results for http://bank.htb

Visiting this page gives a list of what appear to be individual bank transactions with encrypted customer information.

List of transactions
Encrypted information in each transaction log

There were a large number of transactions listed on this page and all of them, except one, had a size listed between 580 and 585. The one below stood out for being less than half the size of the others.

Opening this transaction shows clear-text credentials for the customer Christos Christopoulos on a transaction that appears to have failed to be encrypted.

Using these credentials on the bank login page found earlier allows us access to the customer’s dashboard, showing various pieces of account information.

The dashboard also has an option for “Support”, which leads to what seems to be a way of submitting a ticket and allows for a file to be uploaded.

My first reaction was to create a malicious php file with msfvenom and upload it through this page, hoping we can run it somehow on the web server. Below is the command used to generate the php code that was then copied into a file called “shell.php”.

msfvenom php code generated to upload to web server

Unfortunately, the site gives an error that only image files are allowed to be uploaded when trying to upload shell.php. Modifying the file name to an extension used for images uploads successfully, but isn’t very useful if we can’t execute the code. After a few other fruitless attempts, I looked at the source code for the page and found a way around their upload limitation using debug functionality that was not removed.

Source code for support.php revealing an extension used for debugging

I re-named my php file to shell.htb and tried to upload it one more time. This time it worked successfully and my information/file was listed under the “My Tickets” section on the left side of the page.

File re-named to shell.htb
shell.htb file successfully uploaded

Before clicking the “Click Here” option for my attachment, I started a listener in metasploit to catch the connection, assuming it was going to work. Luckily, the php code executed when the attachment was viewed and it connected back to my listener, giving me a meterpreter shell on the machine as the www-data user.

Now that we’re on the machine, we need to find how to escalate privileges. Looking for SUID files is usually my first step, so I dropped into a shell from meterpreter and used python to upgrade the functionality.

From my new shell, I ran a search for any files with the SUID bit set. One in particular stood out, a file called “emergency” in a non-standard directory.

Using cat on the file doesn’t give any useful information as it appears to be a compiled binary, but the binary is owned by root and can be executed by the www-data user. Running the file doesn’t do anything immediately noticeable, other than replacing our standard prompt with a #. Testing the prompt reveals it has created a new shell running with an euid of root.

And that’s all there is for Bank. I enjoyed this one, mainly because the last few I’ve done have ended up being pretty basic once you figure out what kind of exploit is needed.

Additional Notes

As this server was also running a DNS service, some additional enumeration could be done around this. I used dig to attempt a zone transfer on the server and found the sub-domains below, but they didn’t really help me get anywhere, though it’s very possible (and even likely) that I missed something.

Recommendations

  1. Restrict access to web directories that do not need to be publicly visible.
  2. Enable alerting of some type for when a transaction log fails to be encrypted.
  3. Ensure any additional functionality used for debugging is removed before code is put into production.
  4. Remove the use of files on the server that allow a regular user access to a shell with root privileges. If additional privileges are needed, an account with appropriate privileges should be used.

Hack the Box – #2 – Grandpa

I have a little free time since I’m in Alabama for the next few days, so I’ll probably post a few of these. For now, I started with Grandpa, an easy Windows Server 2003 box, but one that seems to be a little unstable at times. I had to reset it a few times because the website started giving odd errors even when I hadn’t tried to exploit anything.

I started with the usual nmap scan which showed us only one open port, 80, but some interesting information on the HTTP methods that seem to be allowed.

nmap -sV -sC -p- 10.10.10.14

The first thing I investigated was the use of the PUT method listed as potentially allowed. If this method works, I could upload a file to the web server, allowing multiple ways to get a shell. As the nmap scan showed the server was using WebDAV, I connected to it using the cadaver tool built into Kali for WebDAV management. Unfortunately, it doesn’t look like we have access to upload files.

Using cadaver to test uploading files through WebDAV

Moving on to other options, I used searchsploit to look for exploits in Microsoft IIS 6.0. There were a few for this specific version, but a buffer overflow in WebDAV looked promising. Unfortunately this time, this was only a proof-of-concept and the shellcode used only launched calc.exe rather than a reverse shell. We could generate new shellcode with msfvenom if we wanted, but instead I chose the easier method of checking for a metasploit module that does the same thing.

Searchsploit results for “Microsoft IIS 6.0”

With metasploit loaded up, I searched for exploits in “webdav” and got around 25 results. Luckily, one of these seemed to be exploiting the same vulnerability as the searchsploit file I saw earlier for a buffer overflow in “ScStoragePathFromUrl”. This uses the PROPFIND HTTP method that was seen in the nmap request above.

Metasploit info for WebDAV buffer overflow module

Running this module against grandpa gives a successful reverse shell, but there seemed to be some access issues and we couldn’t even get the ID of the user we were connected as.

This can happen from time to time, but migrating to another process usually fixes the issue. I ran ‘ps’ in the meterpreter window to get the current running processes and, as it was the only user account listed, migrated into a process owned by “NT AUTHORITY\NETWORK SERVICE”. This worked successfully, but unfortunately this user doesn’t have very many permissions.

I poked around with this account for a bit, but it didn’t seem to have permission to do anything useful like uploading files to the web server. directory. Next, I turned to the metasploit module “local_exploit_suggester” which examines the system info for any given session and tests appropriate modules against it. This suggested 9 potential exploits for privilege escalation.

I chose “ms15_051_client_copy_image” which exploits a vulnerability in the win32k.sys driver. With this, I successfully get a shell as SYSTEM.

And that’s it for this box. Or is it?

I went back after being done to try some other methods and found a way to get a SYSTEM shell using the first metasploit module, but through a different target path.

I ran nikto on the web server and noticed a directory mentioned a few times that did not show up when I enumerated the box earlier with gobuster (which I also didn’t get a screenshot of sadly).

As “admin” was mentioned in some of the paths, I thought it might be worth trying to see if it provided a different level of access. I added this path to the metasploit module that had previously only given me access to the “NETWORK SERVICE” account.

Lo and behold, this time we get a SYSTEM shell.

Now we’re actually done with this box. I think the Granny box is similar to this one, so that’ll be my next target.

EDIT: Granny turned out to be almost exactly the same as this one and I was able to get root using the same steps, so I won’t do a new post for that one.

Recommendations

To finish it off and practice what would actually be done in a pentest, below are my recommendations for how to remediate the vulnerabilities I found. Some will be a little obvious since Hack-the-box machines are intentionally setup like this for practice.

  1. Upgrade to a more modern OS. My recommendation would be at least Windows Server 2012 as support for Server 2008 and 2008 R2 ends in January 2020.
  2. Institute a regular patching cycle to ensure out of date software is not left in production longer than needed.
  3. Disable any HTTP Methods that are not absolutely necessary.

Hack the Box – #1 – Beep

It’s been a while since I posted anything here, but with Rose being my only follower and likely waiting on the edge of her seat for the next post, here we go.

I worked through a few more chapters in Practical Malware Analysis back in May, but never wrote up the labs unfortunately. Instead of continuing down that path, I’m going to go in a completely different direction and start writing up walk-throughs of retired machines from Hack-the-Box as I find those a lot more fun at the moment. This week’s target is an easy Linux machine named “Beep”.

First, I started with the normal nmap scan of the box, with the output below.

nmap -sC -sV 10.10.10.7

There are more ports open here than usual, but the obvious ones to check first are 80 and 443 to see what web pages are available. When visiting http://10.10.10.7, the page just re-directs to the HTTPS version, so we’ll work from there.

After checking the certificate for any useful information (there wasn’t any), I loaded https://10.10.10.7, which appears to be a login screen for Elastix. A quick side trip to Google says Elastix is used for managing PBX software.

I tried the usual default logins (admin:admin, admin:password, etc.), but didn’t have any luck. My next step was to run gobuster on the site to find any other visible directories worth investigating. After a short scan, I got the results below.

There were several directories worth checking, but /admin is where I started and was met with a login prompt for “FreePBX Administration”.

I followed the same steps as the first login and tried well-known default credentials, but they didn’t work here either. However, when cancelling this window, we were re-directed to a FreePBX page that disclosed the version of the software in use of the server.

There were a few paths we could have gone at this point, but I chose to move back to the Elastix software and search for any well-known vulnerabilities/exploits. Searchsploit gave a few results involving cross-site scripting that wouldn’t be of use here, but a local file inclusion looked promising.

The script appeared to exploiting a vulnerability in a php file used by Elastix that allowed directory traversal and reading of a configuration file on the server.

I tried running the script, but it failed, so I borrowed the path used for the LFI and pasted it directly into the browser. The result was a page full of text that was hard to read, but had multiple mentions of ‘users’ and ‘passwords’.

Viewing the source of the page made it much easier to read and extract some credentials from the configuration file being shown (/etc/amportal.conf). There were several usersnames and passwords listed through the page, but the most important seemed to be “admin” with a password of “jEhdIekWmdjE”.

Going back to the /admin login and using these credentials allowed me access as the “admin” user.

Checking for password re-use, I was able to ssh directly into the box as root with the same password. From here we could get both the user and root flags.

And that’s all for this box. There are probably other ways to solve this one, but I’m going to move on to a new machine for now.

Practical Malware Analysis – Chapter 7: Analyzing Malicious Windows Programs

This chapter focused on the common Windows functions and tools that are used in Malware and provided some useful examples of how they can be used to affect the system or provide persistence.

Lab 7-3 took a while to analyze as it was pretty complicated. I didn’t have a lot of free time this week to dig deeper, but I wanted to finish this one up and post it so I can keep moving on to other chapters.

Lab 7-1 (Lab07-01.exe)

Question 1: How does this program ensure that it continues running (achieves persistence) when the computer is restarted?

It creates a service called Malservice that is set to automatically start when the computer restarts.

Question 2: Why does this program use a mutex?

The mutex is used to ensure there is only one instance of the malware running on the target computer.

Question 3: What is a good host-based signature to use for detecting this program?

A useful host-based signature would be a service called “Malservice” or the mutex “HGL345”.

Question 4: What is a good network-based signature for detecting this malware?

The malware reaches out to http://www.malwareanalysisbook.com using the user-agent “Internet Explorer 8.0”.

Question 5: What is the purpose of this program?

The purpose of this program seems to be to attempt a denial of service attack on the http://www.malwareanalysis.com website. It sets the “DueTime” value to midnight on January 1, 2100 and starts into a loop of connecting to the website above to download the home page over and over again. The second screenshot below shows how the program uses the InternetOpenURLA function to download http://www.malwareanalysisbook.com” and then jumps right back to the start of the same section to repeat the action again.

Setting the time to stop connecting
Infinite loop of downloading website home page

Question 6: When will this program finish executing?

Never. When the system time reaches the “DueTime” value (1/1/2100) it will create 20 different threads that will all be running an infinite loop of connecting to the website.

Lab 7-2 (Lab07-02.exe)

Question 1: How does this program achieve persistence?

When this program is run, it immediately reaches out to http://www.malwareanalysisbook.com/ad.html” over http and launches an instance of Internet Explorer attempting to connect to the site. However, it doesn’t seem to attempt persistence as it stops running after connecting to the site without making any changes to the OS/registry.

Question 2: What is the purpose of this program?

It seems to attempt to show an ad to the user. Mine did not load the actual page due to how my VM is networked, but we can assume from the name of the page (ad.html).

Question 3: When will this program finish executing?

It finishes running once it loads the website above.

Lab 7-3 (Lab0703.exe and Lab07-03.dll)

Question 1: How does this program achieve persistence to ensure that it continues running when the computer is restarted?

It copies the Lab07-03.dll file into a new file at C:\Windows\system32\kerne132.dll (with a 1 instead of l).

Question 2: What are two good host-based signatures for this malware?

The two host-based signatures would be the file “kerne132.dll” listed above and the mutex created called “SADFHUHF”.

Question 3: What is the purpose of this program?

This file creates a backdoor into the computer that is very difficult to remove.

When the .dll file (kerne132.dll being a copy of Lab07-03.dll) is run it reaches out to 127.26.152.13 and attempts to connect. If it can’t connect, the socket is closed and the program terminates. If it can connect, it will either sleep for 393 seconds (listed as 0x60000 seconds, so this might have been a mistake meant to be a decimal) or create a process to run a command, based on the command received (either “sleep” or “exec”). After each command is run, it loops back to 0x100010E9 to try and connect to the site again and start the process over. If at any point it can’t connect or receives a “q” command, it will close the socket and terminate the program.

Question 4: How could you remove this malware once it is installed?

It is difficult to remove because the program searches the entire C: drive for any .exe file that uses kernel32.dll and replaces that reference with kerne132.dll. There is some complicated comparison and file modification that happens, but essentially it forces kerne132.dll to be imported by any .exe file on the system, which will still have the same functionality as the normal dll, but will also come with the backdoor described in question 3.

The easiest way to remove the malware would be to re-image the machine with so many applications affected. However, it should be possible to edit the malware by reversing the values stored for the strings “kernel32.dll” and “kerne132.dll” and by doing so have the malware itself fix all of the affected applications when run a second time.

Practical Malware Analysis – Chapter 6: Recognizing C Code Constructs in Assembly

As we move through the book, I’m noticing myself starting to become more comfortable reading assembly and able to recognize what some functions do more quickly. It still takes me a long time (and a good bit of googling sometimes) to figure out what exactly is happening at the assembly level, but hey, it’s progress.

Chapter 6 was interesting in that it takes the basic aspects of a programming language (in this case C) and shows how they are implemented in Assembly to help an analyst pick out the patterns more easily. It covers some of the concepts I’m already familiar with, at least at a basic level, such as if statements, loops, and arrays, but also adds a little more complexity with structs and linked lists. I had to look up some of the C syntax for structs and linked lists to get a better idea of why they’re formatted like they are, but it at least makes enough sense for me to get through the labs now.

Lab 6-1 (Lab06-01.exe)

Question 1: What is the major code construct found in the only subroutine called by main?

It’s an if statement that prints a message depending on the outcome of the “InternetGetConnectedState” function. If the function returns 0, it will print a message stating there is no internet, otherwise it will print a message indicating the computer has an internet connection.

Question 2: What is the subroutine located at 0x40105F?

As the subroutine follows the push of the strings mentioned above, it is likely printing the string to the shell. This is confirmed when running the program from the command line.

Question 3: What is the purpose of this program?

The purpose seems to be just to check the internet connection of the computer it is running on and print a success/failure message.

Lab 6-2 (Lab06-02.exe)

Question 1: What operation does the first subroutine called by main perform?

The first subroutine called is sub_401000 and performs the check for an internet connection that was used in Lab6-1.

Question 2: What is the subroutine located at 0x40117F?

This seems to have the same function as sub_40105F in the last lab. It seems to print the result of the internet connectivity check to the screen.

Question 3: What does the second subroutine called by main do?

The second subroutine, sub_401040, is called if there is an internet connection and tries to connect to the URL “http://www.practicalmalwareanalysis.com/cc.htm&#8221;. If it successfully connects to the site it will attempt to read the cc.htm file and, if there is an HTML comment in the file, read a command from after the comment. The second screenshot below shows the steps it takes on the right hand side to iterate through an array of the characters in the html file. If it reads the first three characters as “<!–“, or the beginning of a comment, it will store the next character as the command. If any of these steps fail it will print an error message.

Question 4: What type of code construct is used in this subroutine?

This subroutine uses an array to store information read from an html file to try and retrieve a command. It iterates over the html file looking for a comment at the beginning (starting with the characters “<!–“).

Question 5: Are there any network-based indicators for this program?

The network-based indicator would be an attempted connection to “http://www.practicalmalwareanalysis.com/cc.htm&#8221; or the user-agent it creates to connect to the URL “Internet Explorer 7.5/pma”.

Question 6: What is the purpose of this malware?

This malware builds on the first from Lab 6-1 by checking for an internet connection and, if so, attempting to connect to a URL to get a command from a file stored there. If it is able to connect and successfully retrieve a command it will then sleep for 60 seconds.

Lab 6-3 (Lab06-03.exe)

Question 1: Compare the calls in main to Lab 6-2’s main method. What is the new function called from main?

The new function called is sub_401130, which can create a directory, create/delete a file, create a registry key, sleep for 100 seconds, or print an error depending on which command it is passed.

Question 2: What parameters does this new function take?

The sub_401130 function takes two parameters: the command character parsed from the previous function and “argv[0]” which is a standard parameter for the main function and isn’t very useful for us.

Question 3: What major code construct does this function contain?

This function uses a switch statement.

Question 4: What can this function do?

Depending on the file name parameter passed, this function can: create a Temp directory, create the new file cc.exe in the Temp directory, delete the file from the Temp directory, create a registry key to have the cc.exe file run on startup, set the program to sleep for 100 seconds, or try to read a command from the website again.

Question 5: Are there any host-based indicators for this malware?

The two host-based indicators would be the malicious file at C:\Temp\cc.exe or the registry key “Malware” under HKLM\Software\Microsoft\Windows\CurrentVersion\Run.

Question 6: What is the purpose of this malware?

This malware starts the same as the first two labs by checking for an internet connection, connecting to a website to download a file and get a command, then, depending on the command, will perform one of the actions from question 4.

Lab 6-4 (Lab06-04.exe)

Question 1: What is the difference between the calls made from the main method in Labs 6-3 and 6-4?

The main function now includes a loop that will continue trying to connect to the website and get a command until var_C is greater than or equal to 1440.

Question 2: What new code construct has been added to main?

A for loop.

Question 3: What is the difference between this lab’s parse HTML function and those of the previous lab?

It takes a parameter now, the counter from the main function, and calls _sprintf when creating the user agent to add the parameter passed to the end of the agent string. This makes the agent string dynamic, allowing the malware creator to track how long it has been running.

Question 4: How long will this program run? (Assume that it is connected to the Internet.)

24 hours. Each time it goes through the process it sleeps for 60 seconds after successfully parsing a command and the while loop runs while the incremental value is less than 1440 (and 1440 minutes is equal to 24 hours).

Question 5: Are there any new network-based indicators for this malware?

The user-agent changes depending on how long the malware has been running. An indicator could be to look for the agent “Internet Explorer 7.50/pma%d”.

Question 6: What is the purpose of this malware?

The malware starts working the same way as the previous labs by checking an internet connection, parsing an html page for a document starting with a comment (“<!–“), reads the comment for a command to pass to the malware and chooses between multiple options based on the command received. Where this version differs is that it implements a for loop in the main function that will continue to run (if there is still an internet connection) for 24 hours. It also modifies the user agent used when parsing the website by adding a number to the end of the string that matches how long the program has been running. If it doesn’t find an internet connection on any iteration, the program terminates.

Practical Malware Analysis – Chapter 4 & 5: Adventures in Assembly Code

Chapter 4 starts off with a brief explanation of the different types of programming languages (machine code, low-level/assembly, high-level, and interpreted) and how their interaction with the computer differs. I’ve dabbled in various interpreted languages, such as Python and Java, and even experimented with a high-level language like C, but I’m not what I’d call proficient in any of them. Assembly code is an entirely different beast. The book focuses on assembly code for the x86 architecture, which is what most 32-bit personal computers use, so the book is showing it’s age a little bit in this regards, but it says x64 will be covered briefly in a later chapter.

I’m not going to try and explain how assembly code works as it still seems like mostly black magic to me at this point. I’ve had a little exposure to reading and manipulating assembly code when practicing buffer overflows in “Penetration Testing: A Hands-On Introduction to Hacking” by Georgia Weidman, and this book covers much of the same basic information, but the chapter 5 labs definitely left me feeling a lot more comfortable with at least the basics and how to navigate it using IDA.

Chapter 4 doesn’t have any labs as it’s just an introduction to assembly and the chapter 5 labs focus on practical application of that knowledge.

Chapter 5 is entirely devoted to the IDA Pro disassembly application by Hex-Rays. There is only 1 lab for this chapter, but that one lab has 21 questions to ensure we get a lot of experience poking around the tool.

Lab 5-1 (Lab05-01.dll)

Question 1: What is the address of DllMain?

0x10000D02E

Question 2: Use the Imports window to browse to gethostbyname. Where is the import located?

“gethostbyname” is located in the WS2_32 library at address 0x100163CC in memory.

Question 3: How many functions call gethostbyname?

By searching for cross-references to the gethostbyname import, we see it is referenced 9 times.

Question 4: Focusing on the call to gethostbyname located at 0x10001757, can you figure out which DNS request will be made?

When looking at this call, we see the first instruction is to move the data stored in offset 10019040 into eax and then add 0xD to it. If we double-click on the offset, it shows us the data stored in that location – “[This is RD0]pics.practicalmalwareanalysis.com”. Adding 0xD (13) to this, we get “pics.practicalmalwareanalysis.com” as the address the program is trying to resolve.

The call to “gethostbyname” at 0x10001757
The data stored at offset 0x10019040

Question 5: How many local variables has IDA Pro recognized for the subroutine at 0x10001656?

IDA recognizes 20 local variables at this address. The book says there are 23 variables, so it seems IDA Free has a 20 variable limit.

Question 6: How many parameters has IDA Pro recognized for the subroutine at 0x10001656?

IDA found 1 parameter. See “arg_0” in the screenshot above.

Question 7: Use the Strings window to locate the string \cmd.exe /c in the disassembly. Where is it located?

It’s located at 0x10095B34.

Question 8: What is happening in the area of code that references \cmd.exe /c?

This area of code seems to be used for creating a string that will call cmd.exe on the user’s system, possibly to get a reverse shell. In the screenshot below, the variable “CommandLine” in the top box gets assigned the value of the “GetSystemDirectoryA” function. The next step after the cmd.exe push concatenates the CommandLine variable from before with the command for cmd.exe, creating a command to open a shell (i.e. “C:\Windows\System32\cmd.exe /c”.

Question 9: In the same area, at 0x100101C8, it looks like dword_1008E5C4 is a global variable that helps decide which path to take. How does the malware set dword_1008E5C4? (Hint: Use dword_1008E5C4’s cross-references.)

The malware assigns a value to dword_1008E5C4 at the beginning of subroutine 10001656 at the very beginning of the program. It assigns the value of eax to dword_1008E5C4 and then calls sub_100036C3, which seems to gather information about the operating system. In the 2nd screenshot below, the subroutine will return 1 if the platform ID == 2 and MajorVersion == 5, else it will return 0. This all comes together to decide which version of the command prompt text to use based on the operating system of the computer. In screenshot 3, we see that if it returns 1 it will use “command.exe /c” and it if returns 0 it will use “cmd.exe /c”.

dword_1008E5C4 assignment
sub_100036C3 checking information on the OS
Choosing which command prompt to use based on OS version

Question 10: A few hundred lines into the subroutine at 0x1000FF58, a series of comparisons use memcmp to compare strings. What happens if the string comparison to robotwork is successful (when memcmp returns 0)?

If the comparison is successful, it calls the subroutine sub_100052A2, where it queries a registry value at “SOFTWARE\Microsoft\Windows\CurrentVersion” for the value of the “WorkTime” key. Once it has the value, it converts it to an integer and pushes it in the format “\r\n\r\n[Robot_WorkTime :] %d\r\n\r\n” through an open network socket. It then does the same thing for the “WorkTimes” key.

Question 11: What does the export PSLIST do?

It first queries the OS version using the same sub_100036C3 as before and continues on the version is 5,2 (it just returns if the version is not 5,2). It then checks the length of a string it has been given. If the length is not equal to zero, it calls sub_10006518 where it searches through active processes trying to find a match. If the string length is equal to zero, then it does similar, but returns a list of all active processes.

Question 12: Use the graph mode to graph the cross-references from sub_10004E79. Which API functions could be called by entering this function? Based on the API functions alone, what could you rename this function?

This function could call the “GetSystemDefaultLangID”, “sprintf”, “strlen”, and “sub_100038EE” functions. It could be named to match the function it calls or something similar to “GetDefaultLanguage”.

Question 13: How many Windows API functions does DllMain call directly? How many at a depth of 2?

The DLLMain function calls CreateThread, strncpy, strlen, and _strnicmp.

At a depth of two, DLLMain calls 33 total API functions including Sleep and a variety of network-related functions like socket, connect, recv, and send. The screenshot below shows all of the functions (API functions are pink) with DLLMain circled in red for reference.

Question 14: At 0x10001358, there is a call to Sleep (an API function that takes one parameter containing the number of milliseconds to sleep). Looking backward through the code, how long will the program sleep if this code executes?

In this section, eax is first given the value of the string at 0x10019020 – “[This is NTI]30”. It then adds 0Dh (13) to the value, setting the string as “30”. In the next few steps it converts the string “30” to the integer 30 and multiplies it by 3E8h (1000). Judging by this, the program will sleep for 30000 seconds or 30 seconds.

Question 15: At 0x10001701 is a call to socket. What are the three parameters?

The three parameters of socket are all integers: af, type, and protocol. In this program, they’re passed the values 2, 1, and 6.

Question 16: Using the MSDN page for socket and the named symbolic constants functionality in IDA Pro, can you make the parameters more meaningful? What are the parameters after you apply changes?

Yes, after the changes the parameters are changed to AF_INET (af), SOCK_STREAM (type), and IPPROTO_TCP (protocol).

Question 17: Search for usage of the in instruction (opcode 0xED). This instruction is used with a magic string VMXh to perform VMware detection. Is that in use in this malware? Using the cross-references to the function that executes the in instruction, is there further evidence of VMware detection?

Yes, we find the “in” instruction in the subroutine sub_10006196. The instructions here copy the hex value 564D5868h into eax (which is VMXh in ASCII) and then call “in” on eax. There are cross-references to 3 functions in the program that all call this subroutine and they all include the string “Found Virtual Machine,Install Cancel.”.

Question 18: Jump your cursor to 0x1001D988. What do you find?

Starting at 0x1001D988 we see a list of readable ASCII characters, followed by a string of zeroes, and then a very long list of something IDA doesn’t seem to have recognized and labeled “? ;”.

Question 19: If you have the IDA Python plug-in installed (included with the commercial version of IDA Pro), run Lab05-01.py, an IDA Pro Python script provided with the malware for this book. (Make sure the cursor is at 0x1001D988.) What happens after you run the script?

I don’t have the Pro version and a few quick Google searches says the free version doesn’t support IDA Python, so we’ll skip this question.

Question 20: With the cursor in the same location, how do you turn this data into a single ASCII string?

Pressing “A” tells IDA to combine as many ASCII characters as it can until the next empty space character.

Question 21: Open the script with a text editor. How does it work?

The script Lab05-01.py uses the “ScreenEA” function to get the current position of the cursor in IDA. It then iterates through the next 0x50 bytes and uses an XOR to compare each byte to 0x55, then uses PatchByte to merge them all together on one line.

Practical Malware Analysis – Chapter 3: Basic Dynamic Analysis

It’s starting to get into the good stuff with this chapter. I’m mostly going to be writing about the labs as that’s the interesting part for me and let’s me test everything out. Fair warning though, these will likely be a little long as I’m trying to practice documenting everything that seems relevant.

Lab 3-1 (Lab03-01.exe)

Question 1: What are the malware’s imports and strings?

The only DLL this file seems to import is KERNEL32.DLL along with the “ExitProcess” function. Not much we’re able to get from that.

Question 2 and 3: What are the malware’s host-based indicators? Are there any network-based signatures for this malware? If so, what are they?

When running Strings on the file it has several interesting entries for URLs, file names, and registry entries that are confirmed when it is run and the .data section in PEView gives a general idea of the flow. So let’s run it and see what happens.

1 – Network-Based – The program reaches out to “www.practicalmalwareanalysis.com” every minute, likely to receive commands for further instructions from the C&C (Command and Control) server. I setup a netcat listener on port 443 (https) to see if I can catch the HTTP request it sends out, which worked, but it seems to be random and changes each time.

2 – Host-based – Creates a new file called “wmx32to64.exe” in the C:\WINDOWS\system32 folder and adds it to the registry under HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run as the key “VideoDriver”. This seems to be for persistence so it will continue to send a beacon to the C&C server if the computer is restarted.

3 – Host-based – The program also creates a mutex called “WinVMX32” that is replicated by the “vmx32to64.exe” program mentioned above if the computer is restarted.

Lab 3-2 (Lab03-02.dll)

Question 1: How can you get this malware to install itself?

When looking at the file in PEView or Dependency Walker it shows several useful functions being exported, “Install”, “Uninstall”, and “MainService” being the most important. These indicate the DLL is meant to install a new service and what function needs to be called to do so. Running the command “rundll32.exe Lab03-02.dll, Install MainService” in the command line from the directory with the lab files will install the service. When comparing Regshot entries, we can see the DLL installed a service named “IPRIP” along with several other keys for a fake service called “Intranet Network Awareness (INA+)”.

Question 2: How would you get this malware to run after installation?

Per Regshot above, it installs a service called “IPRIP”, so the command to start it would be “net start IPRIP”. After running this command, we get a confirmation message that the service has been started successfully.

Question 3: How can you find the process under which this malware is running?

By running “tasklist /svc” to show active services. This tells us which instance of svchost.exe is running the IPRIP service and we can track that PID now if needed (1052 in the screenshot below).

Question 4: Which filters could you set in order to use Procmon to glean information?

We can set a filter for PID 1052, per the screenshot above, but this would also show events for the other services running under this instance of svchost.exe and gives a significant amount of noise to sort through.

Question 5 and 6: What are the malware’s host-based indicators or network-based signatures (if any)?

Host-based – The host-based indicators would be the new registry keys added for the IPRIP service and the screenshot from Regshot above could be used as a reference for what it creates.

Network-based – Once the service is created and running, it reaches out to http://www.practicalmalwareanalysis.com. I setup another netcat listener, this time on port 80 (http), and it caught a valid HTTP GET request for “serve.html”.

Lab 3-3 (Lab03-03.exe)

Question 1: What do you notice when monitoring this malware with Process Explorer?

When run, the Lab03-03.exe process shows up briefly with a child process of svchost.exe. After a few seconds, the Lab03-03.exe process disappears, but svchost.exe is still there, but not actually running any services. When viewing the properties of svchost, it still lists the lab file as it’s parent and gives the parent’s PID.

Question 2: Can you identify any live memory modifications?

When filtering Procmon to the PID of the parent process, it doesn’t give any results. However, when filtering to the PID of the active svchost.exe process the program created it gives multiple results for opening and writing to a file called “practicalmalwareanalysis.log” in the same folder as Lab03-03.exe. After opening that file, it seems to be logging the keystrokes on my computer.

Question 3: What are the malware’s host-based indicators?

The most obvious host-based indicator would be the log file it creates above – “practicalmalwareanalysis.log”.

Question 4: What is the purpose of this program?

It’s a keylogger that logs the keystrokes on the computer and the window they occur in.

Lab 3-4 (Lab03-04.exe)

Question 1: What happens when you run the file?

It runs for a second or so, flashes a command window up, and then closes. When looking through Procmon for anything that references cmd.exe (based on the cmd window popping up briefly), we find the entries for when it is creating the process, but the command line arguments seem to be for deleting the binary file instead of doing anything exciting.

Question 2: What is causing the roadblock in dynamic analysis?

The program doesn’t look like it actually does anything malicious. It seems to detect that something isn’t working correctly so it doesn’t continue execution and tries to delete itself. My guess would be that the malware might be detecting that I’m running it in a virtual machine as opposed to a physical computer, but we’ll find out later as the book says we’re going to analyze this one again in chapter 9.

Question 3: Are there other ways to run this program?

I tried running it from the command line, but get the same results as what happens in question 1.

Practical Malware Analysis – The Setup

Over Christmas last year I bought the book bundle Humble Bundle happened to be offering at the time – “Hacking for the Holidays”. It came with 16 books published by No Starch Press on a variety of cyber security topics, but mostly focused on penetration testing. Over the first few months of the year I worked my way through “Penetration Testing: A Hands-on Introduction to Hacking” by Georgia Weidman, which is excellent and I wish I had written about it as I did so, but that’s not why we’re here today.

One of the other books in the bundle was “Practical Malware Analysis: The Hands-On Guide to Dissecting Malicious Software” by Michael Sikorski and Andrew Honig. Considering I’ll be doing at least a little of this in the new job I’ll be starting soon, this seemed like a good next step and most of the reviews I found on the internet say it’s still incredibly useful in 2019 (it was published in 2011). I’m only on chapter 3 at the moment, so I don’t think you’ve missed out on much with the first 2 chapters, but I’ll give a brief summary of what it covered and what I’ve learned so far.

For anyone interested, here’s a link to the book. I personally bought a physical copy of it in addition to what came with the Humble Bundle as I’m not a huge fan of eBooks.
https://www.amazon.com/Practical-Malware-Analysis-Hands-Dissecting/dp/1593272901/

Chapter 0/1

Disclaimer: Seeing as how I’m mostly explaining things here to help with my own retention, my terminology or explanations definitely won’t be 100% correct all the time and I’m OK with that because I’m still learning.

The book starts out with a basic explanation of what malware analysis entails and moves right into basic static analysis techniques in chapter 1. Static analysis focuses on any information that can be gathered from the source code of the program, the functions it calls in the OS, or anything else that can be found without actually running the file. It covers the VirusTotal website, which I only found out about a few months ago, but now use all the time and then moves into specific tools. Below are the useful tools it covers and a brief synopsis of what they’re used for.

  • Strings
    • This program scans the source code of the program for anything that seems to be a sequence of characters. These could be used for anything from printing a message to the user to connecting to a specific IP address or URL.
  • PEiD
    • Since it is common for malware writers to pack or compress their code to make it more difficult to be analyzed, this tool scans the file and easily shows whether a file is packed and, if so, what tool was most likely used to do so.
  • Dependency Walker
    • This tool lists any DLLs that are called by the given program and shows what functions those DLLs import, which can give an idea of what the program might do when run.
  • PEView
    • This is my favorite tool so far. In a way it shows some of the same information as Dependency Walker, but it also displays plenty of other useful info. Some of the information I’ve found it useful for so far: timestamp of when the program was compiled, clues on whether the program was packed based on the space it takes in memory, a cleaner view at the imported DLLs and functions, and the actual text used through the program (where Strings gets it’s results from).
  • Resource Hacker
    • This tool seems useful for poking through what icons, menu items, and other resources a program uses. I haven’t actually used this much and the author says it will be used more heavily later in the book.

Before we go much further, I should probably mention what environment I’m using to run everything on. I setup two VMs for now, one with Windows XP and another with Windows 7, as that is what the book recommended, but I’ve done everything in XP so far haven’t had any issues.

The chapter finishes up with several labs that let you use the tools covered to examine some example programs provided by the author, and this is always my favorite part as I’m much more of a hands-on learner. The labs were pretty basic, which makes sense for chapter 1, but still useful and let me poke through the tools to get used to them.

Chapter 2 covered how Virtual Machines are useful for malware analysis and how to set them up, but I won’t go over any of that since anyone reading this has more than likely setup plenty of those already and there are more interesting things to move on to.