Malware

Presenter Notes

Obligatory Disclaimer

Everything here is dual use

Learn about malware, malware techniques, etc. . .

Presenter Notes

Process Environment Block (PEB)

All processes contain a PEB from _EPROCESS

  • Win32 at [FS:30h]
  • Win64 at [GS:60h]
  • Contains full path to executable

Full command line and arguments

Working Directory

Process Heaps

Standard handles (Stdin/out/err)

Loaded DLLs (_PEB_LDR_DATA)

Exists in user space

Easily modifiable

Presenter Notes

PEB

OS Version Information

Process Creation Flags

BeingDebugged

ImageBaseAddress

Presenter Notes

_PEB

>>> dt ("_PEB")
 '_PEB' (584 bytes)
0x0   : InheritedAddressSpace          ['unsigned char']
0x1   : ReadImageFileExecOptions       ['unsigned char']
0x2   : BeingDebugged                  ['unsigned char']
0x3   : BitField                       ['unsigned char']h
0x3   : ImageUsesLargePages            ['BitField', {'end_bit': 1, 'start_bit': 0, 'native_type': 'unsigned char'}]
0x3   : IsImageDynamicallyRelocated    ['BitField', {'end_bit': 4, 'start_bit': 3, 'native_type': 'unsigned char'}]
0x3   : IsLegacyProcess                ['BitField', {'end_bit': 3, 'start_bit': 2, 'native_type': 'unsigned char'}]
0x3   : IsProtectedProcess             ['BitField', {'end_bit': 2, 'start_bit': 1, 'native_type': 'unsigned char'}]
0x3   : SkipPatchingUser32Forwarders   ['BitField', {'end_bit': 5, 'start_bit': 4, 'native_type': 'unsigned char'}]
0x3   : SpareBits                      ['BitField', {'end_bit': 8, 'start_bit': 5, 'native_type': 'unsigned char'}]
0x4   : Mutant                         ['pointer', ['void']]
0x8   : ImageBaseAddress               ['pointer', ['void']]
0xc   : Ldr                            ['pointer', ['_PEB_LDR_DATA']]
0x10  : ProcessParameters              ['pointer', ['_RTL_USER_PROCESS_PARAMETERS']]
0x14  : SubSystemData                  ['pointer', ['void']]
0x18  : ProcessHeap                    ['pointer', ['void']]
0x1c  : FastPebLock                    ['pointer', ['_RTL_CRITICAL_SECTION']]
0x20  : AtlThunkSListPtr               ['pointer', ['void']]
0x24  : IFEOKey                        ['pointer', ['void']]
0x28  : CrossProcessFlags              ['unsigned long']
0x28  : ProcessInJob                   ['BitField', {'end_bit': 1, 'start_bit': 0, 'native_type': 'unsigned long'}]
0x28  : ProcessInitializing            ['BitField', {'end_bit': 2, 'start_bit': 1, 'native_type': 'unsigned long'}]
0x28  : ProcessUsingFTH                ['BitField', {'end_bit': 5, 'start_bit': 4, 'native_type': 'unsigned long'}]
0x28  : ProcessUsingVCH                ['BitField', {'end_bit': 4, 'start_bit': 3, 'native_type': 'unsigned long'}]
0x28  : ProcessUsingVEH                ['BitField', {'end_bit': 3, 'start_bit': 2, 'native_type': 'unsigned long'}]
0x28  : ReservedBits0                  ['BitField', {'end_bit': 32, 'start_bit': 5, 'native_type': 'unsigned long'}]
0x2c  : KernelCallbackTable            ['pointer', ['void']]
0x2c  : UserSharedInfoPtr              ['pointer', ['void']]
0x30  : SystemReserved                 ['array', 1, ['unsigned long']]
0x34  : AtlThunkSListPtr32             ['unsigned long']
0x38  : ApiSetMap                      ['pointer', ['void']]
0x3c  : TlsExpansionCounter            ['unsigned long']
0x40  : TlsBitmap                      ['pointer', ['void']]
0x44  : TlsBitmapBits                  ['array', 2, ['unsigned long']]
0x4c  : ReadOnlySharedMemoryBase       ['pointer', ['void']]
0x50  : HotpatchInformation            ['pointer', ['void']]
0x54  : ReadOnlyStaticServerData       ['pointer', ['pointer', ['void']]]
0x58  : AnsiCodePageData               ['pointer', ['void']]
0x5c  : OemCodePageData                ['pointer', ['void']]
0x60  : UnicodeCaseTableData           ['pointer', ['void']]
0x64  : NumberOfProcessors             ['unsigned long']
0x68  : NtGlobalFlag                   ['unsigned long']
0x70  : CriticalSectionTimeout         ['_LARGE_INTEGER']
0x78  : HeapSegmentReserve             ['unsigned long']
0x7c  : HeapSegmentCommit              ['unsigned long']
0x80  : HeapDeCommitTotalFreeThreshold ['unsigned long']
0x84  : HeapDeCommitFreeBlockThreshold ['unsigned long']
0x88  : NumberOfHeaps                  ['unsigned long']
0x8c  : MaximumNumberOfHeaps           ['unsigned long']
0x90  : ProcessHeaps                   ['pointer', ['array', <function <lambda> at 0x93fa534>, ['pointer', ['_HEAP']]]]
0x94  : GdiSharedHandleTable           ['pointer', ['void']]
0x98  : ProcessStarterHelper           ['pointer', ['void']]
0x9c  : GdiDCAttributeList             ['unsigned long']
0xa0  : LoaderLock                     ['pointer', ['_RTL_CRITICAL_SECTION']]
0xa4  : OSMajorVersion                 ['unsigned long']
0xa8  : OSMinorVersion                 ['unsigned long']
0xac  : OSBuildNumber                  ['unsigned short']
0xae  : OSCSDVersion                   ['unsigned short']
0xb0  : OSPlatformId                   ['unsigned long']
0xb4  : ImageSubsystem                 ['unsigned long']
0xb8  : ImageSubsystemMajorVersion     ['unsigned long']
0xbc  : ImageSubsystemMinorVersion     ['unsigned long']
0xc0  : ActiveProcessAffinityMask      ['unsigned long']
0xc4  : GdiHandleBuffer                ['array', 34, ['unsigned long']]
0x14c : PostProcessInitRoutine         ['pointer', ['void']]
0x150 : TlsExpansionBitmap             ['pointer', ['void']]
0x154 : TlsExpansionBitmapBits         ['array', 32, ['unsigned long']]
0x1d4 : SessionId                      ['unsigned long']
0x1d8 : AppCompatFlags                 ['_ULARGE_INTEGER']
0x1e0 : AppCompatFlagsUser             ['_ULARGE_INTEGER']
0x1e8 : pShimData                      ['pointer', ['void']]
0x1ec : AppCompatInfo                  ['pointer', ['void']]
0x1f0 : CSDVersion                     ['_UNICODE_STRING']
0x1f8 : ActivationContextData          ['pointer', ['_ACTIVATION_CONTEXT_DATA']]
0x1fc : ProcessAssemblyStorageMap      ['pointer', ['_ASSEMBLY_STORAGE_MAP']]
0x200 : SystemDefaultActivationContextData ['pointer', ['_ACTIVATION_CONTEXT_DATA']]
0x204 : SystemAssemblyStorageMap       ['pointer', ['_ASSEMBLY_STORAGE_MAP']]
0x208 : MinimumStackCommit             ['unsigned long']
0x20c : FlsCallback                    ['pointer', ['_FLS_CALLBACK_INFO']]
0x210 : FlsListHead                    ['_LIST_ENTRY']
0x218 : FlsBitmap                      ['pointer', ['void']]
0x21c : FlsBitmapBits                  ['array', 4, ['unsigned long']]
0x22c : FlsHighIndex                   ['unsigned long']
0x230 : WerRegistrationData            ['pointer', ['void']]
0x234 : WerShipAssertPtr               ['pointer', ['void']]
0x238 : pContextData                   ['pointer', ['void']]
0x23c : pImageHeaderHash               ['pointer', ['void']]
0x240 : CritSecTracingEnabled          ['BitField', {'end_bit': 2, 'start_bit': 1, 'native_type': 'unsigned long'}]
0x240 : HeapTracingEnabled             ['BitField', {'end_bit': 1, 'start_bit': 0, 'native_type': 'unsigned long'}]
0x240 : SpareTracingBits               ['BitField', {'end_bit': 32, 'start_bit': 2, 'native_type': 'unsigned long'}]
0x240 : TracingFlags                   ['unsigned long']

Presenter Notes

_RTL_USER_PROCESS_PARAMETERS

Std{In,Out,Err}

ImagePathName is full

  • _EPROCESS.ImageFileName is 16 chars

Command Line Args

Environmental Variables

>>> dt("_RTL_USER_PROCESS_PARAMETERS")
 '_RTL_USER_PROCESS_PARAMETERS' (664 bytes)
0x0   : MaximumLength                  ['unsigned long']
0x4   : Length                         ['unsigned long']
0x8   : Flags                          ['unsigned long']
0xc   : DebugFlags                     ['unsigned long']
0x10  : ConsoleHandle                  ['pointer', ['void']]
0x14  : ConsoleFlags                   ['unsigned long']
0x18  : StandardInput                  ['pointer', ['void']]
0x1c  : StandardOutput                 ['pointer', ['void']]
0x20  : StandardError                  ['pointer', ['void']]
0x24  : CurrentDirectory               ['_CURDIR']
0x30  : DllPath                        ['_UNICODE_STRING']
0x38  : ImagePathName                  ['_UNICODE_STRING']
0x40  : CommandLine                    ['_UNICODE_STRING']
0x48  : Environment                    ['pointer', ['void']]
0x4c  : StartingX                      ['unsigned long']
0x50  : StartingY                      ['unsigned long']
0x54  : CountX                         ['unsigned long']
0x58  : CountY                         ['unsigned long']
0x5c  : CountCharsX                    ['unsigned long']
0x60  : CountCharsY                    ['unsigned long']
0x64  : FillAttribute                  ['unsigned long']
0x68  : WindowFlags                    ['unsigned long']
0x6c  : ShowWindowFlags                ['unsigned long']
0x70  : WindowTitle                    ['_UNICODE_STRING']
0x78  : DesktopInfo                    ['_UNICODE_STRING']
0x80  : ShellInfo                      ['_UNICODE_STRING']
0x88  : RuntimeData                    ['_UNICODE_STRING']
0x90  : CurrentDirectores              ['array', 32, ['_RTL_DRIVE_LETTER_CURDIR']]
0x290 : EnvironmentSize                ['unsigned long']
0x294 : EnvironmentVersion             ['unsigned long']

Presenter Notes

DLL Loading

_PEB._LDR_DATA

Contains 3 circular linked lists of loaded modules

  • InLoadOrder

    • Loaded into process. *.exe is always first.
  • InMemoryOrder

    • Order in which DLLs appear in memory. ASLR changes.
  • InInitializationOrder

    • When the DllMain fires.
    • Just because DLL is loaded does not mean it executes.

Malware/packers LOVES this

Presenter Notes

PEB_LDR_DATA

>>> dt("_PEB_LDR_DATA")
 '_PEB_LDR_DATA' (48 bytes)
0x0   : Length                         ['unsigned long']
0x4   : Initialized                    ['unsigned char']
0x8   : SsHandle                       ['pointer', ['void']]
0xc   : InLoadOrderModuleList          ['_LIST_ENTRY']
0x14  : InMemoryOrderModuleList        ['_LIST_ENTRY']
0x1c  : InInitializationOrderModuleList ['_LIST_ENTRY']
0x24  : EntryInProgress                ['pointer', ['void']]
0x28  : ShutdownInProgress             ['unsigned char']
0x2c  : ShutdownThreadId               ['pointer', ['void']]

Presenter Notes

DATA_TABLE_ENTRY

>>> dt("_LDR_DATA_TABLE_ENTRY")
'_LDR_DATA_TABLE_ENTRY' (120 bytes)
0x0   : InLoadOrderLinks               ['_LIST_ENTRY']
0x8   : InMemoryOrderLinks             ['_LIST_ENTRY']
0x10  : InInitializationOrderLinks     ['_LIST_ENTRY']
0x18  : DllBase                        ['pointer', ['void']]
0x1c  : EntryPoint                     ['pointer', ['void']]
0x20  : SizeOfImage                    ['unsigned long']
0x24  : FullDllName                    ['_UNICODE_STRING']
0x2c  : BaseDllName                    ['_UNICODE_STRING']
0x34  : Flags                          ['unsigned long']
0x38  : LoadCount                      ['unsigned short']
0x3a  : TlsIndex                       ['unsigned short']
0x3c  : HashLinks                      ['_LIST_ENTRY']
0x3c  : SectionPointer                 ['pointer', ['void']]
0x40  : CheckSum                       ['unsigned long']
0x44  : LoadedImports                  ['pointer', ['void']]
0x44  : TimeDateStamp                  ['UnixTimeStamp', {'is_utc': True}]
0x48  : EntryPointActivationContext    ['pointer', ['_ACTIVATION_CONTEXT']]
0x4c  : PatchInformation               ['pointer', ['void']]
0x50  : ForwarderLinks                 ['_LIST_ENTRY']
0x58  : ServiceTagLinks                ['_LIST_ENTRY']
0x60  : StaticLinks                    ['_LIST_ENTRY']
0x68  : ContextInformation             ['pointer', ['void']]
0x6c  : OriginalBase                   ['unsigned long']
0x70  : LoadTime                       ['WinTimeStamp', {'is_utc': True}]

Presenter Notes

_PEB Enumeration

Windbg

Volatility

  • Find address of _EPROCESS
  • Go to _PEB
  • List strucutre

PEB could be paged

Presenter Notes

Enumeration

0:003> !peb
PEB at 000007fffffdf000
    InheritedAddressSpace:    No
    ReadImageFileExecOptions: No
    BeingDebugged:            Yes
    ImageBaseAddress:         00000000ff510000
    Ldr                       0000000077482640
    Ldr.Initialized:          Yes
    Ldr.InInitializationOrderModuleList: 00000000000e3030 . 0000000000152740
    Ldr.InLoadOrderModuleList:           00000000000e2f20 . 0000000000152720
    Ldr.InMemoryOrderModuleList:         00000000000e2f30 . 0000000000152730
            Base TimeStamp                     Module
        ff510000 4a5bc9d4 Jul 13 16:57:08 2009 C:\Windows\system32\calc.exe
        77350000 521eaf24 Aug 28 19:17:08 2013 C:\Windows\SYSTEM32\ntdll.dll
        77130000 5315a059 Mar 04 01:43:53 2014 C:\Windows\system32\kernel32.dll
     7fefd430000 5315a05a Mar 04 01:43:54 2014 C:\Windows\system32\KERNELBASE.dll
     7fefe090000 54dd89c7 Feb 12 21:21:11 2015 C:\Windows\system32\SHELL32.dll
     7feff5b0000 4eeb033f Dec 16 00:37:19 2011 C:\Windows\system32\msvcrt.dll
     7feff530000 4ce7c9ab Nov 20 05:14:19 2010 C:\Windows\system32\SHLWAPI.dll
     7feff4c0000 53f7f650 Aug 22 19:02:56 2014 C:\Windows\system32\GDI32.dll
        77250000 4ce7c9f1 Nov 20 05:15:29 2010 C:\Windows\system32\USER32.dll
     7feff650000 54e6ba7d Feb 19 20:39:25 2015 C:\Windows\system32\LPK.dll
     7feff3f0000 5359c98c Apr 24 19:33:48 2014 C:\Windows\system32\USP10.dll
     7fefb650000 535b1ac9 Apr 25 19:32:41 2014 C:\Windows\WinSxS\amd64_microsoft.windows.gdiplus_6595b64144ccf1df_1.1.7601.18455_none_2b283fd671e9bf4d\gdiplus.dll
     7feff1e0000 4ce7c92c Nov 20 05:12:12 2010 C:\Windows\system32\ole32.dll
     7fefdc70000 53c339ee Jul 13 19:01:18 2014 C:\Windows\system32\RPCRT4.dll
     7feff020000 521eae52 Aug 28 19:13:38 2013 C:\Windows\system32\ADVAPI32.dll
     7fefee70000 4a5be05e Jul 13 18:33:18 2009 C:\Windows\SYSTEM32\sechost.dll
     7feff100000 5441ca8a Oct 17 19:03:54 2014 C:\Windows\system32\OLEAUT32.dll
     7fefb870000 4a5be093 Jul 13 18:34:11 2009 C:\Windows\system32\UxTheme.dll
     7fefba80000 4ce7c45b Nov 20 04:51:39 2010 C:\Windows\WinSxS\amd64_microsoft.windows.common-controls_6595b64144ccf1df_6.0.7601.17514_none_fa396087175ac9ac\COMCTL32.dll
     7fefac60000 4a5be0b0 Jul 13 18:34:40 2009 C:\Windows\system32\WINMM.dll
     7fefbf70000 4a5be082 Jul 13 18:33:54 2009 C:\Windows\system32\VERSION.dll
     7fefd4d0000 4a5bdf40 Jul 13 18:28:32 2009 C:\Windows\system32\IMM32.DLL
     7fefee90000 54b9cd47 Jan 16 18:47:35 2015 C:\Windows\system32\MSCTF.dll
     7fefa910000 54c9c3ff Jan 28 21:24:15 2015 C:\Windows\system32\WindowsCodecs.dll
     7fefb020000 4a5bdf27 Jul 13 18:28:07 2009 C:\Windows\system32\dwmapi.dll
     7fefcfb0000 4a5bdf91 Jul 13 18:29:53 2009 C:\Windows\system32\CRYPTBASE.dll
     7fefddc0000 4a5bdeba Jul 13 18:26:18 2009 C:\Windows\system32\CLBCatQ.DLL
     7fefa030000 4e587ee5 Aug 26 22:21:41 2011 C:\Windows\system32\oleacc.dll
    SubSystemData:     0000000000000000
    ProcessHeap:       00000000000e0000
    ProcessParameters: 00000000000e22b0
    CurrentDirectory:  'C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\'
    WindowTitle:  'C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\Calculator.lnk'
    ImageFile:    'C:\Windows\system32\calc.exe'
    CommandLine:  '"C:\Windows\system32\calc.exe" '
    DllPath:      'C:\Windows\system32;;C:\Windows\system32;C:\Windows\system;C:\Windows;.;C:\Python27\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;c:\/bin;C:\Program Files\TortoiseGit\bin;C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\;C:\Program Files\Microsoft SQL Server\110\Tools\Binn\;C:\HashiCorp\Vagrant\bin;C:\Program Files (x86)\OpenSSH\bin;C:\Users\Topher\AppData\Local\Pandoc\;C:\Program Files (x86)\Microsoft Visual Studio 12.0\V;C\bin;C:\Python27\Scripts;C:\MinGW\bin;C:\Program Files (x86)\Prince\Engine\bin;'
    Environment:  00000000000e1320
        =::=::\
        ALLUSERSPROFILE=C:\ProgramData
        APPDATA=C:\Users\Topher\AppData\Roaming
        CommonProgramFiles=C:\Program Files\Common Files
        CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
        CommonProgramW6432=C:\Program Files\Common Files
        COMPUTERNAME=TOPHER-PC
        ComSpec=C:\Windows\system32\cmd.exe
        CYGWIN=tty
        FP_NO_HOST_CHECK=NO
        GIT_SSH=C:\Program Files\TortoiseGit\bin\TortoiseGitPlink.exe
        HOMEDRIVE=C:
        HOMEPATH=\Users\Topher
        LOCALAPPDATA=C:\Users\Topher\AppData\Local
        LOGONSERVER=\\TOPHER-PC
        NUMBER_OF_PROCESSORS=8
        OS=Windows_NT
        Path=C:\Python27\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;c:\/bin;C:\Program Files\TortoiseGit\bin;C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\;C:\Program Files\Microsoft SQL Server\110\Tools\Binn\;C:\HashiCorp\Vagrant\bin;C:\Program Files (x86)\OpenSSH\bin;C:\Users\Topher\AppData\Local\Pandoc\;C:\Program Files (x86)\Microsoft Visual Studio 12.0\V;C\bin;C:\Python27\Scripts;C:\MinGW\bin;C:\Program Files (x86)\Prince\Engine\bin;
        PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
        PROCESSOR_ARCHITECTURE=AMD64
        PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 60 Stepping 3, GenuineIntel
        PROCESSOR_LEVEL=6
        PROCESSOR_REVISION=3c03
        ProgramData=C:\ProgramData
        ProgramFiles=C:\Program Files
        ProgramFiles(x86)=C:\Program Files (x86)
        ProgramW6432=C:\Program Files
        PSModulePath=C:\Windows\system32\WindowsPowerShell\v1.0\Modules\
        PUBLIC=C:\Users\Public
        SESSIONNAME=Console
        SVN_SSH=C:\Program Files\TortoiseGit\bin\TortoiseGitPlink.exe
        SystemDrive=C:
        SystemRoot=C:\Windows
        TEMP=C:\Users\Topher\AppData\Local\Temp
        TMP=C:\Users\Topher\AppData\Local\Temp
        USERDOMAIN=Topher-PC
        USERNAME=Topher
        USERPROFILE=C:\Users\Topher
        VBOX_MSI_INSTALL_PATH=C:\Program Files\Oracle\VirtualBox\
        VS120COMNTOOLS=C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\
        windir=C:\Windows
        windows_tracing_flags=3
        windows_tracing_logfile=C:\BVTBin\Tests\installpackage\csilogfile.log

Presenter Notes

Dll paths, Full environment variables All DLLS loaded

With Volatility

>>> sc()
Current context: explorer.exe @ 0x8625b420, pid=352, ppid=1848 DTB=0x3ecec3e0

>>> dt("_EPROCESS", 0x8625b420)
[_EPROCESS _EPROCESS] @ 0x8625B420
0x1a8 : Peb                            2147332096


>>> dt("_PEB", 2147332096)
[CType _PEB] @ 0x7FFDB000
0x0   : InheritedAddressSpace          0
0x1   : ReadImageFileExecOptions       0
0x2   : BeingDebugged                  0
0x3   : BitField                       8
0x3   : ImageUsesLargePages            0
0x3   : IsImageDynamicallyRelocated    1
0x3   : IsLegacyProcess                0
0x3   : IsProtectedProcess             0
0x3   : SkipPatchingUser32Forwarders   0
0x3   : SpareBits                      0
0x4   : Mutant                         4294967295
0x8   : ImageBaseAddress               10027008
0xc   : Ldr                            2003400832
0x10  : ProcessParameters              1774304
0x14  : SubSystemData                  0
0x18  : ProcessHeap                    1769472
0x1c  : FastPebLock                    2003399552
0x20  : AtlThunkSListPtr               0
0x24  : IFEOKey                        0
0x28  : CrossProcessFlags              0
0x28  : ProcessInJob                   0
0x28  : ProcessInitializing            0
0x28  : ProcessUsingFTH                0
0x28  : ProcessUsingVCH                0
0x28  : ProcessUsingVEH                0
0x28  : ReservedBits0                  0
0x2c  : KernelCallbackTable            1996871016
0x2c  : UserSharedInfoPtr              1996871016
0x30  : SystemReserved                 -
0x34  : AtlThunkSListPtr32             66783744
0x38  : ApiSetMap                      2004877312
0x3c  : TlsExpansionCounter            0
0x40  : TlsBitmap                      2003399264
0x44  : TlsBitmapBits                  -
0x4c  : ReadOnlySharedMemoryBase       2137980928
0x50  : HotpatchInformation            0
0x54  : ReadOnlyStaticServerData       2137982352
0x58  : AnsiCodePageData               2147155968
0x5c  : OemCodePageData                2147222052
0x60  : UnicodeCaseTableData           2147288648
0x64  : NumberOfProcessors             1
0x68  : NtGlobalFlag                   0
0x70  : CriticalSectionTimeout         2147332208
0x78  : HeapSegmentReserve             1048576
0x7c  : HeapSegmentCommit              8192
0x80  : HeapDeCommitTotalFreeThreshold 65536
0x84  : HeapDeCommitFreeBlockThreshold 4096
0x88  : NumberOfHeaps                  13
0x8c  : MaximumNumberOfHeaps           16
0x90  : ProcessHeaps                   2003399936
0x94  : GdiSharedHandleTable           3997696
0x98  : ProcessStarterHelper           0
0x9c  : GdiDCAttributeList             20
0xa0  : LoaderLock                     2003399488
0xa4  : OSMajorVersion                 6
0xa8  : OSMinorVersion                 1
0xac  : OSBuildNumber                  7601
0xae  : OSCSDVersion                   256
0xb0  : OSPlatformId                   2
0xb4  : ImageSubsystem                 2
0xb8  : ImageSubsystemMajorVersion     6
0xbc  : ImageSubsystemMinorVersion     1
0xc0  : ActiveProcessAffinityMask      1
0xc4  : GdiHandleBuffer                -
0x14c : PostProcessInitRoutine         0
0x150 : TlsExpansionBitmap             2003399272
0x154 : TlsExpansionBitmapBits         -
0x1d4 : SessionId                      1
0x1d8 : AppCompatFlags                 2147332568
0x1e0 : AppCompatFlagsUser             2147332576
0x1e8 : pShimData                      0
0x1ec : AppCompatInfo                  0
0x1f0 : CSDVersion                     Service Pack 1
0x1f8 : ActivationContextData          262144
0x1fc : ProcessAssemblyStorageMap      1945264
0x200 : SystemDefaultActivationContextData 196608
0x204 : SystemAssemblyStorageMap       1839920
0x208 : MinimumStackCommit             0
0x20c : FlsCallback                    1846536
0x210 : FlsListHead                    2147332624
0x218 : FlsBitmap                      2003399280
0x21c : FlsBitmapBits                  -
0x22c : FlsHighIndex                   3
0x230 : WerRegistrationData            55640064
0x234 : WerShipAssertPtr               0
0x238 : pContextData                   327680
0x23c : pImageHeaderHash               0
0x240 : CritSecTracingEnabled          0
0x240 : HeapTracingEnabled             0
0x240 : SpareTracingBits               0
0x240 : TracingFlags                   0


>>> dt("_PEB_LDR_DATA", 2003400832)
[CType _PEB_LDR_DATA] @ 0x77697880
0x0   : Length                         48
0x4   : Initialized                    1
0x8   : SsHandle                       0
0xc   : InLoadOrderModuleList          2003400844
0x14  : InMemoryOrderModuleList        2003400852
0x1c  : InInitializationOrderModuleList 2003400860
0x24  : EntryInProgress                0
0x28  : ShutdownInProgress             0
0x2c  : ShutdownThreadId               0

Presenter Notes

Environment Variables

_PEB.ProcessParameters.Envvionrment

- Points to NULL-terminated strings

Attackers use to store shellcode/keys/flags. . .

Can set variables per user and process

Can be volatile and destroyed at system shutdown

BOOL WINAPI SetEnvironmentVariable(
  _In_      LPCTSTR lpName,
  _In_opt_  LPCTSTR lpValue
);

Presenter Notes

Environment Variables

Child processes inherit environment block

  • Unless lpEnviornment is used in CreateProcess()

Contains

  • $PATH
  • $PATHEXT
  • $WINDIR
  • Temp Direcotires
  • User/Computer/Domain names
  • Location of cmd.exe

Presenter Notes

ENV: Continued

$PATH and $PATHEXT

  • Used to locate order in which to find files/executables
  • Path order hijacking
  • Start->Run->*.exe
    • Could be alerted by PATH to look at user controlled location first
  • Start->run->name
  • Looks for $PATHEXT for what to search for first if user does not specify .exe,.dll, etc.

Presenter Notes

ENV

Malware likes to not have duplicates of itself...

Remember Mutants?

Could also use ENV to check if a malware already is present on system

Add special argument to $PATH, $USERPROFILE, etc.

Presenter Notes

Process Heaps

Memdump and Vaddump contain heap artifacts

Yara also scans heaps

Heaps are for dynamic memory

Contain juicy sources of data

We have linked list of heaps now... go forth and scan!

Presenter Notes

Standard Handles

Streams are special

  • StdIn,StdOut,StdErr, Serial, etc.

Windows calls these Standard Handles, but function like File Descriptors do in *unix land

Attackers want control of handles for backdoors

  • Telnet, cmd, netcat, etc.

Communications channels

  • Stdin = 0x3
  • Stdout = 0x7
  • StdErr = 0xb

Presenter Notes

Standard Handles

If a PID had weird handles for In,Out,Err

  • Investigate further...
  • What is the device the handle is mapped to?
  • Is it a named pipe or network socket?

Presenter Notes

Dynamic Link Libraries (DLLs)

Code and resources that can be shared between processes.

Run inside a host process...

  • Access to all a process's resources!

Loaded by

  • Dependencies (DependancyWalker.exe)
  • Dyanmic Linking (Import Address Table, IAT, in PE)
  • Runtime linking (LoadLibrary. No IAT)
  • Code injection

Presenter Notes

DLLs

Follow one of the three linked lists in the PEB for DLLs

Can unlink from the lists as PEB is in process space.

No need for kernel level module!

Still referenced in the VAD

Presenter Notes

How DLL Unlinking Works

dllunlink

Presenter Notes

DllList

Volatility plugin to find DLLs

Walks the LoadOrder list

  • Wants to not detect hidden DLLs

If LoadCount is 0xffff (-1) then DLL loaded in IAT

If LoadCount != 0xffff, it was loaded by LoadLibrary

Not necessarily suspicious...

  -o OFFSET, --offset=OFFSET
                    EPROCESS offset (in hex) in the physical address space
  -p , --pid=     Operate on these Process IDs (comma-separated)
  -n NAME, --name=NAME  Operate on these process names (regex)

Presenter Notes

DllList

[root&windows]#volatility -f Win7.bin --profile=Win7SP0x86 -p 352 dlllist
Volatility Foundation Volatility Framework 2.4
************************************************************************
explorer.exe pid:    352
Command line : C:\Windows\Explorer.EXE
Service Pack 1

Base             Size  LoadCount Path
---------- ---------- ---------- ----
0x00990000   0x281000     0xffff C:\Windows\Explorer.EXE
0x775c0000   0x13c000     0xffff C:\Windows\SYSTEM32\ntdll.dll
0x76dc0000    0xd4000     0xffff C:\Windows\system32\kernel32.dll
0x75820000    0x4b000     0xffff C:\Windows\system32\KERNELBASE.dll
0x77750000    0xa0000     0xffff C:\Windows\system32\ADVAPI32.dll
0x76f40000    0xac000     0xffff C:\Windows\system32\msvcrt.dll
0x77700000    0x19000     0xffff C:\Windows\SYSTEM32\sechost.dll
0x75970000    0xa2000     0xffff C:\Windows\system32\RPCRT4.dll
0x75d10000    0x4e000     0xffff C:\Windows\system32\GDI32.dll
0x77040000    0xc9000     0xffff C:\Windows\system32\USER32.dll
0x75960000     0xa000     0xffff C:\Windows\system32\LPK.dll
0x76ea0000    0x9d000     0xffff C:\Windows\system32\USP10.dll
0x772b0000    0x57000     0xffff C:\Windows\system32\SHLWAPI.dll
0x760a0000   0xc4a000     0xffff C:\Windows\system32\SHELL32.dll
0x75bb0000   0x15c000     0xffff C:\Windows\system32\ole32.dll

Presenter Notes

DLL Detection if Unlinked

PE File Scanning

  • DLLs still have a PE header...
  • DLL Flag Present

VAD

  • VAD contains full paths to disk for files mapped
  • DLL could have been memory injected so no disk reference

Presenter Notes

ldrmodules

Plugin to find DLLs that are hidden by going through all LDR lists and executable VAD nodes.

Scans the VAD nodes first

Cross references with PEB LDR lists

-o OFFSET, --offset=OFFSET
                EPROCESS offset (in hex) in the physical address space
-p , --pid=PID     Operate on these Process IDs (comma-separated)
-n NAME, --name=NAME  Operate on these process names (regex)

Presenter Notes

ldrmodules

[root&windows]#volatility -f Win7.bin --profile=Win7SP0x86 -p 352 ldrmodules
Volatility Foundation Volatility Framework 2.4
Pid      Process              Base       InLoad InInit InMem MappedPath
-------- -------------------- ---------- ------ ------ ----- ----------
 352 explorer.exe         0x6f670000 True   True   True  \Windows\System32\cscui.dll
 352 explorer.exe         0x00990000 True   False  True  \Windows\explorer.exe
 352 explorer.exe         0x73d30000 True   True   True  \Windows\System32\oleacc.dll
 352 explorer.exe         0x73730000 True   True   True  \Windows\System32\msacm32.drv
 352 explorer.exe         0x73f60000 True   True   True  \Windows\System32\wtsapi32.dll
 352 explorer.exe         0x637a0000 False  False  False \Windows\System32\imageres.dll
 352 explorer.exe         0x6adb0000 True   True   True  \Windows\System32\WWanAPI.dll
 352 explorer.exe         0x709d0000 True   True   True  \Windows\System32\PortableDeviceApi.dll
 352 explorer.exe         0x6afe0000 True   True   True  \Windows\System32\QUTIL.DLL
 352 explorer.exe         0x075c0000 False  False  False \Windows\System32\imageres.dll
 352 explorer.exe         0x71210000 True   True   True  \Windows\System32\mpr.dll
 352 explorer.exe         0x63380000 True   True   True  \Windows\System32\acppage.dll
 352 explorer.exe         0x75820000 True   True   True  \Windows\System32\KernelBase.dll
 352 explorer.exe         0x6ae30000 True   True   True  \Windows\System32\wwapi.dll
 352 explorer.exe         0x63440000 True   True   True  \Windows\System32\StructuredQuery.dll
 352 explorer.exe         0x73a50000 True   True   True  \Windows\System32\ksuser.dll
 352 explorer.exe         0x75670000 True   True   True  \Windows\System32\msasn1.dll
 352 explorer.exe         0x74670000 True   True   True  \Windows\System32\authui.dll
 352 explorer.exe         0x6b290000 True   True   True  \Windows\System32\netshell.dll
 352 explorer.exe         0x76ff0000 True   True   True  \Windows\System32\Wldap32.dll
 352 explorer.exe         0x754c0000 True   True   True  \Windows\System32\secur32.dll
 352 explorer.exe         0x73ad0000 True   True   True  \Windows\System32\ntmarta.dll
 352 explorer.exe         0x686a0000 True   True   True  \Windows\System32\FXSRESM.dll
 352 explorer.exe         0x740e0000 True   True   True  \Windows\System32\dwmapi.dll
 352 explorer.exe         0x6ad00000 True   True   True  \Windows\System32\srchadmin.dll
 352 explorer.exe         0x77310000 True   True   True  \Windows\System32\wininet.dll
 352 explorer.exe         0x75920000 True   True   True  \Windows\System32\cfgmgr32.dll
 352 explorer.exe         0x73f30000 True   True   True  \Windows\System32\api-ms-win-downlevel-shell32-l1-1-0.dll
 352 explorer.exe         0x73a60000 True   True   True  \Windows\System32\wdmaud.drv
 352 explorer.exe         0x6ad80000 True   True   True  \Windows\System32\QAGENT.DLL
 352 explorer.exe         0x76cf0000 True   True   True  \Windows\System32\msctf.dll
 352 explorer.exe         0x735c0000 True   True   True  \Windows\System32\IPHLPAPI.DLL

Presenter Notes

DLLDump

Plugin to dump a DLL to disk for analysis.

-p PID
-D DUMP_DIR
-u unsafe to bypass checks
-r regex for DLLs in memory
-o OFFSET
-b ImageAddressBase


[root&windows]#volatility -f Win7.bin --profile=Win7SP0x86 -p 352 dlldump -D dumpedDlls/
Volatility Foundation Volatility Framework 2.4
Process(V) Name                 Module Base Module Name          Result
---------- -------------------- ----------- -------------------- ------
0x8625b420 explorer.exe         0x000990000 Explorer.EXE         OK: module.352.3dc5b420.990000.dll
0x8625b420 explorer.exe         0x0775c0000 ntdll.dll            OK: module.352.3dc5b420.775c0000.dll
0x8625b420 explorer.exe         0x073d30000 OLEACC.dll           OK: module.352.3dc5b420.73d30000.dll
0x8625b420 explorer.exe         0x0748b0000 SAMLIB.dll           OK: module.352.3dc5b420.748b0000.dll
0x8625b420 explorer.exe         0x073f60000 WTSAPI32.dll         OK: module.352.3dc5b420.73f60000.dll
0x8625b420 explorer.exe         0x0687a0000 FXSAPI.dll           OK: module.352.3dc5b420.687a0000.dll
0x8625b420 explorer.exe         0x06adb0000 wwanapi.dll          OK: module.352.3dc5b420.6adb0000.dll
0x8625b420 explorer.exe         0x070a60000 sfc_os.DLL           OK: module.352.3dc5b420.70a60000.dll
0x8625b420 explorer.exe         0x0709d0000 PortableD...eApi.dll OK: module.352.3dc5b420.709d0000.dll

Presenter Notes

PE In Memory

PE executables also live in memory and can be carved

Remember DLLs, Exe and drivers follow PE struct

Not all PE sections are loaded in memory

Self-modifying code

Packed on disk → unpacked in memory

Presenter Notes

In Memory

Can use Volshell to parse PE header for you

Get base address of process → EPROCESS → PEB → ImageBaseAddress

Can display structures inline with a memory address using volshell

dt(“_IMAGE_DOS_HEADER”, 0xADDRESS)

Presenter Notes

Volatility

DllDump

  • Carves DLL out of memory

Procdump

  • Carves an executable out of memory.

Moddump

  • Carves a kernel loaded module out of memory

Can request slack space between sections in output file with –memory.

  • Recall pages are on a 4,096KB boundary and PE sections might not be.

Presenter Notes

Packing PE Files

Common method to obfuscate a PE to make analysis harder by preventing static analysis

Removes IAT

Compresses strings

Compresses sections into raw data

Could encrypt data

A new section is added to PE that has the unpacking stub

  • UPX uses .UPX

Presenter Notes

Other Notes

PE file can be stripped in memory as once loaded Windows no longer cares

Work has been done to have loader process heavily stripped PE header.

PE sections can be paged out of memory.

IAT needs to be reconstructed.

Not necessarily malicious...

Presenter Notes

Original Entry Point (OEP)

Normal PE files have entry point at the “main”.

Packed PE have entry point in the unpacking stub.

After PE goes through decryption routine the PE header is fixed up in memory and the stub jumps pack to the OEP to execute original binary.

Presenter Notes

packer

Presenter Notes

Detecting Packed Binaries

Non-standard entry point

Weird section names

UPX and no .text/.code with any information in it

Writable and Executable memory sections

Size on disk > size in memory

Few imports or Strings

Imports only GetProcAddress and LoadLibrary from Kernel32.

PeiD contains signatures of known packers

  • YARA can use these
  • RDG Packer detects some packers better

Presenter Notes

BUT

Packed binaries are only really a problem on disk

Can dump memory and binary is unpacked

  • Some packers do not unpack the whole binary at load time. . .

Find the section jump in debugger and dump executable after stub runs

  • Typically called a tail jump
  • Anti-debugging/Anti-reversing is a hurdle.
  • Import Address Table is not reconstructed

Presenter Notes

Detecting packing on sizes

Size on disk > virtual size in memory for sections

unpacked

c:\bin>peparser.py -f ssdeep.exe -a
[IMAGE_SECTION_HEADER]
0x1A0      0x0   Name:                          .data
0x1A8      0x8   Misc:                          0x6334
0x1A8      0x8   Misc_PhysicalAddress:          0x6334
0x1A8      0x8   Misc_VirtualSize:              0x6334
0x1AC      0xC   VirtualAddress:                0x79000
0x1B0      0x10  SizeOfRawData:                 0x6400
0x1B4      0x14  PointerToRawData:              0x77E00
[IMAGE_SECTION_HEADER]
0x1C8      0x0   Name:                          .rdata
0x1D0      0x8   Misc:                          0xA208
0x1D0      0x8   Misc_PhysicalAddress:          0xA208
0x1D0      0x8   Misc_VirtualSize:              0xA208
0x1D4      0xC   VirtualAddress:                0x80000
0x1D8      0x10  SizeOfRawData:                 0xA400
0x1DC      0x14  PointerToRawData:              0x7E200

Presenter Notes

Detecting packing on sizes

Packed

c:\bin>upx.exe ssdeep.exe -o ssdeepPacked.exe   
        File size         Ratio      Format      Name
   --------------------   ------   -----------   -----------
    563712 ->    165376   29.34%    win32/pe     ssdeepPacked.exe   
Packed 1 file.

c:\bin>peparser.py -f ssdeepPacked.exe -a
----------PE Sections----------
[IMAGE_SECTION_HEADER]
0x178      0x0   Name:                          UPX0
0x180      0x8   Misc:                          0x68000
0x180      0x8   Misc_PhysicalAddress:          0x68000
0x180      0x8   Misc_VirtualSize:              0x68000
0x184      0xC   VirtualAddress:                0x1000
0x188      0x10  SizeOfRawData:                 0x0
0x18C      0x14  PointerToRawData:              0x200

[IMAGE_SECTION_HEADER]
0x1A0      0x0   Name:                          UPX1
0x1A8      0x8   Misc:                          0x29000
0x1A8      0x8   Misc_PhysicalAddress:          0x29000
0x1A8      0x8   Misc_VirtualSize:              0x29000
0x1AC      0xC   VirtualAddress:                0x69000
0x1B0      0x10  SizeOfRawData:                 0x28200
0x1B4      0x14  PointerToRawData:              0x200


[IMAGE_SECTION_HEADER]
0x1C8      0x0   Name:                          UPX2
0x1D0      0x8   Misc:                          0x1000
0x1D0      0x8   Misc_PhysicalAddress:          0x1000
0x1D0      0x8   Misc_VirtualSize:              0x1000
0x1D4      0xC   VirtualAddress:                0x92000
0x1D8      0x10  SizeOfRawData:                 0x200
0x1DC      0x14  PointerToRawData:              0x28400

Presenter Notes

PEiD

ssdeepun

ssdeepPacked

Presenter Notes

Imports

Unpacked

c:\bin>peparser.py -f ssdeep.exe -i 
----------Imported dll's----------
KERNEL32.dll
        0x48c2e0 CloseHandle
        0x48c2e4 CreateSemaphoreA
        0x48c2e8 DeleteCriticalSection
        0x48c2ec EnterCriticalSection
        0x48c2f0 FindClose
        0x48c2f4 FindFirstFileW
        0x48c2f8 FindNextFileW
        0x48c2fc GetCommandLineW
        0x48c300 GetCurrentProcess
        0x48c304 GetCurrentProcessId
        0x48c308 GetCurrentThreadId
        0x48c30c GetLastError
        0x48c310 GetModuleFileNameW
        0x48c314 GetModuleHandleA
        0x48c318 GetModuleHandleW
        0x48c31c GetProcAddress
        0x48c320 GetStartupInfoA
        0x48c324 GetSystemTimeAsFileTime
        0x48c328 GetTickCount
        0x48c32c InitializeCriticalSection
        0x48c330 IsDBCSLeadByteEx
        0x48c334 LeaveCriticalSection
        0x48c338 MultiByteToWideChar
        0x48c33c QueryPerformanceCounter
        0x48c340 ReleaseSemaphore
        0x48c344 SetLastError
        0x48c348 SetUnhandledExceptionFilter
        0x48c34c Sleep
        0x48c350 TerminateProcess
        0x48c354 TlsAlloc
        0x48c358 TlsFree
        0x48c35c TlsGetValue
        0x48c360 TlsSetValue
        0x48c364 UnhandledExceptionFilter
        0x48c368 VirtualProtect
        0x48c36c VirtualQuery
        0x48c370 WaitForSingleObject
        0x48c374 WideCharToMultiByte
msvcrt.dll
        0x48c37c __argv
        0x48c380 __dllonexit
        0x48c384 __doserrno
        0x48c388 __getmainargs
        0x48c38c __initenv
        0x48c390 __lconv_init
        0x48c394 __mb_cur_max
        0x48c398 __pioinfo
        0x48c39c __set_app_type
        0x48c3a0 __setusermatherr
        0x48c3a4 _acmdln
        0x48c3a8 _amsg_exit
        0x48c3ac _cexit
        0x48c3b0 _errno
        0x48c3b4 _exit
        0x48c3b8 _filelengthi64
        0x48c3bc _fileno
        0x48c3c0 _fmode
        0x48c3c4 _fstat64
        0x48c3c8 _initterm
        0x48c3cc _iob
        0x48c3d0 _lock
        0x48c3d4 _lseeki64
        0x48c3d8 _onexit
        0x48c3dc _snwprintf
        0x48c3e0 _strnicmp
        0x48c3e4 atol
        0x48c3e8 calloc
        0x48c3ec exit
        0x48c3f0 fclose
        0x48c3f4 feof
        0x48c3f8 ferror
        0x48c3fc fflush
        0x48c400 fgetpos

Presenter Notes

Imports

Packed

c:\bin>peparser.py -f ssdeepPacked.exe -i
----------Imported dll's----------
KERNEL32.DLL
        0x492064 LoadLibraryA
        0x492068 GetProcAddress
        0x49206c VirtualProtect
        0x492070 VirtualAlloc
        0x492074 VirtualFree
        0x492078 ExitProcess
msvcrt.dll
        0x492080 _iob
SHELL32.DLL
        0x492088 CommandLineToArgvW
USER32.dll
        0x492090 MessageBoxW

Presenter Notes

peparser is a small wrapper on pefile.py

ProcDump

Dump a process to an executable file sample

-o OFFSET, --offset=OFFSET
                EPROCESS offset (in hex) in the physical address space
-p 352, --pid=PID     Operate on these Process IDs (comma-separated)
-n NAME, --name=NAME  Operate on these process names (regex)
-D DUMP_DIR, --dump-dir=DUMP_DIR
                Directory in which to dump executable files
-u, --unsafe          Bypasses certain sanity checks when creating image
-m, --memory          Carve as a memory sample rather than exe/disk
-x, --fix             Modify the image base of the dump to the im-memory
                base address


[root&windows]#volatility -f Win7.bin --profile=Win7SP0x86 -p 352 procdump -D .
Volatility Foundation Volatility Framework 2.4
Process(V) ImageBase  Name                 Result
---------- ---------- -------------------- ------
0x8625b420 0x00990000 explorer.exe         OK: executable.352.exe

Presenter Notes

Code Injection

Common practice with malware and exploitation

Remote DLL injection

  • Process forces another to load a DLL from disk

Remote code injection

  • Process writes code into another process and forces execution

Reflective DLL injection

  • Process writes a DLL into remote process space and it loads itself from a specific loader stub

Hollow process injection

  • Process is started as suspended and memory space is blotted over with other code

Presenter Notes

Remote DLL Injection

Loaded Library is used

Registers in PEB.LDR if not unlinked.

from ctypes import *
import sys
kernel32 = windll.kernel32  
#PROCESS_CREATE_THREAD |  PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION |  PROCESS_VM_WRITE | PROCESS_VM_READ
PROCESS_ACCESS  = ( 0x0080 | 0x0400 | 0x0008 |  0x0020 | 0x0010 ) 
PROCESS_ACCESS = ( 0x00F0000 | 0x00100000 | 0xFFF )
#  MEM_COMMIT | MEM_RESERVE
MEMORY  = ( 0x1000 | 0x2000 )
#PAGE_EXECUTE_READWRITE
PAGE_EXECUTE_READWRITE = 0x04
pid = sys.argv[1]
dll_path = sys.argv[2]
print "Going to inject into %s with %s" %(pid, dll_path)
#Step 1: Open a handle to a process
handleToProcess = kernel32.OpenProcess(PROCESS_ACCESS, False, int(pid))
#Step 2: allocate memory for the process (Just enough for the PATH of the dll you want to load into it)
dll_length = len(dll_path)
#2.1 allocate space for the dll_path in the process
virtualAllocated = kernel32.VirtualAllocEx(handleToProcess, 0, dll_length, MEMORY, PAGE_EXECUTE_READWRITE)
#Step 3: Find location of LoadLibrary and write memory into remote process
null = c_int(0)
kernel32.WriteProcessMemory(handleToProcess, virtualAllocated, dll_path, dll_length, byref(null))
handle = kernel32.GetModuleHandleA("kernel32.dll")
loadedDll = kernel32.GetProcAddress(handle, "LoadLibraryA")
#Step 4: Run LoadLibraryA on remote target pointing to our DLL!
id = c_ulong(0)
if kernel32.CreateRemoteThread(handleToProcess, None, 0, loadedDll, virtualAllocated, 0, byref(id)):
print "injected!"

Presenter Notes

Hollow Process Injection

Stuxnet used this on lsass

Create a process suspended

Free memory of original executable .code and insert malicious code sections.

Resume the process.

https://www.trustwave.com/Resources/SpiderLabs-Blog/Analyzing-Malware-Hollow-Processes/

Presenter Notes

HollowProcess

Presenter Notes

Hollow Process Injection

Uses undocumented Nt functions to unmap sections from memory

typedef NTSTATUS(__stdcall* pNtUnmapViewOfSection)(HANDLE ProcessHandle, PVOID BaseAddress);

Parses though the PE header of two files.. the replacer and reaplcee

  1. Create a process in a suspended state
  2. Unmap sections that overlap and the image base
  3. Virtual alloc memory into target process at replacers image base and size of image
  4. Write the PE header into the target process of replacer
  5. Go through each section and write it into target
  6. Get the thread context of target and set eax to the imageBase+AddressOfEntryPoint
  7. Resume the main thread, now holding the replacement processes code

Presenter Notes

Detecting Hollow Injection

RWX memory

  • Unless malware author is cute
  • File size of process differs

Fuzzy hashing

  • Commonality between files
  • Ssdeep

Presenter Notes

Fuzzy Hashing

Common in malware research

Used as indicator of similarities in files

Higher hash number = more similarities

ssdeep is open source freeware for fuzzy hashing by Jesse Kornblum

Great read

Presenter Notes

Ssdeep

Usage: ssdeep [-m file] [-k file] [-dpgvrsblcxa] [-t val] [-h|-V] [FILES]
-m - Match FILES against known hashes in file
-k - Match signatures in FILES against signatures in file
-d - Directory mode, compare all files in a directory
-p - Pretty matching mode. Similar to -d but includes all matches
-g - Cluster matches together
-v - Verbose mode. Displays filename as its being processed
-r - Recursive mode
-s - Silent mode; all errors are supressed
-b - Uses only the bare name of files; all path information omitted
-l - Uses relative paths for filenames
-c - Prints output in CSV format
-x - Compare FILES as signature files
-a - Display all matches, regardless of score
-t - Only displays matches above the given threshold
-h - Display this help message
-V - Display version number and exit

c:\bin>ssdeep.exe -d reg.pdf mal.pdf
mal.pdf matches c:\bin\reg.pdf (99)

Presenter Notes

Readable, Writable, Executable

Injected code typically has page permissions of readable, writable and executable (rwx).

Pages must be readable and executable for the CPU to run code, hence why .text/.code is rx.

If a page is wx, attacker can write into memory and execute arbitrary code.

Presenter Notes

Changing Page Permissions

Recall from the remote DLL injection we used VirtualAllocEX on memory to make it PAGE_EXECUTE_READWRITE.

After injection Attackers clean up and call VirtualProtectEx to make page rx

BOOL WINAPI VirtualProtectEx(
  _In_   HANDLE hProcess,
  _In_   LPVOID lpAddress,
  _In_   SIZE_T dwSize,
  _In_   DWORD flNewProtect,
  _Out_  PDWORD lpflOldProtect
);

Do not always rely on rwx for injected code

Presenter Notes

Advanced Authors

Never make page rwx

Start with PAGE_READWRITE and put code into memory

Change page to PAGE_EXECUTE_READ after writing

Now there are no RWX pages every allocated.

  • RW when copying data
  • RX when executing

Presenter Notes

Malfind

Volatility plugin to find injected code.

Scans for RWX private memory regions

Some false positives...

  • Analyze disassembly output

Use VAD plugins to cross reference findings.

Useful to find signatures to write Yara rules on!

-D to dump sections to disk.

Presenter Notes

Impscan

Scan for calls to imported functions

Useful with addresses from Malfind

IAT might not be reconstructed when carved out of memory

  • -b base address from malfind

If not, scans main module of process

  • -p PID

Can output new IAT as an idc file to insert into IDA.

  • --output=Module
    • Module Output Options: idc, text

Presenter Notes

Usage

0x863cc540 ProcessHacker.         PID = 1108
[root&windows]#volatility -f Win7.bin --profile=Win7SP0x86 impscan -p 1108
Volatility Foundation Volatility Framework 2.4
IAT        Call       Module               Function
---------- ---------- -------------------- --------
0x012d9000 0x77764251 ADVAPI32.dll         LsaLookupPrivilegeValue
0x012d9004 0x7779a469 ADVAPI32.dll         LsaEnumerateAccounts
0x012d9008 0x7775c7a6 ADVAPI32.dll         SetServiceStatus
0x012d9010 0x7775a965 ADVAPI32.dll         StartServiceCtrlDispatcherW
0x012d9014 0x777930f8 ADVAPI32.dll         ChangeServiceConfigW
0x012d9018 0x77798819 ADVAPI32.dll         LsaAddAccountRights
0x012d901c 0x7775b466 ADVAPI32.dll         EnumServicesStatusExW
0x012d9020 0x7775b537 ADVAPI32.dll         QueryServiceConfigW
0x012d9024 0x777930d8 ADVAPI32.dll         ChangeServiceConfig2W
0x012d9028 0x7777712c ADVAPI32.dll         CreateServiceW
0x012d902c 0x7776369c ADVAPI32.dll         CloseServiceHandle
0x012d9030 0x7777715c ADVAPI32.dll         DeleteService
0x012d9034 0x7775ca64 ADVAPI32.dll         OpenSCManagerW
0x012d9038 0x7775ca4c ADVAPI32.dll         OpenServiceW
0x012d903c 0x77757974 ADVAPI32.dll         StartServiceW
0x012d9040 0x77777144 ADVAPI32.dll         ControlService
0x012d9044 0x777793dc ADVAPI32.dll         LsaLookupSids
0x012d9048 0x7777077c ADVAPI32.dll         LsaOpenPolicy
0x012d904c 0x777933f9 ADVAPI32.dll         QueryServiceConfig2W
0x012d9050 0x77799e99 ADVAPI32.dll         LsaLookupPrivilegeDisplayName
0x012d9054 0x77777cdc ADVAPI32.dll         LsaLookupNames2
0x012d9058 0x77771af7 ADVAPI32.dll         LsaClose
0x012d905c 0x77799df1 ADVAPI32.dll         LsaLookupPrivilegeName
0x012d9060 0x7776ede1 ADVAPI32.dll         LsaFreeMemory
0x012d9078 0x7775c592 ADVAPI32.dll         CreateProcessAsUserW
0x012d9088 0x744f09ce COMCTL32.dll         InitCommonControlsEx
0x012d908c 0x74512607 COMCTL32.dll         CreatePropertySheetPageW
0x012d9090 0x7451388e COMCTL32.dll         PropertySheetW
0x012d9098 0x744e3c75 COMCTL32.dll         ImageList_Create
0x012d909c 0x745246d0 COMCTL32.dll         ImageList_Replace
0x012d90ac 0x75d9a36e COMDLG32.dll         GetSaveFileNameW
0x012d90b0 0x75d9a2d5 COMDLG32.dll         GetOpenFileNameW
0x012d90b4 0x75d90d68 COMDLG32.dll         ChooseColorW
0x012d90c0 0x75d1cff1 GDI32.dll            SetDCBrushColor
0x012d90c4 0x75d15f14 GDI32.dll            DeleteObject
0x012d90c8 0x75d205cf GDI32.dll            Polyline
0x012d90cc 0x75d183f2 GDI32.dll            GdiAlphaBlend
0x012d90d0 0x75d16888 GDI32.dll            CreateCompatibleDC
0x012d90d4 0x75d169b1 GDI32.dll            SetBkMode
0x012d90d8 0x75d18850 GDI32.dll            CreateDIBSection
0x012d90dc 0x75d1fb87 GDI32.dll            Polygon
0x012d90e0 0x75d16eaa GDI32.dll            DeleteDC
0x012d90e4 0x75d16906 GDI32.dll            SetTextColor
0x012d90e8 0x75d1b4b5 GDI32.dll            GetTextExtentPoint32W
0x012d90ec 0x75d172c0 GDI32.dll            BitBlt
0x012d90f8 0x75d1c204 GDI32.dll            CreateFontW
0x012d90fc 0x75d16640 GDI32.dll            SelectObject
0x012d9104 0x75d1a23b GDI32.dll            GetDIBits
0x012d9108 0x75d1a67b GDI32.dll            RestoreDC
0x012d910c 0x75d17dfe GDI32.dll            IntersectClipRect
0x012d9110 0x75d1633b GDI32.dll            CreateRectRgn
0x012d9114 0x75d1a74b GDI32.dll            SaveDC
0x012d9118 0x75d1651e GDI32.dll            CombineRgn
0x012d9120 0x75d19218 GDI32.dll            ExcludeClipRect
0x012d9124 0x75d1abfc GDI32.dll            CreateFontIndirectW
0x012d9128 0x75d17b8f GDI32.dll            GetTextMetricsW
0x012d912c 0x75d17f2d GDI32.dll            GetClipRgn
0x012d9130 0x75d17568 GDI32.dll            GetObjectW
0x012d9134 0x75d16f7f GDI32.dll            GetDeviceCaps
0x012d9138 0x75d1f1ff GDI32.dll            Rectangle
0x012d913c 0x75d310c0 GDI32.dll            SetDCPenColor
0x012d9140 0x75d15ddf GDI32.dll            GetStockObject
0x012d9144 0x75d173ad GDI32.dll            CreateCompatibleBitmap
0x012d9148 0x75d17242 GDI32.dll            SelectClipRgn
0x012d9150 0x76e1527c kernel32.dll         LCMapStringW
0x012d9154 0x76e20641 kernel32.dll         UnhandledExceptionFilter
0x012d9158 0x76e0f4eb kernel32.dll         SetUnhandledExceptionFilter
0x012d915c 0x76e0d790 kernel32.dll         GetCurrentProcess
---SNIP---

Presenter Notes

EOF

Presenter Notes