Tuesday, December 23, 2014

Malware Reversing Part I: Introduction & njRAT


Recently, I have taken upon learning malware reversing and how to properly analyze malware in the wild. I find nothing more interesting than taking things apart and seeing how they work. I am also fascinated my the sophistication of modern-day malware. In order to pursue my goal of becoming a malware reverse engineer, I have began manually reversing live samples of malware found in the wild.

Getting Started

To begin, I first had to obtain a method for getting samples of wild-malware. I contacted the nice guys at VirusTotal and outlined my research goals to them. In a short amount of time the gave me an API key with nearly unlimtted access to their Intelligence service. For those of you who are unaware, this is a service that allows one access to fresh samples submitted to VirusTotal.com. This service even allows one to filter samples based on YARA rules. I spent a fair amount of time playing with YARA rules to generate a few rule sets that fit my needs. With my YARA rulesets created and actively filtering live samples coming into VirusTotal, it was time to play the waiting game and begin my hunt for malware.

It Didn't Take Long...

Almost immediately after enabling the YARA rules I was being bombarded with live samples of malware showing up in my notifications. I am not going to lie, I got pretty excited and my adrenaline was going. These weren't old samples that have been hacked apart by universities and research teams; these were wild samples of malware with live C2 servers. I couldn't wait to get started, so I fired up my sandbox environment that would soon become my second home and got to work...

My Malware Sandbox

I should make a brief note of what my malware sandbox consists of. My sandbox is extremley limited and basic as I set it up it a short time, but it gets the job done. What I did was simply create a VM, load windows 7 home premium onto it, loaded some tools that I would think useful for malware analysis, and snapshot it. 

Some tools I started with:
Ollydbg w/ various plugins
Resource Hacker
FastScanner V3.0 Final
Delphi Disassembler (DeDe)
Process Explorer
*after learning to manually unpack PE's using ollydbg, I obtained some common unpackers to speed up the process

*note, I am fully aware that modern malware analysis is almost entirely automated. However, I refrained from setting up an automated sandbox such as Cuckoo for the sole purpose of learning. For me, hands-on is the best way to learn and automating the process surly would not help my goal.

njRAT Reversal

njRAT is a variant of a common class of trojans know as Remote Administration Tools (RATs). The goal of this reversal is to demonstrate and practice my ability to reversal a live sample of wild malware, identify its command and control server (C2), and to write a SNORT rule for the sample's callback (or phone home), in order to detect the presence of this sample on a network.

Obtaining the sample

To obtain this particular sample, I used the following YARA rule written by Kevin Breen:

rule njRat : RAT
author = " Kevin Breen <kevin@techanarchy.net>"
date = "2014/04"
ref = "http://malwareconfig.com/stats/njRat"
maltype = "Remote Access Trojan"
filetype = "exe"

$s1 = {7C 00 27 00 7C 00 27 00 7C} // |'|'|
$s2 = "netsh firewall add allowedprogram" wide
$s3 = "Software\\Microsoft\\Windows\\CurrentVersion\\Run" wide
$s4 = "yyyy-MM-dd" wide

$v1 = "cmd.exe /k ping 0 & del" wide
$v2 = "cmd.exe /c ping & del" wide
$v3 = "cmd.exe /c ping 0 -n 2 & del" wide

all of ($s*) and any of ($v*)

VirusTotal's Intelligence service did the rest, supplying me with live samples that match the above YARA rule.

This particular sample is identified by its SHA-256  Hash of "baead7962c62083ecb2d77dcbdc65ba348addd128f03825e1b9d9e1cd3a047a6"

Identifying the Packing Used

I always start by checking which packing is used on the portable executable. This determines which direction I am going to go in when beginning the reversal. I used PEiD v0.95 and cross reference it with Fast Scanner v3.0 Final to determine what I am working with. I chose this piece of malware as my first reversal based on the fact that it was written in C#, a .NET language.

Below are screenshots of this process:

A Closer Look...

My next step was to take a closer look at the sample in question. Since this sample was written in C#, I can use any common .NET reflector tool to convert the assembly code to readable functions. For this I generally use ILSpy.

I begin my doing a quick skim through of the entire code, trying to get a feel for the malware's behavior and keeping an eye out for keywords in variables and function names such as HOST, CONNECT, PORT, KEY, PASSWORD, NICK, MSG, as well as strings or integers that fit the format for an IP address or port number. The purpose of this is to catch any valuable information such as a unique callback method and the address of the command and control server.

In this particular sample I lucked out and found the following variables:

public static string H = "";
public static string P = "1234";

Below is a screenshot of the code in ILSpy:

Now I have a suspect IP for the command and control server, as well as a port number. Knowing what destination and source address to keep an eye out for, I popped open Wireshark to begin some network analysis of this sample in action.

Fire In The Hole!

This is one of my favorite parts of my process, getting to knowingly execute a live sample of malware. There's just something about double clicking that executable that gets my blood flowing. It's like knowingly pressing the switch on a detonator: despite it being a controlled environment your are still getting to blow something up, and that's pretty cool, right?

When I run a sample I like to have process explorer open, "netstat -naob" ready to run in an elevated CMD window, and Wireshark listening. This let's me see any immediate changes in my system upon execution of the sample. Process Explorer will alert me to any new processes being spawned, as well as give me a ton of information on each one. *Later I use Process Explorer to do a live memory dump of a sample to further analyze it* "Netstat -naob" will tell me what processes are activley listening out to the internet on my system. I have found that this often will be a dead giveaway to the callback behavior of a sample. Finally, Wireshark which allows me carefully inspect each packet going across my interface. 

Wireshark allows me to see the process in which a sample interacts with its C2 as well as any data it is sending or receiving. This is crucial in developing a unique signature to identify this malware's activity by. I can use this information to write a custom SNORT rule to detect activity of this malware on a network.

Below is a screenshot of this sample's TCP packet stream in Wireshark, as well as a screenshot of the data stream it is sending to the C2:

Identifying The CallBack

In order to create a useful signature of this sample that can be later turned into a SNORT rule, I must identify the callback method used by the malware.

Analysing the ILSpy dump, I find a function that catch my eye:

Which when further inspected, reveals a TCP connection being made to the previously discovered host and port, as well as sending the data from the function "OK.inf()":

Clearly, we should check out "OK.inf()", here is a snipped of the function:

Essentially what this function is doing is gathering some data on our system and calling other functions to compress and obfuscate it using base64 encoding. We could further dissect this to determine exactly what information from our system is being grabbed, however for our purpose of finding a unique network signature, we will skip this step.

 OK.Connect() takes the information gathered of OK.inf() and sends it to the C2. This is the first time an outbound connection is being made, and is our initial callback of this sample. Analyzing the first packet sent by this sample confirms this theory and can be seen below:

Crafting The SNORT RULE

With all of the information we have obtained above, we can now craft a snort rule for this piece of malware's callback to its C2. As shown in the above packet, as well as in the code of the sample, the inital callback begins with:
lv |'|'|

This is shown in the code via the next two screenshots:

Knowing that this string is hard-coded into this malware, we can write a SNORT rule that parses network packets for this string, and alerts when it it is found:

alert tcp $HOME_NET any -> $EXTERNAL_NET any (msg:"njRAT C2 Callback"; flow:from_client,established; content:"|00|lv|7C 27 7C 27 7C|"; fast_pattern;reference:url,www.virustotal.com/en/file/baead7962c62083ecb2d77dcbdc65ba348addd128f03825e1b9d9e1cd3a047a6/analysis/; classtype:trojan-activity;)


Command and Control Server:
SNORT Rule For C2 Callback:
alert tcp $HOME_NET any -> $EXTERNAL_NET any (msg:"njRAT C2 Callback"; flow:from_client,established; content:"|00|lv|7C 27 7C 27 7C|"; fast_pattern;reference:url,www.virustotal.com/en/file/baead7962c62083ecb2d77dcbdc65ba348addd128f03825e1b9d9e1cd3a047a6/analysis/; classtype:trojan-activity;)


This is the first part of my Malware Reversing series, which will document my findings of my research on live samples of malware in the wild. I apologize for its length, as later segments will skip right to the analysis of the malware. My goal of this research is to better hone my skills of malware reversal with a hands-on approach, while also being able to contribute to the security community by offering up C2 server addresses and SNORT rules to detect malware activity.

Tuesday, April 8, 2014

Rhetorical Analysis

The following is a rheotrical analysis I did for my Rhetorical II class. Often when students see that they must do a "rhetorical analysis" they tend to freak out and stress. I know all to well about stressing out, therefor I am hoping other people can use this as a guide/example for their own papers.  I follow this general guide for all of my papers in both highschool and college.

My steps for writing a paper are as follows:
1.Identify what the assignment is asking for
2. Develop your topic
3. Develop a good thesis! (This is your entire paper in one sentence. Handling the thesis creates an outline for you to follow) Your thesis should state what your argument is (or what you are explaining), and points that you plan to address. (I always try to go with 3)

Paragraph Structure:
-Point #1
-Point #2
-Point #3
(Points should be mentioned in the same order as your thesis!)

When writing your paper it is not so important to focus on spelling and grammer. Just get your ideas out, this is was proofreading is for. In fact, I don't even do my correct citations until the very end. While writing I simply put places holders in parentheses where a citation will later go.

Now, here is a copy of my Rhetorical Analysis of "The Lives of a Cell", by Lewis Thomas:

*For a copy with the original formatting, not corrupted by Blogger see - [REDACTED]

Hunter Gregal  
Professor Removed For Anonymity
Rhetoric II
March 14, 2014
Just a Bunch of Cells
            Humans have been known to simplify their existence on Earth by assuming they are dominant, stable organisms. According to Darwin’s Theory of Evolution however, humans are simply the result of numerous biological mutations in nature (Than). In Lewis Thomas’s ‘The Lives of a Cell,” the true stability of the human organism is examined in-depth in ways that begin to highlight a prevalent flaw in the “all mighty” human species ideology. Thomas incorporates usage of personification, simile, and metaphor in order to argue the underlying point in “The Lives of a Cell” that he is trying to make: humans have created the false illusion that they are the product of their own accomplishments, and are actually a very fragile and dependent organism at the cellular level.
            Thomas is attempting to make a powerful point to the reader concerning a very complex subject. In order to help fortify his argument and make it easier to understand to the reader, Thomas uses the strategy of personification. His use of personification not only makes the complex system of cellular activity easier to understand, but also helps shape his tone into that of someone the reader can relate to. For example, Thomas explains to the reader that despite common belief, a human is not composed entirely of “human” cells. At one point in time very early in the biological history of the human species, a foreign bacterium merged itself into human cells and has been there ever since (Thomas 550-552).  This new bacteria plays the role of consuming human cell nourishment in return providing the human cell with chemical energy. The foreign source of these bacteria, known as mitochondria, can be proven through cellular examinations revealing that separate “mtDNA” is present alongside of the expected human DNA (Martin, Roettger, and et al). To make this concept of “we are not alone, even in our own bodies” simpler, Thomas uses personification and gives the mitochondria human-like characters. Thomas writes, “They turn out to be little separate creatures, the colonial posterity of migrant prokaryotes, probably primitive bacteria that swam into ancestral precursors of our eukaryotic cells and stayed here” (Thomas 550-552). By giving the foreign bacteria mitochondria human behavior such as “swimming,” and even referring to the organism by using personal pronouns, Thomas is essentially creating a bond between the reader and his writing. As such, the reader is now more drawn into the text and more susceptible to Thomas’s end argument.  
              When an author is attempting to explain something that may not be well understood by everyone, it often makes sense to use comparisons in order to relate confusing information to something that is more widely understood by the general public. It is this exact reason that Thomas uses the literary device known as simile throughout his text. Thomas is attempting to make the point to the reader that human beings are under the illusion that they are the most successfully organism solely due to their own accomplishments. This involves briefly informing the reader of complex biology concepts such as cellular mutation and symbiotic relationships without derailing the main argument. In one specific example, Thomas compares the joint-relationship between humans and mitochondria to that similar of a type of bacteria known as rhizobial found in the roots of beans (Thomas 550-552). This helps show the reader how much humans rely on the presence of a foreign bacteria such as the way plants rely on roots.  Another spot where Thomas utilizes the power of simile to help drive his argument is where he attempts to figure out what the Earth is comparable to. First he compares Earth to an organism (much like a human), but decides that Earth is much too complex to be compared to something so simple. Eventually Thomas concludes “it is most like a single cell”, where he not only uses simile but also a hint of irony to show that the Earth truly is very complex much like a single cell (Thomas 550-552).The irony here is implied for as stated earlier by Thomas, humans have the illusion that they are very simple, stable creatures; but, in reality are only the product of millions of complex cells relatable to the complexity of planet Earth (Thomas 550-552).   
                Another example of a rhetorical strategy Thomas uses is his use of the device known as metaphor. Thomas’s first use of metaphor is used in a way similar to that of his reason for using simile; to help explain a complex issue. A simile compares two unlike things using words such as “like” and “as” whereas a metaphor compares two unlike things by stating that they are the same (Maddox). However, the difference of using a metaphor to compare two unlike things and using a simile to do the same is that a metaphor offers a different sense of tone for the reader. When using a simile in order to simplify a subject the reader is often well-aware of the fact that something is being made simple for them. This often shifts the sense of “power” to the author and the reader is simply along for the ride such as in the earlier example of comparing mitochondria to bacteria in the roots of beans (Thomas 550-552). The control being held by the author is not a bad thing, especially in the case of an argument; it is simply a way for the author to take an authoritative voice. However, when Thomas says, “My cells are no longer the pure line entities I was raised with; they are ecosystems more complex than Jamaica Bay”, he is comparing cells to ecosystems without blatantly stating that a cell is not an ecosystem (Thomas 550-552). Thomas is assuming that the reader can pick up on the fact that an environmental ecosystem is not the same as a living cell, thereby shifting power to the reader. This sense of power the reader gains, no matter how insignificant it may seem, actually empowers Thomas in is argument. He is essentially letting the reader believe that they are now the one in control and as such choosing to side with Thomas in his argument as opposed to being forced to side with him. Another location where Thomas uses metaphor is when he states “Evolution is still an infinitely long and tedious biologic game” (Thomas 550-552). In this case of metaphor Thomas is not so much as trying to make the reader understand evolution as he is trying to say “evolution is not as simple as you may think”. By using metaphor instead of stating this, the reader can continue to believe that they are not being told what to believe. 
            Human beings have essentially become the dominant species on the planet Earth. In fact according Thomas, modern humans have even begun to detach themselves from nature. Unfortunately, this can has lead to a false sense of understanding one’s biological place in nature. In the case of the human race, Thomas believes that this detachment from nature has bred ignorance in the form of an illusion. Thomas argues through the use of rhetorical strategies such as personification, simile, and metaphor that humans have formed the illusion that they are perfect, powerful, and simple beings. Thomas attempts to argue this point by refuting the simplicity of the human organism with facts and information regarding the true nature of the human body. He goes into details such as that of the complexity of a cell and the human’s dependence on foreign entities in order to convince the reader that no organism is a simple, stable, all powerful being. Despite being a complex issue to inform the average person of, Thomas manages to utilize rhetorical strategies and creates an argument that can appeal to anyone. Overall in “The Lives of a Cell” Thomas is telling the reader that despite everything, humans truly are just a bunch of cells.

Works Cited
Maddox, Maeve. "What is the Difference Between Metaphor and Simile?" Daily Writing Tips. n. page. Web. 12 Mar. 2014.Than, Ker. "What is Darwin's Theory of Evolution?" Live Science. (2012): n. page. Web. 11 Mar. 2014.Thomas, Lewis. "The Lives of a Cell." 75 Thematic Readings: An Anthology. New York, New York: McGraw-Hill, 2003. 550-552. Print.William Martin, Roettger, Mayo, et al. "Modern endosymbiotic theory: Getting lateral gene transfer into the equation" Journal of Endocytobiosis and Cell Research. VOL 23. (2012): n. page. Print.             

Sunday, March 16, 2014


The Northeast Collegiate Cyber Defense Competition is a competition designed to test students in the IT and Cyber Security fields. The competition consists of a team of 8 from each College that passed the qualifier round. Teams are given a fresh network in which they must run, secure, and actively defend from hackers (Red Team) over the course of three days. First place is able to move on to the national level of the competition known as CCDC which can be read about more on their home page - http://nationalccdc.org/.

This year NECCDC was held at the University Of New Hampshire and I was fortunate enough to be the first ever freshmen to represent Champlain College. Going into the competition I had no idea what to expect. Despite practice and preparing with my team for months nothing could have prepared me for what the actual competition would have in store. I was chosen to manage our network's client computers and was tasked with securing each device. The clients for NECCDC 2014 included a Kali Linux box, ubuntu, Windows 7. and Windows 8.1. While most of my time was spent on helping enumerate possible threats and vulnerabilities from the Kali system, I was rarely standing still. A constant flow of injects and chaos kept me moving about from system to system in a joint team effort to mitigate incoming attacks from red team. Coming into our network, each box was backdoored from the start with various scripts connection out on arbitrary ports as well as internal cron jobs and tasks that performed....dirty.... actions. One such script discovered would dig out passwords and export them to a Red Team Server.

By day 3 our team was not only stressed and sleep-deprived, but also wary of what to expect. To our surprise we found ourselves in first place at the beginning of day 3. After the final grueling hours of trying to scrape as many points as we could it was "hands off keyboards" and time for red team debriefing. Each team was fortunate enough to get to have our "hackers" from red team come into our room and thoroughly explain what they had done. This was an amazing learning experience in that it is not often systems administrators have the privilege of having their hackers explain exactly what they did and how they did it. 

At the end of the competition Champlain College was able to walk away in second place with RIT in first. Despite winning first place this was a huge accomplishment. Never did I expect to place so well on my first time competing in the competition, especially at my young grade level and age (18 years old). My first NECCDC competition will probably be one of the most memorable experiences of my life and I cannot wait to return next year to take on Red Team once again.

Tuesday, February 11, 2014

Python WebCrawler [Basic] [Practice]

So lately I have been trying to expand on my knowledge by taking on personal projects that help me teach myself new things. While it can be a bit difficult finding time to work on side projects with my official school studies and work, I'm quite happy I found the time for this little project.

My program experience is limited to a brief python introduction last semester, and a java programming class that I am currently in. Personally I favor the python and would really like to get better at it. Unfortunately, after this Java class my programming requirements will be meant for my major so I must work on teaching myself in my spare time. Something that I really wanted to dive into was the networking portion of python using modules such as socket, http.client, urllib.request, and so on. (These are the python v3 variants as I want to focus on learning the newest version of python as opposed to python versions < 3).

After about an hour of reading up on some of the modules in question I decided to just throw myself into a program and try my best. I came up with the idea of making a simple webcrawler as it seemed simple utilizing the little knowledge I just gained on the networking modules.

In an attempt to utilize more then just one module that I read about I decided to go with http.client, and urlib.request as the http support for the socket module was a bit limited for my goal of a webcrawler. After just a little bit of time I ended up with this:

import http.client
import urllib.request
#Brought to you by Hunter Gregal

host=str(input("Please input the target host url. Ex: aptgetswag.com:\n"))
dir1=str(input("Please input the directory to crawl. Ex: '/pages/' or simple '/':\n"))
while (a < len(myName)):
    while (b < len(myExt)):
        myDict.append(myName[a] + myExt[b])
while (i < len(myDict)):
    conn = http.client.HTTPConnection(host)
    conn.request("HEAD", dir1 + myDict[i])
    res = conn.getresponse()
    page = str(("http://" + host + dir1 + myDict[i]))
    if (res.status == 200):
        print(page + "    " + res.reason)
        usock = urllib.request.urlopen(page)
    i = i+1

How It Works :
The code started out as simply a way to check if a specific URL returned an active response. I used http.client to request a connection to a user defined host in a user define directory. The program attempts to make a connection to a predefined list of page names that iterated through another list of predefined extensions. Upon the return of a "200" value (as opposed to a "404" or similar) the urllib.request module then retrieves the pages response headers to print out to the user.

Learning Experience:
Making this simple little program was a huge step in teaching myself python. It gave me the chance to learn in the best way that I know possible: by just doing it. I jumped right in with no idea how to even open a socket in python. Each problem and even syntax error I ran into was a chance for me to learn from my mistakes. At the end of this program I left feeling comfortable that I at least had a grasp on networking in Python. I recommend this method of learning to anyone attempting to teach themselves a programming language.

Friday, January 31, 2014

My First Python Encryptor

As part of my curriculum at Champlain College I was required to take Introduction to Computer Theory. This introduced me to the Python programming language for what was really the first time. My first impression of Python was that I  loved it. I instantly saw the potential that a language like this (or any scripting language such as perl/bash etc.) truly has. 

As my final project for the class I was able to choose to either write a research paper or create my own Python program. Despite my side-love for writing I chose to try something new and write my own program. After a little bit of thought I knew that I wanted to create a simple string encryptor. This seemed to me to be within my skill level, yet at the same time something that would challenge me. I put ALOT of time into this piece of code and taught myself more Python outside of class then was necessary. It was worth it though for at the end I had a working Python program that I was proud of and could truly call my own.

I wrote the code in a way that it could be expanded upon by adding more encryption/decryption methods. This particularly version is simply my one encryption method that I invented wrapped up into a user-input type text interface.

How it works:
1. Asks user to use the program
2. Asks user if they want to encrypt or decrypt a string
3. Asks the user for their desired method
4. If encryption, parses a string seeded with a unique key through an encryption algorithm
5. If decryption parses a encrypted string seeded with the key through a decryption algorithm

Things to keep in mind:
-My invented encryption algorithm is named "bloat"
-Due to the character encoding this program currently only runs in the IDLE environment
-This code was written using Python 3.3.3 and as such will only work when ran using Python version 3.

 Source Code:

#!/usr/bin/env python3
import random
import string
import sys
from collections import deque
#Bloat encryption invented by Hunter Gregal
#Encrypt bloat
def bloat_encrypt(destring,enstring):
    #Asks for a key from the user
    key=str(input("Please enter a key to encrypt the string. This key will be required in order to decrypt it as well.\n: "))
    #gives key numerical value
    i=len(key) - 1
    while i:
        c= c + ord(keylist[i])
    #encodes destring with key
    i=len(destring) -1
    while i:
        n = ord(destringlist[i]) #gives each letter a number value
        destringlist[i]=chr(n+c) #increase each letter value by key value and converts it to its unicode char

   #Further obfuscates destring by salting it  
    while destring:
        #Reverses string and adds random letters
        enstring = (enstring + destring[x] + random.choice(m))
        destring = destring[0:x]
    return destring,enstring
#Decrypt bloat
def bloat_decrypt(destring,enstring):
    key=str(input("Please enter a key to decrypt the string with.\n:"))
    #Reverses string and removes salt
    #gives key numerical value
    i=len(key) - 1
    while i:
        c= c + ord(keylist[i])
    #Decrypts string with the key
    i=len(destring) -1
    while i:
        m = ord(destringlist[i])
    return destring,enstring

Running in IDLE: 

print("Python string encryptor brought to you by Hunter Gregal")
#Define enstring/destring ahead of time
go=input("Would you like to use the program? Y/N\n: ")
while go == "Y" or go == "y":  #Run or breaks the program depending on input
    choice=input("Would you like to decrypt or encrypt a string? [decrypt]/[encrypt]\n: ") #Asks user if they want to encrypt or decrypt
    if choice == "encrypt" or choice == "Encrypt": #If user chooses encrypt....
        method=input("What encryption method would you like to use?\n [bloat]\n: ")
        destring=input("What string would you like to encrypt?\n: ")
        if method == "bloat" or method == "Bloat": #If user chooses bloat run bloat_encrypt function
    elif choice =="decrypt" or choice == "Decrypt": #If user chooses decrypt ....
        method=input("What is the decryption method you would like to use?\n [bloat]\n: ")
        enstring=input("What is the string that you would like to decrypt?\n: ")
        if method == "bloat" or method == "Bloat": #If users chooses bloat run bloat_decrypt function
        go=input("Would you like to use the program again? Y/N\n: ") #Keep running?
input("Press any key to exit")