You are browsing the archive for Anti-Forensics.

HMFT 0.3 + Extended Attributes, short update

February 17, 2013 in Anti-Forensics, Compromise Detection, Forensic Analysis, HMFT, Malware Analysis

update

fixed the title of the post  – it’s obviously a version 0.3 and not 3.0 :-)

old post

In my last post I talked about detecting Extended Attributes (used by ZeroAccess malware) using HMFT.  Today I got a chance to update it a bit with some more information.

First of all, I clustered some of the ZeroAccess samples I had and I came up with a list of comprehensive (of course it’s limited by a sampleset I have) file locations and their Extended Attributes that are used by the malware:

  • %SYSTEMROOT%\system32\services.exe::731
  • %USERPROFILE%\appdata\local\a4ca9b9c\u::@@@ 
  • %USERPROFILE%\AppData\Local\{0c9c4ca4-c3a9-47cf-2e3e-4db8bf2ad457}\U::001
  • %SYSTEMROOT%\$NtUninstallKB16214$\2764741532\U::CFG

You can find a full list of samples using EAs together with hashes (md5_sha1) here.

Secondly, I added some code to HMFT and now it can dump Extended Attribute’s name (and some printable content of the EA value) as well:

   RESIDENT ATTRIBUTE
      AttributeTypeIdentifierD = 224
      LengthOfAttributeD       = 40
      NonResidentFlagB         = 0
      LengthOfNameB            = 0
      OffsetToNameW            = 0
      FlagsW                   = 0
      AttributeIdentifierW     = 4
      --
      SizeOfContentD          = 16
      OffsetToContentW        = 24
      --
        MFTA_EA
            OfsNextEAD      = 16
            FlagsB          = 0
            EaNameLenB      = 3
            EaValueLenW     = 3
            EaName = FOO
            EaValue= bar

Using newer version of HMFT on one of the ZeroAccess samples gives the following result after postprocessing with eads.pl script:

2013-02-17_zeroaccess_ea1

After HMFT update, eads.pl had to be slightly modified::

use strict;
my $f='';
my $l='';
while (<>)
{
  s/[\r\n]+//g;
  $f = $1 if /FileName = (.+)$/;
  print "$f has $1 record\n" if ($l =~ /(MFTA_EA(_[A-Z]+)?)/);
  print "$f:".":$1\n" if (/EaName = (.+)$/);
  print "$f:$1\n" if ($l =~ /MFTA_DATA/&&/AttributeName = (.+)$/);
  $l = $_;
}

Btw. if you look at the screenshot above you will notice :SummaryInformation ADS used by this sample (5D23ACF4C2221B687BC96A2701786C13/ AB7EEC68F9438E31523D0A67E7612CA666C8F56A) as well – it can be even better seen in the window of Process Monitor during the malware installation:

2013-02-17_zeroaccess_ea2

In terms of APIs used by ZeroAccess to create EAs, I finally came across a few samples that use ZwSetEaFile to do so,. Interestingly. none of the samples used this API to create EA for services.exe – all the samples using this API create the following EA:

  • %USERPROFILE%\appdata\local\a4ca9b9c\u::@@@

(Please refer to the older post for more information about the context of this discussion.)

You can download latest hmft here.

 

Detecting Extended Attributes (ZeroAccess) and other Frankenstein’s Monsters with HMFT

January 25, 2013 in Anti-Forensics, Compromise Detection, Forensic Analysis, HMFT, Malware Analysis

The topic of Extended Attributes (EA) has been recently covered in an excellent post by Corey. Entitled Extracting ZeroAccess from NTFS Extended Attributes it goes into (amazing) depth explaining on what EA is and how to extract this artifact from the system. It’s a pure forensic gold and if you haven’t read this post yet, please go ahead and do so before reading mine.

Similarly to Corey, I was very interested in researching EA, and I finally took some time tonight to have a deeper look at it myself. I actually wanted to dig in the code more than the $MFT artifacts alone not only to have something to write about (after all, Corey already covered everything! :-) ), but also because I wanted to see how the EA is actually created and what system functions/APIs are used by malware. The reason behind this curiosity was improvement of my analysis tools and techniques, and a few other ideas that I will be quiet about for the moment.

I first assumed that the ZeroAccess’ EAs are created using ZwSetEaFile/NtSetEaFile function from ntdll.dll. I saw this API name popping up on some blogs and I saw it being referenced in my ZeroAccess memory/file dumps so it was a natural ‘breakpoint’ choice for OllyDbg analysis:

zeroaccess_ea_1

To my surprise, none of the samples I checked used this function at all!

Curious, I started digging into it a bit more and realized that for the samples I looked at, the EAs are actually created not by  ZwSetEaFile/NtSetEaFile function, but by ZwCreateFile/NtCreateFile.

Surprised?

I was!

Looking at a documentation, you can see the following function parameters described on MSDN:

NTSTATUS NtCreateFile(
  _Out_     PHANDLE FileHandle,
  _In_      ACCESS_MASK DesiredAccess,
  _In_      POBJECT_ATTRIBUTES ObjectAttributes,
  _Out_     PIO_STATUS_BLOCK IoStatusBlock,
  _In_opt_  PLARGE_INTEGER AllocationSize,
  _In_      ULONG FileAttributes,
  _In_      ULONG ShareAccess,
  _In_      ULONG CreateDisposition,
  _In_      ULONG CreateOptions,
  _In_      PVOID EaBuffer,
  _In_      ULONG EaLength
);

Yes, it’s that simple.

One thing to note – the EA is added to files on both windows XP and Windows 7, but only under Windows 7 I observed the modification of services.exe. On Windows XP, it only appended EA to the  ‘U’ file and nothing else.

Okay, I mentioned I had a couple of ideas why I wanted to research this feature. Now it’s time to reveal them!

Idea #1 – POC

Once I found out what APIs are being used by the malware, I was also able to produce a simple snippet of code that reproduces the functionality:

.586
.MODEL FLAT,STDCALL

 o equ OFFSET
 include    windows.inc
 include    kernel32.inc
 includelib kernel32.lib
 include    ntdll.inc
 includelib ntdll.lib
 include    masm32.inc
 includelib masm32.lib

IO_STATUS_BLOCK STRUCT
    union
    Status        dd ?
    Pointer        dd ?
    ends
    Information    dd ?
IO_STATUS_BLOCK ENDS

.data?
 file db 256 dup (?)
 fa   db 256 dup (?)
 _FILE_FULL_EA_INFORMATION struct
   NextEntryOffset dd ?
   Flags           db ?
   EaNameLength    db ?
   EaValueLength   dw ?
   EaName          db ?
 _FILE_FULL_EA_INFORMATION ends
 FEA equ _FILE_FULL_EA_INFORMATION
 io IO_STATUS_BLOCK <>
.code
  Start:
  invoke GetCL,1, o file
  lea    edi,[fa+_FILE_FULL_EA_INFORMATION.EaName]
  invoke GetCL,2, edi
  invoke lstrlenA,edi
  lea    esi,[fa+_FILE_FULL_EA_INFORMATION.EaNameLength]
  mov    [esi],al
  add    edi,eax
  inc    edi
  invoke GetCL,3, edi
  invoke lstrlenA,edi
  lea    esi,[fa+_FILE_FULL_EA_INFORMATION.EaValueLength]
  mov    [esi],al
  add    edi,eax
  invoke CreateFileA, o file, \
                      GENERIC_WRITE, \
                      0, \
                      NULL, \
                      CREATE_NEW, \
                      FILE_ATTRIBUTE_NORMAL, \
                      NULL
  xchg   eax,ebx
  mov    eax,edi
  sub    eax,o fa
  invoke NtSetEaFile,ebx,o io,o fa, eax
  invoke CloseHandle,ebx
  invoke ExitProcess,0
END Start

This code can be used for testing purposes in a lab environment.

You can either compile the code yourself using masm32 or you can use a precompiled binary – download it here.

To run:

ea.exe <full path name to a file> <EA name> <EA value>

e.g.:

ea.exe g:\test.txt foo bar

Remember to specify a full path to a file. Also, choose a non-existing file name for a file (the program won’t work with files that are already present).

Last, but not least – there is no error checks, you can add it yourself if you wish :-)

Idea #2 – Reduce the FUD factor

While it is a novelty technique, it is not very advanced -  a single API call does all the dirty job to _create_ the EA.

To _detect_ EA is not very difficult either – as long as you have a right tool to do so :-)

Idea #3 – Show how to detect EA on a live system

Now that I got a POC, I can run it:

g:\test.txt foo bar

and then analyze changes introduced to the file system.

I can do it quickly  with hmft.

hmft -l g: mft_list

I tested the program on a small drive that I use for my tests. I formatted it first to ensure its MFT is clean:
hmft_ea_1

I then opened the mft_list file in a Total Commander’s Lister and searched for MFTA_EA. hmft_ea_2

I am pasting the full record for your reference:

  [FILE]
    SignatureD                    = 1162627398
    OffsetToFixupArrayW           = 48
    NumberOfEntriesInFixupArrayW  = 3
    LogFileSequenceNumberQ        = 1062946
    SequenceValueW                = 1
    LinkCountW                    = 1
    OffsetToFirstAttributeW       = 56
    FlagsW                        = 1
    UsedSizeOfMFTEntryD           = 368
    AllocatedSizeOfMFTEntryD      = 1024
    FileReferenceToBaseRecordQ    = 0
    NextAttributeIdD              = 5
   --

    RESIDENT ATTRIBUTE
      AttributeTypeIdentifierD = 16
      LengthOfAttributeD       = 96
      NonResidentFlagB         = 0
      LengthOfNameB            = 0
      OffsetToNameW            = 0
      FlagsW                   = 0
      AttributeIdentifierW     = 0
      --
      SizeOfContentD          = 72
      OffsetToContentW        = 24
      --
        MFTA_STANDARD_INFORMATION
            CreationTimeQ         = 130036100539989520
            ModificationTimeQ     = 130036100539989520
            MFTModificationTimeQ  = 130036100539989520
            AccessTimeQ           = 130036100539989520
            FlagsD                = 32
            MaxNumOfVersionsD     = 0
            VersionNumberD        = 0
            ClassIdD              = 0
            OwnerIdD              = 0
            SecurityIdD           = 261
            QuotaQ                = 0
            USNQ                  = 0
            CreationTime (epoch)    = 1359136453
            ModificationTime (epoch)  = 1359136453
            MFTModificationTime (epoch)  = 1359136453
            AccessTime (epoch)           = 1359136453
   --

    RESIDENT ATTRIBUTE
      AttributeTypeIdentifierD = 48
      LengthOfAttributeD       = 112
      NonResidentFlagB         = 0
      LengthOfNameB            = 0
      OffsetToNameW            = 0
      FlagsW                   = 0
      AttributeIdentifierW     = 2
      --
      SizeOfContentD          = 82
      OffsetToContentW        = 24
      --
        MFTA_FILE_NAME
            ParentID6             = 5
            ParentUseIndexW       = 5
            CreationTimeQ         = 130036100539989520
            ModificationTimeQ     = 130036100539989520
            MFTModificationTimeQ  = 130036100539989520
            AccessTimeQ           = 130036100539989520
            CreationTime (epoch)    = 1359136453
            ModificationTime (epoch)  = 1359136453
            MFTModificationTime (epoch)  = 1359136453
            AccessTime (epoch)           = 1359136453
            AllocatedSizeQ        = 0
            RealSizeQ             = 0
            FlagsD                = 32
            ReparseValueD         = 0
            LengthOfNameB         = 8
            NameSpaceB            = 3
     FileName = test.txt
   --

    RESIDENT ATTRIBUTE
      AttributeTypeIdentifierD = 128
      LengthOfAttributeD       = 24
      NonResidentFlagB         = 0
      LengthOfNameB            = 0
      OffsetToNameW            = 24
      FlagsW                   = 0
      AttributeIdentifierW     = 1
      --
      SizeOfContentD          = 0
      OffsetToContentW        = 24
      --
        MFTA_DATA
   --

   
    RESIDENT ATTRIBUTE
      AttributeTypeIdentifierD = 208
      LengthOfAttributeD       = 32
      NonResidentFlagB         = 0
      LengthOfNameB            = 0
      OffsetToNameW            = 0
      FlagsW                   = 0
      AttributeIdentifierW     = 3
      --
      SizeOfContentD          = 8
      OffsetToContentW        = 24
      --
        MFTA_EA_INFORMATION
   --

    RESIDENT ATTRIBUTE
      AttributeTypeIdentifierD = 224
      LengthOfAttributeD       = 40
      NonResidentFlagB         = 0
      LengthOfNameB            = 0
      OffsetToNameW            = 0
      FlagsW                   = 0
      AttributeIdentifierW     = 4
      --
      SizeOfContentD          = 16
      OffsetToContentW        = 24
      --
        MFTA_EA

There are two EA-related entries here:

  • MFTA_EA_INFORMATION
  • MFTA_EA record

Manual analysis like this are quite tiring, so we can write a short perl snippet that can help us with postprocessing:

use strict;
my $f='';
my $l='';
while (<>)
{
  s/[\r\n]+//g;
  $f = $1 if /FileName = (.+)$/;
  print "$f has $1 record\n" if ($l =~ /(MFTA_EA(_[A-Z]+)?)/);
  $l = $_;
}

Saving it into ea.pl file, and running it as:

ea.pl mft_list

produces the following output:

hmft_ea_3

Idea #4 – Detect ZeroAccess with hmft

It’s simple :)

  • I ran hmft before the ZeroAccess installation
  • Then I infected my test box
  • I then ran hmft after the ZeroAccess installation

zeroaccess_ea_2

At this stage, all I had to do was to run ea.pl on both outputs and I got the following results:

zeroaccess_ea_3

Or, for the sake of copy & paste (and web bots :) ):

r:\>ea.pl before_installation
V20~1.6 has MFTA_EA_INFORMATION record
V20~1.6 has MFTA_EA record

r:\>ea.pl after_installation
U has MFTA_EA_INFORMATION record
U has MFTA_EA record
V20~1.6 has MFTA_EA_INFORMATION record
V20~1.6 has MFTA_EA record
U has MFTA_EA_INFORMATION record
U has MFTA_EA record
services.exe has MFTA_EA_INFORMATION record
services.exe has MFTA_EA record/span>

As we can see, the malware activity is immediately visible.

Btw. V20~1.6 is a $MFT FILE record that refers to C:\Windows\CSC\v2.0.6 and is related to Offline files (client-side caching). I don’t have any information about the content of this EA. Perhaps someone will be more curious than me to poke around there :-)

Idea #5 – Create a Frankenstein’s monster

Using EA and ADS (Alternate Data Streams) with a single file is also possible.

You can use ea.exe to create such Frankenstein’s monster in 2 simple steps:

  • by running it first with a  filename only – this will create EA record
  • and then re-runing it with a stream name, this will create the ADS, but EA for ADS will fail (sometimes it’s OK to fail :) )

The result is shown on the following screenshot:
ea_frankensteins_monster_1

Using hmft and a combination of ea.pl and ads.pl (posted in older post related to HMFT) in a single eads.pl script:

use strict;
my $f='';
my $l='';
while (<>)
{
  s/[\r\n]+//g;
  $f = $1 if /FileName = (.+)$/;
  print "$f has $1 record\n" if ($l =~ /(MFTA_EA(_[A-Z]+)?)/);
  print "$f:$1\n" if ($l =~ /MFTA_DATA/&&/AttributeName = (.+)$/);
  $l = $_;
}

we can easily detect such beast as well.

That’s all, thanks for reading!

Beyond good ol’ Run key, Part 3

January 19, 2013 in Anti-Forensics, Malware Analysis

Possible Autostart/start mechanisms that are built-in ‘natively’ in Windows and also available by means of extra features offered by many applications go beyond typical path locations and registry keys highlighted by popular programs and scripts like Autoruns and SilentRunners. I have covered some of the non-standard persistence techniques in 2 older posts in the series here and here, but as usual – there is always more to write about.

In this post I will cover another batch of less known and possibly ‘obscure’ technique that could be potentially used for autostart/start purposes. I write ‘obscure’, because it is not a typical way of doing autostart, but let’s be honest – there is nothing really extraordinary about it – just a simple abuse of built-in features in both OS and applications.

Code-in-the-middle proxy

Long story short, it is a well known fact that many existing registry entries and files pointing to or containing code can be modified to introduce a code-in-the-middle proxy (DLL, EXE, etc.) that will be executed/loaded first instead of a legitimate entry. The original entries are preserved so that they can be transparently executed/loaded once malware is running. There are many existing examples of this technique already being used e.g. hijacks of Shell Open Command,  Image File Execution Options , etc., but it is important to remember that this technique can be extended literally to any registry key or file that is loaded either during autostart or often used by users.

Application Registration (App Paths) hijacking

Another proxy technique that could be used to hijack popular applications relies on registry entries stored under the following key:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths

As per Microsoft:

The entries found under App Paths are used primarily for the following purposes:

  • To map an application’s executable file name to that file’s fully qualified path.
  • To pre-pend information to the PATH environment variable on a per-application, per-process basis.

A legitimate entry that can be found on many newer versions of Windows is shown below:

apppaths1

It is responsible for launching MS Paint program when someone tries to run it using a legacy ‘pbrush.exe’ name.

One could add a modification for e.g. calc.exe:

apppaths2

From now on, anytime someone tries to run calc.exe manually (e.g. from command line/ via Start Menu/Run  window), Notepad will be launched. It may not be a main persistence mechanism, but could be used for re-infection purposes on systems that have been cleaned up, but not rebuilt.

Text Services (TSF)

Microsoft defines Text Services as:

Microsoft Windows Text Services Framework (TSF) is a system service available as a redistributable for Windows 2000. TSF provides a simple and scalable framework for the delivery of advanced text input and natural language technologies. TSF can be enabled in applications, or as a TSF text service. A TSF text service provides multilingual support and delivers text services such as keyboard processors, handwriting recognition, and speech recognition.

From a practical point of view, TSF offers ways to extend available input methods by allowing to install support for languages that are not natively supported by Windows. A good example of such extension is Ekaya – an extension for a Myanmar (Burmese) language.

In order for TSF to work on Windows XP, one has to enable the ‘Extended support of advanced text services to all programs’:

TextService-Step01.4

On Windows 7, it is enabled by default (but to install a TSF DLL one requires administrator privileges).

Examples on how to use TSF are provided in Microsoft SDK (look for ‘Samples\winui\Input\tsf\TextService’ directory). For the purpose of this article, I just picked up the simplest possible example i.e. a project from the ‘Samples\winui\Input\tsf\TextService\TextService-Step01′ subdirectory and updated it with a trivial cosmetic change – a call to OutputDebugString so that we can observe processes loading and unloading our test DLL.

BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID pvReserved)
{
  TCHAR szFileFullPath[256];
  TCHAR buf[300];
    switch (dwReason)
    {
        case DLL_PROCESS_ATTACH:

            g_hInst = hInstance;
            GetModuleFileName (NULL,szFileFullPath,256);
             _tcscpy (buf, TEXT("TSF DLL loaded: "));
             _tcscat (buf, szFileFullPath);
            OutputDebugString(buf);
            if (!InitializeCriticalSectionAndSpinCount(&g_cs, 0))
                return FALSE;

            break;

        case DLL_PROCESS_DETACH:

            GetModuleFileName (NULL,szFileFullPath,256);
             _tcscpy (buf, TEXT("TSF DLL unloaded: "));
             _tcscat (buf, szFileFullPath);
            OutputDebugString(buf);

            DeleteCriticalSection(&g_cs);

            break;
    }

    return TRUE;
}

Once registered with Regsrv32.exe:

regsvr32 TextService-Step01.dll

TextService-Step01.1

the DLL is now active and it will now be loaded to each new process utilizing Text Services (pretty much every single GUI application, including these already running) as can be shown via DebugView from Sysinternals.

Running a few test applications shows the following output in DebugView:

TextService-Step01.2

Of course, it survives the reboot and is loaded next time user logs on and applications are executed + it works under Windows 7 without any problem:

TextService-Step01.5

You may be wondering if there is any visual indication of the DLL being present on the system.

There is.

If you look at the legitimate software like aforementioned Ekaya – it adds a set of icons to the Language Bar:

Ekaya1

and

Ekaya2

It can be also seen in Text Services and Input Languages section (you can find it under Regional Settings):

Ekaya3

There is no requirement for TSF DLLs to add extra features to the Language Bar, so the Text Services and Input Languages section under Regional Settings is the only place where it is possible to spot the loaded DLL – for our test sample it looks like this:

TextService-Step01.3

DLL load order

This is a trick relying on  DLL load order – it has been covered on many security blogs in last 2 years so I just mention it for completeness – there are many DLLs that can be ‘injected’ into a loading process of many popular programs. Two of them: fxsst.dll and ntshrui.dll have been covered by Nick Harbour from Mandiant in his posts from July 2010 and June 2011.

IIS Server Extensions (ISAPI filters)

In my older post I mentioned plugins and various extensions that can be loaded into various applications. There are really a lot of possibilities here, including multum of popular software, Windows Shell extensions, aforementioned Text services, IME, URL handlers, and so on and so forth. There are also possibilities of writing server environment-specific extensions e.g. ISAPI filters: As per the information on the page

Every ISAPI filter is contained in a separate DLL that must export two entry-point functions, GetFilterVersionand HttpFilterProc, and optionally export the TerminateFilter function. The metabase property, FilterLoadOrder, contains a list of all filters that IIS loads when the Web service is started.

 AppCertDlls

This is also a known technique – it has been researched and published by EP_X0FF in 2007 on sysinternals forum. There were a few follow-up posts about it, and a sample code can be found here, here and here. If you are interested you may also read ReactOS code that implements this feature here (search for ‘BasepIsProcessAllowed’).

Using a slightly modified code from one of the posts, we can build a DLL to demonstrate how it works.

First we need to add a registry key:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\AppCertDlls

then any REG_EXPAND_SZ value pointing to a DLL we have built.

appcertsdll1

 Now we need to restart the system to ensure a system-wide coverage. For testing purposes, it is okay to restart Windows Explorer so that it can refresh its internal program state to include these DLL in a process creation sequence. Or, one can simply launch cmd.exe and then run programs from command line to observe the DLL being loaded into each newly created process:

appcertsdll2

 You may be wondering how it works under 64-bit system. It works pretty well.

In fact, you can register both 32-bit and 64-bit DLLs as a notification on a 64-bit system:

appcertsdll3

to ensure notifications will be processed for both 64-bit and 32-bit programs:

appcertsdll6

That’s all ! Thanks for reading!

Prefetch file names and UNC paths

October 29, 2012 in Anti-Forensics, Forensic Analysis

In one of the older posts, I talked about how the Prefetch file names are created. Today I was looking at program execution from network shares i.e. originating from the UNC paths and realized that I have not included these in the original article.

VM Shares

To test what happens, I launched WinXP under windbg and put a breakpoint on the hashing function and then executed a test file from a shared VM folder – the screenshot shows the mapping between the drive and the UNC path where the executable is placed:

Once executed, the windbg popped up and I could trace the full path to a file in a Memory window

As it seems, nothing really surprising:

  • z:\test.exe is executed
  • it is mapped to its UNC path \\vmware-host\Shared Folders\X\test.exe
  • which is then prepended with a device name responsible for HGFS file system (used internally by VM) to form a final string used in a hash calculation
  • \DEVICE\HGFS\VMWARE-HOST\SHARED FOLDERS\X\TEST.EXE

Real share

Now, that was the case with a ‘fake’ share created by the VM software.

What about a real share?

Following the same procedure:

  • I mapped a host \\H\C$ drive as N: inside the guest system with ‘net use’
  • and then executed N:\test.exe

The result shown below is not very surprising either as now the path refers to LANMANREDIRECTOR:

  • \DEVICE\LANMANREDIRECTOR\H\C$\TEST.EXE

Substed paths

And in case you are curious what happens to drives created with subst…

For drives mapped locally using ‘subst drive: path’ e.g.

subst g: .

there is no difference as the device will refer to HARDDISKVOLUME### (where ### is hard drive’s number) – I don’t include screenshot here as I hope this example doesn’t need one.

However, using subst in a slightly different way i.e. referring to target path via localhost’s IP: e.g.

subst g: \\127.0.0.1\c$

will make the Prefetch file name to be created using the following path:

  • \DEVICE\LANMANREDIRECTOR\127.0.0.1\C$\TEST.EXE

As you can see, each of the test files created a different hash

In other words, there is plenty of ways to abuse the file naming creation of the prefetch file and it’s quite hard to write an universal hash calculator to cover all these cases – it really depends on the environment and there are lots of tricks to confuse the system + I bet there are a few more that wait to be uncovered.

ZeroAccess death match with Shell_NotifyIconW

September 18, 2012 in Anti-Forensics, Malware Analysis

There is a lot of ZeroAccess analysis all over the place, so not sure if anyone documented it before, but oh well…  here it goes…

I have been recently looking at a new sample of ZeroAccess and spotted that at an early stage of the infection, it injects a small code into Windows Explorer:

The snippet is then executed via Asynchronous Procedure Call (NtQueueApcThread). Just looking at the size of the payload and the strings made me curious enough so I decided to have a quick look at the code.

Turns out, this little snippet doesn’t like Shell_NotifyIconW API very much and it patches it in a very clever and selective way.

The disassembled code of the main routine from the snippet looks like this:

The PatchShell_NotifyIconW function shown on the screenshot is responsible for allocating a small buffer in memory (via ZwAllocateVirtualMemory) that will hold a code of the function modifying the standard behavior of Shell_NotifyIconW API.

As per MSDN, the Shell_NotifyIconW function takes 2 arguments:

BOOL Shell_NotifyIcon(
  _In_  DWORD dwMessage,
  _In_  PNOTIFYICONDATA lpdata
);

The new function installed by ZeroAccess looks like this:

The 33333333h is an address (patched at run-time) to the old unpatched version of the function, so that once ZeroAccess modifies the function’s behavior it can pass the control back to the original function.

As you can see, the patch is simple – it only modifies a dwMessage value so that it is always equal to NIM_DELETE, which pretty much means that any attempts to add/modify/change status of an icon on the notification area (tray) will fail.

While I have not tested it as I don’t have any image with all these security settings on, it seems to be a simple trick to prevent the ‘annoying’  security notifications from happening while the malware is doing its evil thing. This is indirectly confirmed by the way the actual patch occurs. Instead of patching the entry code of Shell_NotifyIconW in a typical, process-global detour-like fashion, the malware walks through all DLLs loaded into Windows Explorer and finds addresses of Shell_NotifyIconW function only within the Import Address Tables  of two DLLs: ActionCenter.dll and wscntfy.dll. These hold the code responsible for the system/tray icon area notifications related to current security state of the system.

Quite frankly, I like this piece of code as it is very neatly written (it even self-removes itself from memory after it is executed) but more importantly, these popups are actually quite annoying! :-)

 

Beyond good ol’ Run key, Part 2

September 16, 2012 in Anti-Forensics, Malware Analysis

In my previous post I described various less-known autoruns mechanisms that can be utilized by malware. This post follows-up on some of the ideas I have described there and lists another batch of applications providing features that could be potentially used by malware authors. This is not to scaremonger users of these applications -  the features described here are actually very useful and needed, and certainly developed in the best interest of the users. Still, they are potential avenues for developing hidden autostart so with ‘the better evil known than unknown’ in mind, here it goes:

Winrar archiver

Allows to define external viewer:

The value is stored under the following registry location:

  • HKEY_CURRENT_USER\Software\WinRAR\Viewer\ExternalViewer

The other user-defined value worth remembering of is the AV scanner integration;

stored in the registry under the following path:

  • HKEY_CURRENT_USER\Software\WinRAR\VirusScan\Name

 WinZip Archiver

WinZip allows for creating Self-extracting archives, the task can be accomplished with a help of an externally defined application:

The value is stored under:

  • HKEY_CURRENT_USER\Software\Nico Mak Computing\WinZip\programs\zip2exe

Other interesting values:

  • HKEY_CURRENT_USER\Software\Nico Mak Computing\WinZip\programs\viewer
  • HKEY_CURRENT_USER\Software\Nico Mak Computing\WinZip\programs\vviewer

Winzip in version 10 and earlier allowed for an antivirus scan same way as WinRar. This feature has been removed from newer versions as explained in this article. The users of old WinZip 10 could define the path to various external programs including antivirus, executable for creating Self-extracting .exes, viewer, as well as 3 external applications to handle old 16-bit archivers ARJ, LHZ and ARC.

The user-defined values could be found in Registry:

  • HKEY_CURRENT_USER\Software\Nico Mak Computing\WinZip\programs\arc
  • HKEY_CURRENT_USER\Software\Nico Mak Computing\WinZip\programs\arj
  • HKEY_CURRENT_USER\Software\Nico Mak Computing\WinZip\programs\lha
  • HKEY_CURRENT_USER\Software\Nico Mak Computing\WinZip\programs\scan
  • HKEY_CURRENT_USER\Software\Nico Mak Computing\WinZip\programs\viewer
  • HKEY_CURRENT_USER\Software\Nico Mak Computing\WinZip\programs\zip2exe

Internet Download Manager

Downloading files from the internet is certainly not a safe operation and IDM allows to define what application will be executed and act an external AV scanner upon a file download:

The actual value is stored here:

  • HKEY_CURRENT_USER\Software\DownloadManager\VScannerProgram

Download Accelerator Plus (DAP)

The very same functionality is present in DAP:

and the value is stored here:

  • HKEY_CURRENT_USER\Software\SpeedBit\Download Accelerator\AntiVirusEXE

 Orbit Downloader

Another popular downloader also offers the antivirus scan functionality:

This time the user-defined value is stored not in Registry, but in a configuration file:

  • %USERPROFILE%\Application Data\Orbit\conf.dat

e.g.

c:\Documents and Settings\user\Application Data\Orbit\conf.dat

 Windows Live Messenger

Instant Messenger applications also allow for defining applications that will be executed upon arrival of a file from the other users of IM. Such setting is present in WLM as well:

The actual value is stored under MSNMessnger branch:

  • HKEY_CURRENT_USER\Software\Microsoft\MSNMessenger\AntiVirus

The value is stored as a binary and in this case data is just an UnicodeZ string

Miranda

Another popular IM that offers antivirus scan is Miranda:

the value is stored in a file in the following location:

  • %USERPROFILE%\Application Data\Miranda\PROFILEFOLDER\PROFILEFILENAME.dat

e.g.

c:\Documents and Settings\user\Application Data\Miranda\foo\foo.dat

It took around 2 hours to download all these applications, test them and write this blog entry. Not a thorough and very advanced research as you can see, but this is what it takes to find new stuff. If you have some spare time and like (or want to learn how) to write a new RegRipper plugin, perhaps now it’s a good time to give it a go :) Thanks for reading!

 

Perfect Timestomping a.k.a. Finding suspicious PE files with clustering

September 1, 2012 in Anti-Forensics, Compromise Detection, Forensic Analysis, Malware Analysis, PECluester, Software Releases

In my previous post about clustering, I mentioned that it can be used as an efficient  data reduction technique. I also provided some examples of timestamps that could be useful for detecting suspicious files on the system. One of them was a compilation time  embedded inside Portable Executables (PE). Turns out that putting this idea into practice is easy and today I wrote a simple perl script that implements this functionality in a few dozen lines of code.

The script scans directory (recursively, if requested) and finds all Portable Executables. It then reads their compilation timestamps and groups them into clusters. Each cluster is a ‘bucket’ holding all binaries compiled within a window of 1 day (86400 seconds). You can play around with the script and change the value of CLUSTER_BOUNDARY to e.g. 30 days and see what happens.

On a screenshot below you can see the script at work – finding all PE files and grouping them into clusters:

And after processing the whole folder, the resulting clusters are printed out:

One needs to quickly scroll through these groups and look at isolated / oprhaned files or small groups and this should hopefully help in finding the bad apples. You can also toy around with the script over clean directories to see what intel you can gather from the compilation timestamps of all PE files inside some specific directory.

For example, after running it over the c:\window\system32 directory of various Windows flavors you may spot some interesting patterns:

  • Portable Executables that are part of Windows OS are not build in an alphabetic order (I originally hoped they are – it could be an interesting pattern to use to spot ‘out-of-orderly’ named executables sandwiched between 2 clean OS files)
  • Still, many OS binaries are compiled sequentially (with a few minutes difference) so many can be easily ignored in analysis
  • On Windows XP and Vista DLLs and EXEs seem to be compiled separately (this is an interesting pattern as  seeing .exe in a sequence of  .dlls should be immediately treated as suspicious; note that system updates may affect this pattern)
  •  On Windows 7 both EXEs and DLLs seem to be compiled w/o any specific pattern :(
  • Clean installation has a very small number of clusters within system32 directory; updated/patched binaries make analysis harder (still, updates will be most likely seen as separate clusters)
  • Files dropped by installers, malware, as well as packed executables, compiled scripts e.g. perl32exe, etc. should stand out, even if timestomped – see how psexec service executable stands out below

Compilation time is a very useful characteristic of Portable Executable. Malware authors occasionally zero it or change it to a random value, but this is still not a very common practice. This, of course is a very good news for investigators and forensic analysts. If timestamp is real (not tampered  with), compilation time of a malicious sample is so unique that it is most likely different from ‘typical’ timestamps that can be found e.g. within system32 directory. As mentioned earlier, PECluester should be able to group such randomly dropped files into separate cluster(s) even if the file system (e.g. $MFT) timestamps are timestomped.

Speaking of the devil. I mentioned ‘perfect timestomping’ in the title of this post.

Why?

Perfect timestomping of a Portable Executable would require not only changing the metadata on the file system, but also changing PE file’s compilation time (and all timestamps inside PE file that could reveal its compilation time) to some carefully chosen value that blends with compilation times of system files (especially for malware dropped inside system folders; for malware within application/temp data folders this – of course – is not that useful).

So, how would we go about finding such perfectly timestomped files?

Good news for forensic investigators is that a compilation timestamp is only one of many possible timestamps that can be found inside a typical Portable Executable. Unless malware author takes a really good care of all these timestamps (either understands Portable Executable file format quite well or uses a specialized tool), there is a high chance one may find some inconsistencies. While not many PE timestamps are properly updated during compilation time (e.g. Resources, Import Table have placeholders for timestamps, but are often zeroed by the compiler), some may include timestamps e.g. Debug Directory as show on a screenshot below:

Other clues about the compilation time can be related to

  • embedded files (author might have forgotten to clean up their timestamps)
  • copyright banners for statically linked libraries
  • standard ‘template’ program icon (e.g. icons for win32 applications created via templates in RAD environment utilize always the same standard icon unless authors changes that; icons change between RAD versions and may give some clues as for the ‘age’ of the malware)
  • libraries/compiler signatures – this is difficult as it requires libraries of known patterns, IDA Pro’s FLIRT signatures come to mind here and may give some hints, but associating these with a specific date is close to impossible
  • even harder – specific to the compiler version code of exception handlers, prologue/epilogue code, compilation flags etc.

Back to PECluester – imho you can use it as an alternative to AV scans and a toy for further research. Go ahead and experiment. Enjoy!

You can download script here.

Beyond good ol’ Run key

July 23, 2012 in Anti-Forensics, Malware Analysis

I recently kept posting quite a lot about random stats from 300k/1M samples. Today something different for a change: non-obvious or less-known autorun entries.

The ‘obvious’ introduction

As we know, malware needs to work. To do so, it needs to ensure it runs when the system starts. Well, not really. In fact, it just needs to ensure it runs in general and can start at any time as long as it is at a right moment to activate its payload (e.g. keylogger doesn’t need to autostart with the system; it can activate when the user opens a browser or mail client).

Malware authors are really lucky.  There are so many autorun possibilities in Windows that it is really hard to count. One of the best known tools that try to enumerate most of the entries are Start Runners and Sysinternals’ autoruns. They both do a a great job by highlighting many of the suspicious files, but… deep inside the registry and file system exist a HUGE number of completely new, unexplored (or possibly less or under- explored) paths that can be (maybe already are)  misused.

Obviously, run-at-system start, run-at-logon are commonly used out of convenience, yet all file/registry locations supporting this persistence mechanism are already very well known and pretty much every single AV is always scanning these locations first (not to mention forensic investigators poking around on the analyzed system :) ). There are of course many examples of other autostart locations that are not system/logon related and these include Browser Helper Objects, Layered Service Provider DLLs, codecs, protocols handlers, shell extensions, toolbars, deskbars, etc. etc. These are not all though and there is a lot of possibilities out there.  In this post I provide a quick brain dump of various ideas related to this subject – some may be considered silly, or not worth attention, but… oh well, it’s just a post about possibilities :) Better evil known that unknown.

The autoruns hidden inside other applications

One of the non-standard autorun entries that is probably the most known and documented is the ICQ entry stored under:

  • HKEY_CURRENT_USER\Software\Mirabilis\ICQ\Agent\Apps

The old version of ICQ allowed to add a list of applications that it would launch when it connected to network – the following screenshots are taken from old versions of this great software (imho it used to be a real killer app!).

Adding calculator to be run by ICQ was relatively easy:

And it would then appear on the list:

Looking at the registry under

  • HKEY_CURRENT_USER\Software\Mirabilis\ICQ\Agent\Apps

would show us the actual entry:

I have a vague memory of successfully testing it ages ago, but since the old version no longer works and I was unable to confirm it for this blog post let’s just trust the evidence that can be found online: Googling for this key brings up quite a few hits that show evidence of it being actively used by malware.

As far as I know new versions of ICQ do not support it anymore.

This, obviously is not the only app ever developed that ‘by design’ helps in launching application when some task/event is completed.

For example, similar functionality can be found in many torrent applications e.g. utorrent:

Adding the entry as shown on the screenshot would make utorrent launch calculator every time it finishes downloading the torrent (the actual data for utorrent autorun is stored inside its configuration file settings.dat).

Same goes for bittorrent client (not a surprise the code of the clients being shared)

Again, the settings.dat holds the ‘autorun’ data:

There may be other applications like this.

The even more hidden autoruns hidden inside applications

Pretty much every single downloader, torrent client, media grabber, etc. contains an option to preview files a.k.a. media player.

This is certainly a possible malware’s autorun as it will be executed anytime someone tries to preview/prelisten the video/music downloaded from P2p client or grabbed from a media grabber; again in a case of e.g. for utorrent:

and emule:

There are certainly lots of applications like this.

‘Scanning’ files with AV when downloaded

Another option to place a malicious file resides in many applications e.g. browsers, mail clients. They allow to scan every single  file that has been downloaded from the internet, attached to email or received via Instant Messenger with an extremal application.

Such feature is available e.g. in Firefox with a Download Status Bar installed.

The about:config page shows the following options (false assigned to ‘downbar.function.virusScan’ property indicates the scan is being disabled)”

the default application selected is ‘C:/Program Files/myAnti-VirusProgram.exe’, but of course malware could easily replace it: 

and modify the ‘downbar.function.virusScan’ property to true.

Notably, placing malware as ‘c:\Program Files\myAnti-VirusProgram.exe’ doesn’t seem to work due to slash/backslash war (this could be a neat trick if it worked).

Windows Shell alternatives

Windows Explorer is not the only Windows Shell available. In fact there are lots of alternatives and each of them brings lots of new options to the table. Looking at programs used by hundreds of thousands (if not millions) of users and including Total Commander, FAR, and many others can cause a real headache. From an offensive perspective there are really a lot of opportunities: from plugins and extensions, to completely new (lame, but certainly workable) ‘rootkitish’ methods for hiding under (sic!) the shell (e.g. custom views, or even simple GUI attacks).

The less obvious places for malware autorun

Most of producers of scanners/printers/combos offer  ‘associated software’ that will be taking control of many aspects of the dialog between the user, device and computer.

One of the tasks handled by the software is  ‘Start this program’ function which is an application that runs when certain events happen e.g. you press a specific button on the scanner/printer. The following screenshot is taken on a system with a CanoScan 4400F scanner attached to it, but with no software installed. The ‘Start this program’ option is grayed out.

Installing a Canon Toolbox gives assigns this program to an event associated with various user activities e.g. pressing COPY button on the scanner.

Clicking the ComboBox reveals more events – all of them are associated with the specific application:

You are probably wondering now where the information about this is stored in the registry/on the file system.

The program responding to device events itself is an example of Push-Model Aware Applications added to the system via Windows Image Acquisition (WIA) / Still Image  interface (STI).

The location in the registry where the Push-Model Aware Applications installed on the system are actually listed are described in the article that I just linked to:

  • HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\StillImage\Registered Applications

The programs registered this way can respond to STI events. Of course, malware could overwrite/manipulate the entry and act as a man in the middle between the devioe and the actual software configured to respond to the event. It could also be added to respond to certain events – the actual registry entries that need to be added are described here (I have not tested it though): and include:

  • HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\explorer\AutoplayHandlers\Handlers
  • HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\StillImage\Registered Applications
  • HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StillImage\Events\STIProxyEvent

Autostart by re-using existing entries

Instead of adding new entries to Run/Startup folder, etc. malware can leverage existing registry entries. In many cases, swapping VERY common entries e.g. for jusched.exe from Java updater, or ctfmon.exe could do the trick. Another option is companion infection for active processes on the system – especially interesting for applications in a Portable format as they are used more and more often and not too many people actually inspect their content. They can also easily be hidden on an inspected system and escape routine analysis of Program Files directory.

Plugins,  Plugins,  Plugins

I mentioned plugins in a context of Windows Explorer alternatives, the same goes for various office suites, Drawing/design applications, gfx viewers (note e.g. Irfanview has a subfolder storing all the plugins – DLL files) and so on and so forth. This is a tip of an iceberg.

File System infection

One of the most interesting pieces of malware back in DOS era was DIR-II. It had a unique way of infecting executable files by modifying their cluster map in the FAT itself. Each .exe would point to a cluster containing the malicious code (always the same cluster) so with a malware NOT active in memory, the file system would appear to be corrupted (because of multiple entries pointing to the same cluster – a problem known as cross-linking). With malware active in memory it would ‘fix’ cross-linking on the fly and execute files properly.

The very same technique could be potentially implemented for NTFS – this would require placing a small .exe on a system then changing the cluster sequence within FILE Record to always point to a cluster occupied by .exe. Other alternative (especially for the one formatted with a FILE record larger than 1024 bytes) would require a tiny .exe that could be stored within the $MFT file record itself (replacing non-resident attribute with a resident attribute) while the actual clusters used by a host file could be stored either in a different part of the file record or within the malicious code itself. In both cases, small .exe would read original clusters and transfer control to the host. Very very non-trivial task. Luckily.

 

The shortest anti-forensics code in the world – take #2

March 16, 2012 in Anti-Forensics

In my older post, I claimed that replacing command line buffer is the shortest anti-forensics code as it takes 25 bytes only.

Sorry, I lied.

There are many ways to come up with a much shorter anti-forensics code. I will describe three ideas here. All of them are super obvious.

#1

Just use CopyFile function and copy Notepad.exe or any other file always present on the system over the file that is meant to be deleted (before its deletion). You may need some extra bytes for the file names, but well, it’s just one API call that it takes to implement a simple secure deletion.

#2

The second idea came (indirectly) from Harlan Carvey. He has been recently writing about his ongoing work to improve Prefetch file parsing script. While reading the MSDN article he referred to, I stumbled upon a description that I have read many times before, but never really thought of it from the anti-forensic angle.

In order to know what it should prefetch, the Windows XP Cache Manager monitors the page faults, both those that require that data be read from disk (hard faults) and those that simply require that data already in memory be added to a process’s working set (soft faults), that occur during the boot process and application startup. By default it traces through the first two minutes of the boot process, 60 seconds following the time when all Win32 services have finished initializing, or 30 seconds following the start of the user’s shell (typically Microsoft Internet Explorer), whichever of these three events occurs first. The Cache Manager also monitors the first 10 seconds of application startup.

Read the last sentence one more time:

The Cache Manager also monitors the first 10 seconds of application startup.

That is.

To reduce a number of forensically useful artifacts stored inside a Prefetch file, all the application has to do is… wait for 10 seconds. This can be easily achieved by running a function Sleep or NtDelayExecution at the entry point. Of course, there are extra bytes needed to import the function, etc., but since malware is often using one of these API anyway, a few bytes is what it takes.

I ran a quick test and it works as described:

The same code executed without any delay produced this Prefetch file:

General information :
  Filename  : PREFTEST.EXE
  Run count : 1
  Run time  : Fri Mar 16 17:29:33 2012 (UTC)

Prefetch file information:
  Reported size     : 2468
  Real size         : 2468
  Last access time  : Fri Mar 16 17:29:48 2012 (UTC)
  Modification time : Fri Mar 16 17:29:43 2012 (UTC)
  Creation time     : Fri Mar 16 17:29:48 2012 (UTC)

Filepaths block (1240) :
  \DEVICE\HARDDISKVOLUME1\WINDOWS\SYSTEM32\NTDLL.DLL
  \DEVICE\HARDDISKVOLUME1\WINDOWS\SYSTEM32\KERNEL32.DLL
  \DEVICE\HARDDISKVOLUME1\WINDOWS\SYSTEM32\UNICODE.NLS
  \DEVICE\HARDDISKVOLUME1\WINDOWS\SYSTEM32\LOCALE.NLS
  \DEVICE\HARDDISKVOLUME1\WINDOWS\SYSTEM32\SORTTBLS.NLS
  \DEVICE\HARDDISKVOLUME1\WINDOWS\PREFETCH\PREFTEST.EXE
  \DEVICE\HARDDISKVOLUME1\WINDOWS\PREFETCH\FILE.TXT

Volume information block (1976) :
  Volume Path   : \DEVICE\HARDDISKVOLUME1
  Serial Number : 1216058920
  Creation Time : Sun Jan  6 13:31:42 2008 (UTC)
  \DEVICE\HARDDISKVOLUME1\
  \DEVICE\HARDDISKVOLUME1\WINDOWS\
  \DEVICE\HARDDISKVOLUME1\WINDOWS\PREFETCH\
  \DEVICE\HARDDISKVOLUME1\WINDOWS\SYSTEM32\

and after adding at least 10 seconds delay at its entry point we get the following result:

General information :
  Filename  : PREFTEST.EXE
  Run count : 1
  Run time  : Fri Mar 16 17:30:30 2012 (UTC)

Prefetch file information:
  Reported size     : 2304
  Real size         : 2304
  Last access time  : Fri Mar 16 17:30:46 2012 (UTC)
  Modification time : Fri Mar 16 17:30:40 2012 (UTC)
  Creation time     : Fri Mar 16 17:30:46 2012 (UTC)

Filepaths block (1184) :
  \DEVICE\HARDDISKVOLUME1\WINDOWS\SYSTEM32\NTDLL.DLL
  \DEVICE\HARDDISKVOLUME1\WINDOWS\SYSTEM32\KERNEL32.DLL
  \DEVICE\HARDDISKVOLUME1\WINDOWS\SYSTEM32\UNICODE.NLS
  \DEVICE\HARDDISKVOLUME1\WINDOWS\SYSTEM32\LOCALE.NLS
  \DEVICE\HARDDISKVOLUME1\WINDOWS\SYSTEM32\SORTTBLS.NLS
  \DEVICE\HARDDISKVOLUME1\WINDOWS\PREFETCH\PREFTEST.EXE

Volume information block (1824) :
  Volume Path   : \DEVICE\HARDDISKVOLUME1
  Serial Number : 1216058920
  Creation Time : Sun Jan  6 13:31:42 2008 (UTC)
  \DEVICE\HARDDISKVOLUME1\
  \DEVICE\HARDDISKVOLUME1\WINDOWS\
  \DEVICE\HARDDISKVOLUME1\WINDOWS\PREFETCH\
  \DEVICE\HARDDISKVOLUME1\WINDOWS\SYSTEM32\

So, if you come across an empty Prefetch file in the future, don’t be surprised :-)

I used this script by Jean François Gingras to parse Prefetch files.

And this is a source of a masm32 code I used in a test:

.586
 .MODEL FLAT,STDCALL
 include    windows.inc
 include    kernel32.inc
 includelib kernel32.lib
 include    user32.inc
 includelib user32.lib

 .data
 file db 'file.txt',0

 .data?
 numOfBytesRead dd ?
 buffer db 256 dup(?)

 .code
 Start:
 ;  invoke Sleep,15*1000
 invoke CreateFileA, OFFSET file, \
 GENERIC_READ, \
 FILE_SHARE_READ or FILE_SHARE_WRITE, \
 NULL, \
 OPEN_EXISTING, \
 FILE_ATTRIBUTE_NORMAL, \
 NULL
 invoke ReadFile, eax, \
 OFFSET buffer, \
 SIZEOF buffer, \
 OFFSET numOfBytesRead, \
 NULL
 ; invoke Sleep,15*1000
 invoke ExitProcess,-1
 END Start

All you have to do is uncomment one of the lines ‘; invoke Sleep,15*1000‘ – first one, if you want to keep the Prefetch file clean, and second one if you want to see ‘file.txt’ inside the Prefetch file associated with the executable. Note, for the .pf file to be created program needs to run for at least 10 seconds and actually read the file.

This sort of tricks may sound like a good idea, but as many forensic investigators already know – and as pointed out by Harlan who commented on one of my previous posts here – that (quoting) “the absence of an artifact where you expect to find one is itself an artifact”. Indeed. Not having any file listed inside the Prefetch file doesn’t change the fact that its sole presence indicates the executable _has_ been ran and some useful forensic data can still be fetched from the *.pf files even if they are kind of empty.

This leads me to the third idea that is the most obvious.

#3

Malware can either delete the prefetch file, or use some way to hide it e.g. using PrefetchADS technique I described in one of my forensic riddles. This also can be achieved with one API call.

 

So, there you have it. Anti-forensics, counter-forensics, or forensics prevention can be implemented in a simple and very effective way. And even if they can’t fool an experienced investigator, they surely can take lots of fun from investigation, increase time spent on chasing after ghosts and remove all the juice from the final report. After all, it’s the ‘smoking gun’ that we all want to show, not a circumstantial evidence that leaves many questions unanswered.

Anti-forensics – live examples

February 18, 2012 in Anti-Forensics, Malware Analysis

Amongst many various techniques that are used by malware to prevent its detection and analysis (e.g. rootkits, disabling OS tools, anti-debug, anti-disasm, anti-dumping, anti-VM, anti-sandbox, etc.), there are a few that are not so common, yet still “make it ” to some malicious releases. These techniques do not prevent malware analysis itself, but aim at making it difficult for forensic guys to analyze post-intrusion activities. And since the reason for using these is to wipe out traces of actual hacking, finding these inside the binaries usually suggests that the malware is designed to be remotely controlled in a manual fashion (and is not a typical botnet serving different purposes like like spam, or DDoS campaigns). Indeed, anti-forensics routines are often seen in backdoors as well as hacking tools used by carders and APT-like malware. Of course, many of these techniques are not new – even old tools from early noughties use it.

Out of curiosity, I recently searched my sample collection for malware that actually do use anti-forensics techniques (Windows specific only). In order to do searches, I first had to think of various techniques I came across in the past or heard of, and then create a list of interesting targets – this is a list I came up with so far:

  • Cache and cookies cleanup (as shown in Purple Haze)
  • Event Logs cleanup (as used in various hacking tools)
  • RestorePoints cleanup (very rarely used technique, I found only a few samples doing so)
  • Weak timestomping (used by many samples, it does change only the timestamps visible in Explorer and shell)
  • Full timestomping (haven’t seen any sample yet)
  • Changing attributes (this one I skipped, because it’s very common, I list it here only for the completeness)
  • Alternate Data Streams (also skipped, because it’s quite common and hard to find good keywords)
  • Patching (creating a way to autostart malware without any known autostart keys; also skipped as it is hard to find good keywords other than opening or mapping files in memory + file names of files being patched, usually user32.dll, etc. so it’s too generic)

My searches continue and if I come across something new, I will add it to the list. And if you know some more or spot some techniques I missed, please do let me know.  Thanks in advance!

So, here it is – if you see any of these functions in the malware you analyze, you better get ready for some serious business!

Cache/Cookies cache cleanup

I posted and example recently when I briefly talked about Purple Haze:

APIs and strings to look for:

  • FindFirstUrlCacheEntryA / FindFirstUrlCacheEntryW
  • UnlockUrlCacheEntryFileA / UnlockUrlCacheEntryFileW
  • DeleteUrlCacheEntryA / DeleteUrlCacheEntryW
  • FindNextUrlCacheEntryA / FindNextUrlCacheEntryW
  • FindCloseUrlCache
  • ‘cookie’
  • ‘Temporary Internet Folder’

Event logs cleanup

The recent sample I came across is a new version of Gh0st. Its source can be easily found online, so it’s not a surprise we continue to see new updated versions. A simple routine used to clean the Event logs uses a triplet of functions i.e. OpenEventLog, ClearEventLog and CloseEventLog that is executed with 3 different Event log types i.e. Application, Security, System.

 

APIs and strings to to look for:

  • OpenEventLogA / OpenEventLogW
  • ClearEventLogA / ClearEventLogW
  • CloseEventLog
  • ‘Application’
  • ‘Security’
  • ‘System’

Restore Points cleanup

This is very rarely seen. The sample I looked at contained the following code:

APIs and strings to to look for:

  • SRRemoveRestorePoint
  • SRSetRestorePointA / SRSetRestorePointW
  • ‘srclient.dll’
  • ‘Last known good configuration’

Weak timestomping

This is an easy one:

APIs and strings to to look for:

  • GetSystemTime
  • SystemTimeToFileTime
  • SetFileTime

Full Timestomping

This is based on Vincent Liu’s technique used in his timestomp tool and later expanded upon by Joakim Schicht in his SetMACE script – it allows for a full modification of all time stamps within the MFT record on NTFS system (2x $FILE_NAME records and $STANDARD_INFORMATION) either by using NtSetInformationFile / ZwSetInformationFile or by directly writing to a \\.\PhysicalDriveXXX device (where XXX is a number 0, 1, 2, …):

I have not found any malware using it, but this is also non-trivial to find.

APIs and strings to to look for:

  • NtSetInformationFile / ZwSetInformationFile
  • ‘\\.\PhysicalDrive’

and often together with the following, commonly used functions:

  • NtQueryInformationFile / ZwQueryInformationFile
  • NtOpenFile / ZwOpenFile
  • NtClose / ZwClose
  • DeviceIoControl / NtDeviceIoControl / ZwDeviceIoControl
  • RtlInitUnicodeString