Saturday, October 23, 2021

Shhh we're still hunting Phishers Part 2

Welcome back Phish hunters.

So the first part of the blog series (is two a series?) we looked at different encoding schemes Phishers use in crafting their phishing emails to avoid detection. 

We looked at the two 'easy' ones URL encoding and Base64. After a while you can detect these by sight in pages of logs or code pretty easily.

This next one is a little more complicated. 

But lets start with knowing that html code has to play by the rules of what the browser can interpret, so we can use that to help with our decode.

From our first URL encoding we see the javascript function unescape :




 In the BASE64 we see clear references of the base64 keyword:




Now what can we determine if the html coded looks like this!



We can see that the JavaScript has clearly been obfuscated to avoid human readability and also mail scanners.

We see in the first few lines that there is a function function(p,a,c,k,e,r) . We see this and other weird techniques that do character replacement/substition etc anything to make it hard to read.

This (p,a,c,k,e,r) function is common routine that can be evaluated using the javascript unpacker website kindly provided here https://matthewfl.com/unPacker.html .


This converts to an document.write(atob function and we are back to base64 encoding again. encoding1(encoding2(data)) 

Check out the atob function here https://html.spec.whatwg.org/multipage/webappapis.html#atob

The based64 decoded unpacked javascript contains three of these atob functions. So we can take each content string within the atob function and back to CyberChef to see what it contains .. exciting. 



Ok so this appears to be adding EventListeners to disable certain keys including:

 // disable F12 key
 if(e.keyCode == 123) {

 // disable I key
  if(e.ctrlKey && e.shiftKey && e.keyCode == 73){

// disable J key
 if(e.ctrlKey && e.shiftKey && e.keyCode == 74) {

 // Prevent Ctrl+s = disable save
 if (event.ctrlKey && (event.keyCode === 85 || event.keyCode === 83 || event.keyCode ===65 )) {

// disable U key
(e.ctrlKey && e.keyCode == 85) {

F12: Disables a set of tools that you can use to design, debug, or view webpage source code and behavior
Ctrl Shift I: Disables opening the Developer Tools panel
Ctrl+J: Disables opening the console tab in the Developer Tools panel
Ctrl+s : Disables saving the page
Ctrl + U: Disables opening the browser source code page


So basically the Phisher doesn't want us to look behind the curtain Dorothy!!

If we add the 3rd atob base64 encoded string into CyberChef it decodes nicely to readable html

Interesting in this case the Phisher had hacked a legitimate WordPress site and saved some icons, images and css style sheets. 

I find 9/10 of the hacked sites used in Phishing campaigns are running WordPress. So please ensure you your WordPress sites are up to date with their plugins and patching. 

It is also good to send the website owner/host an email to let them know their website is compromised.

One hacked WP site we found was being used to store a PHP script and a nice text file of hundreds of username and passwords that had been captured. We called the business, sent emails and still months later the page was still up! 

I may have flooded it with hundreds of illegitimate username/passwords credentials to attempt to frustrate the Phishers and slow them down.



The stored images appear on the webpage looks familiar. Also, the victim's email was already prefilled. 

So seems legit!





Later in the page we find some more base64 so now we are at the third level of encoding inception. encoding1(encoding2(encoding3(data).





Decoding that block we find it decodes to be a GIF (does ask me to pronounce it, it will certainly divide my six viewers). GIFs are usually not that interesting and contain animated arrows, progress bars etc to trick the victim to thing something is happening. 




The next section of the html code contains a function to capture and POST your credentials.

They code typically contain a email address validity checker via regex.
The code also typically contain a hard coded error when you enter your password the first time. 

These are both to check if you are just trying rubbish looking credentials to confirm if this website if legitimate.

Once you add your second password they then usually take you to.
1. Microsoft login page www.office.com ,or
2. An error page, or
3. Something specific to original email but not valid. 

In this case, the original Phishing email contained an alert that the victim had an important voicemail waiting for them, Once the went down the rabbit hole it took you to a website that contained an mp3 of voice mail!!   The victim was left confused by voicemail that had nothing to do with them, so thought it  must have been a wrong number.

But within minutes the account was logged into using the stolen credentials and the phishing email had been hard-deleted by the Phisher and then account mayhem!




Now we need to get back to reality from the these layers of encoding. 

Hopefully this has given you an idea of the lengths Phishers will go to to obfuscate their intentions so they can slip into your mail without detection.

Until next time, the hexninja says:

Down the rabbit hole

Phishers encoding data

How low can you go

 



Friday, October 22, 2021

Shhh we're hunting Phishers... %50%68%69%73%68%69%6E%67 or UGhpc2hpbmc=

So the HexNinja has been spending a lot of time going Phishing. Well more correctly examining phishing emails and watching them evolve and do their best to avoid SPAM detection while also gaining your confidence.

One of the questions I get asked is how the Phishing email got into our mail system without being flagged as malicious.

 


Besides obvious issues of SPF DKIM DMARC or lack thereof I am finding many phishing emails containing htm attachments. 

They always have a great title like Remittance #763.htm or Invoice #692.htm and if your job is to process payments and balance the books and the email has come from a known contact that is a customer or supplier then the motivation to open a htm attachment is high.

Examining the contents of many htm files they don't look like human readable htm formats. To obfuscate their contents they will rely on a one or a combination of encoding to hide their true intentions and also so fool your email protection systems.

So armed with CyberChef  https://gchq.github.io/CyberChef/ we can begin experimenting with how the files are encoded.

The four main techniques I am seeing are:

  • URL encoding
  • Base64
  • Hexidecimal encoding
  • Javascript packing
In this first post I will look at URL and BASE64 encoding.
In this second post I will look at Hexidecimal and Javascript packing.

The more difficult decodes involve a combination of these but lets walk before we run.

URL ENCODING


So if we open the htm file in a text editor and we see something like this



We can see that the quoted block has been url encoded and wrapped in a javascript decode function 'unescape'. 

URL encoding is a way that website url and wepages can encoded special characters such as spaces %20 or other special characters. Normally a url string only encoded these special characters in but it can also be used to encode a whole string. 
Basically it converts the string to bytes, encoded each byte to hex and separates each byte with a %.

Eg www.thehexninja.com would be 

  %77%77%77%2e%74%68%65%68%65%78%6e%69%6e%6a%61%2e%63%6f%6d

Try pasting that string into your browser and it automatically resolves to www.thehexninja.com.

We can get Cyberchef to do the heavy lifting of url decoding. We can copy all the encoded block within the quotes and paste it into Cyberchef using the URL Decode function as shown below.




This would obviously render to a simple embedded link as shown below

So we can see how this simple technique can be used to evade basic mail scanners, especially if the embedded link is not malicious such as a OneDrive, DropBox, SharePoint or a page on a another website.

Base64 Encoding

Sometimes the htm attachment contains base64 encoded sections, typically images prefixed with the type of image images/png or images/jpg




We can copy these encoded sections and paste into cyberchef (From Base 64)


We can now paste the Hex output into a hexeditor and save it as a JPG (image/jpeg) or PNG  (image/png). 

The first PNG image decodes to



The second image is a JPG and renders as:


The 3rd image decodes to:


The forth image decodes to 



When these images are overlayed they appear as



This is the classic spoofed Microsoft Office 365. 

Hiding beneath the enticing image/webpage is the the code which basically accepts a post of the password and username in a POST to a google form, essentially capturing the victims credentials 


 

Until next time, the hexninja says:

Stop Sneaky Phishers!

Encoding to Hide Data

Never Trust The Phish



Sunday, April 18, 2021

Getting hashes to Virus Total from an Isolated Virtual Machine




Sometimes when I am testing in a Virtual Machine (VM) I really lock down the isolation. 

No shared folders. 

No bidirectional clipboards. 

No network. 

I may be paranoid but it is 'mildly discomforting' to see malware (ransomware) under test, encrypt your shared folder and then your host AV or Bitdefender start to lose it with Virus detections. 

This usually doesn't happen but when it does you can have a cold sweat moment that somehow the malware has not only jumped to a shared folder and doing what it does best. It is normally just a detection of the encrypted file or ransom note but once I have transferred the files for testing it is a good idea to check and double check your isolation. 

At a first pass when looking for suspected malware dll or exe files I like to upload the hash or suspicious files to Virus Total or Hybrid Analysis

https://www.virustotal.com/gui/home/search

OR

https://www.hybrid-analysis.com/





However with an isolated system I am also limited by how to check the hash. I can't copy it across from the VM guest to host or check directly in a browser as I have isolated my VM. 

During this last year of Covid-19 I have used more QR codes than I have ever have so I had a thought to create a script that calculates the hash and generates a QR code that embeds the hash in the url so it will redirect to a prefilled Virus Total or Hybrid Analysis. 

I can then get the script to show the QR code on the screen and I can capture it in the host or even use a mobile phone to capture the QR to a browser .

Normally, I code in Python but thought I would punish myself and see if I could do it in Python3 and C#.

Python 3 

The python code uses a QR code generating library pyqrcode  and the hashlib library.

These can be installed using pip  

https://pypi.org/project/PyQRCode/
https://pypi.org/project/hashlib/

>pip install PyQRCode
>pip install hashlib

The general functional flow is 
1. Get filename from argument
2. Calculate SHA256 hash
3. Append SHA256 hash to url string ie 'https://www.virustotal.com/gui/file/'+ sha256_hash
4. Generate and display the QR code of this url

The python script is called from the command line using the suspicious file as an argument  to call the function with the suspect file 
> python3 qrcode_gen.py c:\abc.exe


import pyqrcode
import argparse
import hashlib
import os

BUF_SIZE = 1048576 

def calc_hashes(filename):
    md5 = hashlib.md5()
    sha256 = hashlib.sha256()    
    with open(filename, 'rb') as fp:
        while True:
            data = fp.read(BUF_SIZE)
            if not data:
                break
    return md5.hexdigest().upper(),sha256.hexdigest().upper()

# input file to create sha256 hash
parser = argparse.ArgumentParser()
parser.add_argument('filename')
args = parser.parse_args()
md5_hash,sha265_hash=calc_hashes(args.filename)
vt_url='https://www.virustotal.com/gui/file/'+ sha265_hash
print(vt_url)
    
qr = pyqrcode.create(vt_url)
qr.show()

This QR code image will pop up in the image viewer and we can capture it with a phone camera app or QR code scanner.
 

The linked URL will then open up and we can see this was a Wannacry malware. 







C#

The C# program uses two libraries, System.Security.Cryptography to calculate the hashes and ZXing to create the QR code.

Unlike the Python version this C# requires a location to store the image that we parse to the command line program. A memory only version is underway but it is a little more complicated.

>qr_hash.exe C:\tmp\123.txt C:\tmp\123.jpg

The workflow is much the same as the python version except that it saves the QR image as a JPG then it uses a shell process to open the image in the default image viewer.


using System;
using System.Security.Cryptography;
using System.IO;
using ZXing;
using System.Drawing;
using System.Diagnostics;

namespace QR_Hash
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length == 2)
            {
                string filenpath = args[0];
                string imagepath = args[1];
                string hash_string;

                if (File.Exists(filenpath) == true)
                {
                    using (var sha256 = SHA256.Create())
                      
                    {
                        using (var stream = File.OpenRead(filenpath))
                        {
                            var hash = sha256.ComputeHash(stream);
                            hash_string = BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
                        }
                    }
                    var QCwriter = new BarcodeWriter();
                    QCwriter.Format = BarcodeFormat.QR_CODE;
                    QCwriter.Options = new ZXing.Common.EncodingOptions
                    {
                        Width = 400,
                        Height = 400
                    };
                    string vt_url = "https://www.virustotal.com/gui/file/" + hash_string;
                    var result = QCwriter.Write(vt_url);
                    using (var g = Graphics.FromImage(result))
                    using (var font = new Font(FontFamily.GenericMonospace, 8))
                    using (var brush = new SolidBrush(Color.Black))
                    using (var format = new StringFormat() { Alignment = StringAlignment.Center })
                    {
                        int margin = 5, textHeight = 30;
                        var rect = new RectangleF(margin, result.Height - textHeight,
                                                  result.Width - 2 * margin, textHeight);
                        g.DrawString(vt_url, font, brush, rect, format);
                    }
                    result.Save(imagepath);
                    var p = new Process();
                    p.StartInfo = new ProcessStartInfo(@imagepath)
                    {
                        UseShellExecute = true
                    };
                    p.Start();
                    
                }
            }
         }
    }
}

This C# version also add a nice URL link to the bottom of the image 





So there you have it, 2 basic programs to help you get the hash out of a VM via the screen. Noice!

As the hex ninja says.

Finding malware now,
Is easy with QR codes,
Keep safe from malware 


Saturday, October 10, 2020

Capturing Windows Memory

It has been a while since my last post. Changing jobs pointed me in a different direction for a while but as George and Frank Constanza would say. "I'm back baby!"


I recently had to look into windows memory capture to do some offline analysis of running processes.

My normal 'goto' tool for taking a forensic image and memory capture is usually FTK Imager. It is pretty robust and ninja proof. 

You can copy the install directory to an external USB and it will run nicely as a portable version. When we run this it obviously loads into memory which be present when we capture the system memory.

I started to think of if there were any other tools that could do memory analysis and compare some of there features such as 

  1. Memory Footprint - smaller and less processes is better
  2. Portable - I don't really want to install it on the system in question
  3. Fast - Memory capture is often the first stage of a Incident Response so I it to be fast
  4. Access privilege required - do I need to be admin or can I run this a least privilege user.
  5. Stand alone - Do I need to buy the whole forensic suite or can I just get the memory capture tool
  6. Price - gratis is good but a low cost good tool is OK too.
  7. Easy of use - I don't want to fumble in the field with pesky undocumented command line switches.

While there has been numerous blogs on some of the available tools I was mainly interested on the footprint and speed. If the tool was loaded into memory the risk is that some of the data of interest may be popped out.

After some quick browsing it seems the current options are (in no order of preference):

  1. FTK Imager
  2. Belkasoft
  3. Magnet RAM
  4. Process Hacker
  5. Winen
  6. MDD
  7. Mandiant Memoryze
  8. WindowsSCOPE
  9. WinPmem
  10. Dumpit
The next step was to see if my google fu was able to find the memory capture applications as some of these have dropped on and off  hosting sites. 

FTK Imager

Used for forensic imaging and live viewing of disks but can also do memory capture.
Has the option to capture pagefile.sys at same time which is nice.
It does require you to install it first (not on your target machine) then copy the install directory to a USB for portable use.  

Time: 2m:37s
Memory: 11.6MB
Install Directory of FTK Imager

FTK Imager GUI

FTK Imager GUI options

FTK Imager Memory Footprint


Belkasoft - RAM-CAPTURER

Simple to use from a USB.
Time: 2m:22s
Memory: 7.7MB.

Belkasoft RAM Capturer Install directory



Belkasoft RAM Capturer GUI

Belkasoft RAM Capturer Memory Footprint

Magnet - RAM

Has the option to segment but otherwise pretty straightforward.
Time: 4m:01s
Memory: 6.8MB


Magnet RAM Install Directory

Magnet RAM GUI

Magnet RAM Memory Footprint

Process Hacker

While this is a powerful tool it is more granular than required and probably better for live analysis as it allows you to inspect individual processes and dump the memory used by them but not a total memory dump.

Process Hacker Install directory

Process Hacker GUI

Process Hacker Memory Footprint


MDD

I couldn't get this to work successfully. 😢


 

Mandiant Memoryze

This downloads as an msi for installing but it can be run from an USB without installing by using a command line option to install it onto a USB.

msiexec /a E:\Download\\MemoryzeSetup3.0.msi /qb TARGETDIR=E:\Memory_Acquisition\Mandiant_memoryze

It doesn't appear to have support after Win 7 so the testing of this one on hold.

WindowsSCOPE

This requires a $1 to try it registration but looking and the 1 year cost of  $7,699 for a single year decided not to pursue this. 

DumpIt

This app disappeared for a while and I was very keen to test it. A new version came back via the author Matt Suiche at https://my.comae.com but even though I created an account I could never login ?? and got a Failed to Fetch error when logging in. If anyone has tested a newer version let me know.


It does a capture in place so if you run it from an external USB make sure it is big enough for the capture as it doesn't allow you to select a destination location. 

Time: 2m:34s
Memory: 7.1MB
DumpIt Install Directory


DumpItcommand line

DumpIt Memory Footprint


Testing Summary

So the major features I was looking for were a small footprint, easy to use and speed. The table below shows a summary of the four tools that met our needs.




For speed, Belkasoft is slightly faster on my DELL laptop but it will depend on the system you are running it on. 

Magnet RAM has the smallest footprint at 6.8MB.

FTK Imager is also fast, with slightly larger footprint but it has more than just RAM capture functionality. It can also forensically acquire hard drives so if I wanted to also do a forensic disk image or forensically copy files it maybe easier to use this than changing programs. 

But, if I had to just do a memory capture Belkasoft or Magnet RAM might be a good choices.  
 
DumpIt may be a nice choice if I just wanted a simple double click and it stores it in the same directory. 


Now to analyse the memory captures.... that may be for another post.

Until the next post TheHexNinja says:

Memory Capture 
Easy When You Know Your Tools  
Now To Analyse 


References

1. Tool URLs
2. The following article describe some of the methods the memory applications use to obtain the dump in kernel mode: ZwOpenSection with ZwMapViewOfSection, MmMapIoSpace
and MmMapMemoryDumpMdl








Wednesday, January 31, 2018

Practical Exercise - Image Carving II - Python



In the last post we looked at how we can manually carve out a jpeg image from free 'space'. Good to know and OK to do if we have one or two but if we had thousands to carve...... it could take some time. We would then use some sort of Image Recovery Software but could we write our own??

Part of the reason for this blog was to demonstrate some Hex Ninja skills both manually and how we can write some simple scripts to automate some of these tasks.

The general process goes something like this:
1. First we find the artifact we are looking for.
2. Understand the layout of the artifact.
3. Manually try and carve out the artificat and make sure it works for all cases.
4. Write a script to automate the process.
5. Test the script and make sure it works.

The last blog post covered steps 1-3, this post will cover steps 4-5.

So the language we will be using is Python. It is very easy to program in and is my 'goto' language at the moment for getting something up and running fast.

Available from https://www.python.org/downloads/ 

There are two versions available 2.7 and 3.6. See https://wiki.python.org/moin/Python2orPython3 to check out the differences between them.

I mainly use 2.7 because of there are more code libraries and more support for debugging on sites like StackOverflow but we can test it on both and see if it works. Eventually I will move to Python3.

So download Python 2.7 for your OS (Mac/Windows/Linux) and follow the install instructions.


To make sure everything has intalled OK, go to a command prompt and type python.


Hopefully you see something similar to the above screenshot. The output should tell you what version you are using (2.7.12) if it is 32 or 64 bitand a Python command prompt >>>

In the tradition of your programming languages your first exercise is to print Hello World to the screen.
Python makes this very simple, type print ("Hello World") and you should see output like below.



To get back to the normal commad prompt hit hit Ctrl-Z and Enter.

There are two main ways of using python.
1. From the Python command prompt where we can type python commands direct. This is good for doing simple testing of instructions.
2. Running a python script, where we write the python commands in an editor, save it with the extension py and then we can execute it by typing at the command prompt python yourscripty.py

We will be mainly use the second technique. We can use a a basic text editor such a notepad. My favourite editor is PyCharm from JetBrains https://www.jetbrains.com/pycharm/
It has code hightlighting, code completetion, finds error and you can run your code from within the editor, but there are a plethora of editors. They can be a bit daunting to initially use but well worth it if you intend to code a lot. For simlicity we will just use a text editor.

So now we are ready to start coding.
But before we start coding let's think about what we want to achive.
1. We want to load a file.
2. We want to search the file for the JPEG start of frame header "FFD8FFE0" and the end of frame 'FFD9"
3. We then want to save the data between these markers to a file. Simples!

As we want to keep the code simple, we won't be doing any error checking. In a real production program, there is a lot of error checking making sure the file exists, the data is in the correct format etc etc and it can make looking at the code confusing, so we will just be doing the bare basics.

The first thing we add to our script is to tell python what modules we will be using. We will be using the module re . We will be using re (Regular Expressions) to do fast searches so we need to tell Python the load in that module using the import insstruction

We then hardcode in the Start/End of Frame tags we will be searching for. FFD8FFE0 and FFD9. The format of them may look a little strange but basically it is in a hex byte string format. ie each hex byte is preceed with \x. The reason we do this is because the the file we read in will be in that format so it is easier to search for these tags in this format.

import re

JPEG_SOF = b'\xFF\xD8\xFF\xE0'JPEG_EOF = b'\xFF\xD9
JPEG_EOF = b'\xFF\xD9' 

Next we want to read in our file we want to search through. We could pass in the filename as an argument but as we are trying to be simple we will hardcode the filename it into our code. We use the open command with the name of the file we are carving from. We will use the date file Carve1.bin from the previus blog.  https://github.com/thehexninja/BlogDownloads/blob/master/Carve1.bin

We use the 'rb' format indicating we want to read 'r' a binary 'b' file. The open command returns a reference to out file call a file object we call file_obj. Next we read the whole file into a variable call data. Don't try this with a massive file. We will show in later posts files how to read in big files. We then want to close the file which releases the reference to it so other programs can access it. Also make sure the file Carve1.bin i is in the same directory as the python script, otherwise we have to add path information to the filename.

file_obj=open('Carve1.bin','rb')
data=file_obj.read()
file_obj.close()

This seems all pretty straightforward.

No we have our data loaded in memory we can perform our search. This is where we use the re module. Basically we want to get a list of all the offsets in the data where we find our tags. The following commands returns a list of these offsets.

SOF_list=[match.start() for match in re.finditer(re.escape(JPEG_SOF),data)]
EOF_list=[match.start() for match in re.finditer(re.escape(JPEG_EOF),data)]

If we run the script so far we can check what we have found.


>>> SOF_list
[4696]
>>> EOF_list
[11747]

So we have found the SOF tag at byte offset 4696 and the EOF tag at 11747.

Now all that is left for us to do is to get the data between these offset and save it to a file. We will write the code assuming their could be more hits so we can loop through all the we can carve all the images in one go.

So we need a counter variable we will call i we use to go through the lists. We then use a for loop to go through the SOF_list. We then want to get the jpeg image data from the hex byte string we read in from the file. We can do it simply by subdata=data[start:end]. So now we have the data we just need to save it to a file. As before I like to name the file and include the start offset and end offset in the name of the file. We do this with 
carve_filename="Carve1_"+str(SOF)+"_"+str(EOF_list[i])+".jpg"

Now we just open that file with the 'wb' - write binary format. We update i with i=i+1 to then refernce the next EOF_list offset. And we do a print statement to give some feedback to the user.

i=0for SOF in SOF_list:
    subdata=data[SOF:EOF_list[i]+2]
    carve_filename="Carve1_"+str(SOF)+"_"+str(EOF_list[i])+".jpg" 
    carve_obj=open(carve_filename,'wb')
    carve_obj.write(subdata)
    carve_obj.close()
    i=i+1    print ("Found an image and carving it to "+carve_filename)

 So that should do it. We can now save this file call it jpeg_carve.py and run it.


 Great it works .. so lets check the carved file.


And we are done. A 17 line image carver!