06-27-2017: "Amazon.com – Your Cancellation" Spam Leads to Scareware & Weight Loss Scam

Source: Email spam
Date:  June 27, 2017
Subject: Amazon.com – Your Cancellation 173-222723-2163799 (ref. **)
From: “order-update@amazon[.]com” (ref. *)

Goal: Review the email infection/redirection chain leading to scareware on IE
Background: Previously, the same campaign led to the weigh loss spam.
Tools: Fiddler, any JS debugger

Obfuscated redirection chain to scareware/weight loss spam is as follows:

  1. “Amazon.com – Your Cancellation” email href link
  2. hxxp://www[.]cuinavo[.]com/maritime[.]php
  3. hxxp://bestdiet[.]world/?a=401336&c=cpcdiet&s=4220620174
  4. hxxp://moneybetinc[.]com/d/r6t0b27039?rtb=c2da1390dbacd52002e62d397bb5e4f7[.]0&h=0[.]23&rtc=101890_697e696c2343d7da35a0871e91b02e37_ef9aeab99e7822b8f14ddb4f4fa8bd2f1498533889[.]1375_175&subid=NDAxMzM2LU5ESXlNRFl5TURFM05BPT0%3D
  5. hxxp://blobar[.]org/d/r6t0b27039?k=25a6755c0c62719e2d64bcb003637769[.]1498533321[.]628[.]1&rtb=c2da1390dbacd52002e62d397bb5e4f7[.]0&h=0[.]23&rtc=101890_697e696c2343d7da35a0871e91b02e37_ef9aeab99e7822b8f14ddb4f4fa8bd2f1498533889[.]1375_175&subid=NDAxMzM2LU5ESXlNRFl5TURFM05BPT0%3D&r=&z=240

Scareware I:

hxxp://sjoiadiiwdj32892378310[.]xyz/errorinwindowsfound404errorvirus 

Scareware II: 

hxxp://www[.]microsoft-user-alert[.]xyz/microsoft-alert-call-for-support-1-855-633-1666

Scareware III.

hxxp://errorsporttollfree9[.]xyz/microsoftAlert

Weight loss scam IV: 

hxxp://bestdiet.world/us/xxrr/cla-safflower-oil/?bhu=8mcwpko8zespkyV8J8QiBqm51VGT46J9C

Analysis:

I. “Amazon.com – Your Cancellation” email href link leads to the following website:
  • hxxp://www[.]cuinavo[.]com/maritime[.]php

II. Retrieve the code via curl > code.html, paste the JavaScript function into the JS debugger.
Comment out setTimeout and add “alert” on the function schoole() and observer the next redirect to the following website:
  • hxxp://bestdiet[.]world/?a=401336&c=cpcdiet&s=4220620174
IIII. Launch Fiddler and track the redirection chain to scareware

Run 1:
Run 2:
Run 3:
IV. Observe the landing page leading to scareware popup.

Run 1:


Run 2:
Run 3:

Malicious domain blocklist:
  1. hxxp://www[.]cuinavo[.]com/maritime[.]php
  2. hxxp://bestdiet[.]world/?a=401336&c=cpcdiet&s=4220620174
  3. hxxp://moneybetinc[.]com/d/r6t0b27039?rtb=c2da1390dbacd52002e62d397bb5e4f7[.]0&h=0[.]23&rtc=101890_697e696c2343d7da35a0871e91b02e37_ef9aeab99e7822b8f14ddb4f4fa8bd2f1498533889[.]1375_175&subid=NDAxMzM2LU5ESXlNRFl5TURFM05BPT0%3D
  4. hxxp://blobar[.]org/d/r6t0b27039?k=25a6755c0c62719e2d64bcb003637769[.]1498533321[.]628[.]1&rtb=c2da1390dbacd52002e62d397bb5e4f7[.]0&h=0[.]23&rtc=101890_697e696c2343d7da35a0871e91b02e37_ef9aeab99e7822b8f14ddb4f4fa8bd2f1498533889[.]1375_175&subid=NDAxMzM2LU5ESXlNRFl5TURFM05BPT0%3D&r=&z=240

Scareware I:

hxxp://sjoiadiiwdj32892378310[.]xyz/errorinwindowsfound404errorvirus 

Scareware II: 

hxxp://www[.]microsoft-user-alert[.]xyz/microsoft-alert-call-for-support-1-855-633-1666

Scareware III.

hxxp://errorsporttollfree9[.]xyz/microsoftAlert

Weight loss scam IV: 

hxxp://bestdiet.world/us/xxrr/cla-safflower-oil/?bhu=8mcwpko8zespkyV8J8QiBqm51VGT46J9C

Spam originating IP*

180[.]250[.]153[.]197 (DomainTools)

inetnum:        180.250.128.0 – 180.250.159.255netname:        TLKM_D3D4_ASTINET_180_CUSTOMERcountry:        IDdescr:          PT TELKOM INDONESIAdescr:          Menara Multimedia Lt. 7descr:          Jl. Kebonsirih No.12descr:          JAKARTAadmin-c:        AR165-APtech-c:         HM444-APstatus:         ASSIGNED NON-PORTABLEmnt-by:         MAINT-TELKOMNET


Email headers (defanged)**:

Authentication-Results: spf=softfail (sender IP is 180[.]250[.]153[.]197)
 smtp.mailfrom=unitedwaylane.org; hotmail.com; dkim=none (message not signed)
 header.d=none;hotmail.com; dmarc=fail action=quarantine
 header.from=amazon[.]com;
Received-SPF: SoftFail (protection[.]outlook[.]com: domain of transitioning
 unitedwaylane.org discourages use of 180[.]250[.]153[.]197 as permitted sender)
X-IncomingTopHeaderMarker: OriginalChecksum:62325BB6EE949A25F7137383F5223FB0274314903C8331F43DBB3A9AC69D1140;UpperCasedChecksum:ECDCBA2E3C784D1951EFC14295EED9DC8207A5280F4C245C1B79829DBCE4E91C;SizeAsReceived:1087;Count:19
Received: from localhost ([180[.]250[.]153[.]197]) by BAY004-MC1F55.hotmail.com with Microsoft SMTPSVC(7.5.7601.23143);
 Mon, 26 Jun 2017 02:27:36 -0700
Bristled-Offensively-Uncomputable: premise
Chaotic-Elevators: 891b729f1edbb
Content-Type: text/html; charset=”UTF-8″
From: “order-update@amazon.com”
Content-Transfer-Encoding: 7bit
Bound-Documentaries-Lavishly: 2aaba5abff87f
To: REDACTED
X-AMAZON-MAIL-RELAY-TYPE: notification
Reply-To: “order-update@amazon[.]com”
Bounces-to: a7d24f875448b4c4b5ec283256a1543af0625eaaa589@bounces.amazon.com
Taxonomy-Whitman-Friedrich: 558617B1251C
Message-ID:
Date: Mon, 26 Jun 2017 16:27:36 +0000
X-AMAZON-RTE-VERSION: 2.0
Subject: Amazon.com – Your Cancellation 173-222723-2163799
Return-Path: dbaker@unitedwaylane[.]orgX-OriginalArrivalTime: 26 Jun 2017 09:27:36.0439 (UTC) FILETIME=[729CF070:01D2EE5E]
X-IncomingHeaderCount: 19
X-MS-Exchange-Organization-Network-Message-Id: 089e0edc-2b1d-4a1e-8f14-08d4bc75957e
X-EOPAttributedMessage: 0
X-EOPTenantAttributedMessage: 84df9e7f-e9f6-40af-b435-aaaaaaaaaaaa:0
X-MS-Exchange-Organization-MessageDirectionality: Incoming
CMM-sender-ip: 180[.]250[.]153[.]197CMM-sending-ip: 180[.]250[.]153[.]197CMM-Authentication-Results: hotmail.com; spf=softfail (sender IP is
 180[.]250[.]153[.]197; identity alignment result is fail and alignment mode is
 relaxed) smtp.mailfrom=dbaker@unitedwaylane[.]org; dkim=none (identity
 alignment result is pass and alignment mode is relaxed) header.d=amazon.com;
 x-hmca=none header.id=order-update@amazon.com
CMM-X-SID-PRA: order-update@amazon.com

Domain Blocklist:

  1. hxxp://www[.]cuinavo[.]com/maritime[.]php
  2. hxxp://bestdiet[.]world/?a=401336&c=cpcdiet&s=4220620174
  3. hxxp://moneybetinc[.]com/d/r6t0b27039?rtb=c2da1390dbacd52002e62d397bb5e4f7[.]0&h=0[.]23&rtc=101890_697e696c2343d7da35a0871e91b02e37_ef9aeab99e7822b8f14ddb4f4fa8bd2f1498533889[.]1375_175&subid=NDAxMzM2LU5ESXlNRFl5TURFM05BPT0%3D
  4. hxxp://blobar[.]org/d/r6t0b27039?k=25a6755c0c62719e2d64bcb003637769[.]1498533321[.]628[.]1&rtb=c2da1390dbacd52002e62d397bb5e4f7[.]0&h=0[.]23&rtc=101890_697e696c2343d7da35a0871e91b02e37_ef9aeab99e7822b8f14ddb4f4fa8bd2f1498533889[.]1375_175&subid=NDAxMzM2LU5ESXlNRFl5TURFM05BPT0%3D&r=&z=240

Scareware I:

hxxp://sjoiadiiwdj32892378310[.]xyz/errorinwindowsfound404errorvirus 

Scareware II: 

hxxp://www[.]microsoft-user-alert[.]xyz/microsoft-alert-call-for-support-1-855-633-1666

Scareware III.

hxxp://errorsporttollfree9[.]xyz/microsoftAlert

Weight loss scam IV: 

hxxp://bestdiet.world/us/xxrr/cla-safflower-oil/?bhu=8mcwpko8zespkyV8J8QiBqm51VGT46J9C 

p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica}

Let’s Learn: How to Unpack Locky "Osiris" Ransomware

Goal: Unpack Locky ransomware payload using WriteProcessMemory API buffer’s dump.
Source@tmmalanalyst
Tool: ollyDbg, CFF Explorer

Background
Locky ransomware utilizes a loader/patcher algorithm patching and unloading the decoded payload in memory. Many other malware families use this same exact methodology. 

Theory: 
Locky ransomware patches itself using CreateProcessW API setting the creation flag to CREATE_SUSPENDED and writing itself into the buffer via WriteProcessMemory API. Next, the ransomware process won’t be executed immediately; it does not start until called ResumeThread. So, the ransomware has time to patch in memory.


The Locky payload decoding/patching API calls are as follows:

I. CreateProcessW [ref. *]

  • invoke CreateProcessW, NULL, “C:\Documents and Settings\Administrator\Desktop\osiris[.]exe”, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, 0010D8CC, 0010E354

000FBE30   00942791  /CALL to CreateProcessW from 0094278B
000FBE34   00000000  |ModuleFileName = NULL
000FBE38   0010D6C4  |CommandLine = “”C:\Documents and Settings\Administrator\Desktop\osiris[.]exe””
000FBE3C   00000000  |pProcessSecurity = NULL
000FBE40   00000000  |pThreadSecurity = NULL
000FBE44   00000000  |InheritHandles = FALSE
000FBE48   00000004  |CreationFlags = CREATE_SUSPENDED
000FBE4C   00000000  |pEnvironment = NULL
000FBE50   00000000  |CurrentDir = NULL
000FBE54   0010D8CC  |pStartupInfo = 0010D8CC
000FBE58   0010E354  \pProcessInfo = 0010E354


II. WriteProcessMemory (ref. **)

  • invoke WriteProcessMemory, 00000064, 0x300000, 009A0000, 190, NULL

000FBE44   009428BA  /CALL to WriteProcessMemory from 009428B4
000FBE48   00000064  |hProcess = 00000064 (window)
000FBE4C   00300000  |Address = 0x300000
000FBE50   009A0000  |Buffer = 009A0000
000FBE54   00000190  |BytesToWrite = 190 (400.)
000FBE58   00000000  \pBytesWritten = NULL


III. ResumeThread (ref. ***)

  • invoke ResumeThread, 00000068

000FBE54   00942E81  /CALL to ResumeThread from 00942E7E
000FBE58   00000068  \hThread = 00000068 (window)


Practice:
I. Load Ollydbg and click “File” -> locky.exe
II. Click “Go to” -> “Expression” -> Type “WriteProcessMemory” and set up a breakpoint on it using F2.
III. Run the process using F9 and follow buffer to observe the unpacked Locky in the dump section.

IV.  Then, click on “Backup” -> “Save data to file.”

V. Verify the exported payload and IAT in CFF Explorer. Profit!

Locky extension

.osiris

POST requests:

  • &length=..&failed=..&encrypted=
  • &act=stats&path=
  • &v=2..&x64=..&sp=..&os=…&serv=..&corp=..&lang=..&act=getkey&affid=..
  • &act=gethtml&lang= 
  • ..&act=gettext&lang=..


Registry

  • Software\Microsoft\Windows\CurrentVersion\Run 


Self-kill routine: 

cmd.exe /C del /Q /F

Blacklist

tmp;winnt;Application Data;AppData;Program Files (x86);Program Files;temp;thumbs.db;$Recycle.Bin;System Volume Information;Boot;Windows

Locky instructions: 

/_HELP_instructions.html._HELP_instructions.bmp.._HELP_instructions.txt.._Locky_recover_instructions.bmp._Locky_recover_instructions.txt

Delete shadow copy:

vssadmin.exe Delete Shadows /Quiet /All  

Targeted extensions:

yuv…ycbcra..xis…x3f…x11…wpd…tex…sxg…stx…st8…st5…srw…srf…sr2…sqlitedb..sqlite3…sqlite..sdf…sda…sd0…s3db..rwz…rwl…rdb…rat…raf…qby…qbx…qbw…qbr…qba…py..psafe3..plc…plus_muhd…pdd…p7c…p7b…oth…orf…odm…odf…nyf…nxl…nx2…nwb…ns4…ns3…ns2…nrw…nop…nk2…nef…ndd…myd…mrw…moneywell…mny…mmw…mfw…mef…mdc…lua…kpdx..kdc…kdbx..kc2…jpe…incpas..iiq…ibz…ibank…hbk…gry…grey..gray..fhd…fh..ffd…exf…erf…erbsql..eml…dxg…drf…dng…dgc…des…der…ddrw..ddoc..dcs…dc2…db_journal..csl…csh…crw…craw..cib…ce2…ce1…cdrw..cdr6..cdr5..cdr4..cdr3..bpw…bgt…bdb…bay…bank..backupdb..backup..back..awg…apj…ait…agdl..ads…adb…acr…ach…accdt…accdr…accde…ab4…3pr…3fr…vmxf..vmsd..vhdx..vhd…vbox..stm…st7…rvt…qcow..qed…pif…pdb…pab…ost…ogg…nvram…ndf…m4p…m2ts..log…hpp…hdd…groups..flvv..edb…dit…dat…cmt…bin…aiff..xlk…wad…tlg…st6…st4…say…sas7bdat..qbm…qbb…ptx…pfx…pef…pat…oil…odc…nsh…nsg…nsf…nsd…nd..mos…indd..iif…fpx…fff…fdb…dtd…design..ddd…dcr…dac…cr2…cdx…cdf…blend…bkp…al..adp…act…xlr…xlam..xla…wps…tga…rw2…r3d…pspimage..ps..pct…pcd…m4v…m…fxg…flac..eps…dxb…drw…dot…db3…cpi…cls…cdr…arw…ai..aac…thm…srt…save..safe..rm..pwm…pages…obj…mlb…md..mbx…lit…laccdb..kwm…idx…html..flf…dxf…dwg…dds…csv…css…config..cfg…cer…asx…aspx..aoi…accdb…7zip..1cd…xls…wab…rtf…prf…ppt…oab…msg…mapimail..jnt…doc…dbx…contact…n64…m4a…m4u…m3u…mid…wma…flv…3g2…mkv…3gp…mp4…mov…avi…asf…mpeg..vob…mpg…wmv…fla…swf…wav…mp3…qcow2…vdi…vmdk..vmx…wallet..upk…sav…re4…ltx…litesql…litemod…lbf…iwi…forge…das…d3dbsp..bsa…bik…asset…apk…gpg…aes…ARC…PAQ…tar.bz2…tbk…bak…tar…tgz…gz..7z..rar…zip…djv…djvu..svg…bmp…png…gif…raw…cgm…jpeg..jpg…tif…tiff..NEF…psd…cmd…bat…sh..class…jar…java..rb..asp…cs..brd…sch…dch…dip…pl..vbs…vb..js..h…asm…pas…cpp…c…php…ldf…mdf…ibd…MYI…MYD…frm…odb…dbf…db..mdb…sql…SQLITEDB..SQLITE3…011…010…009…008…007…006…005…004…003…002…001…pst…onetoc2…asc…lay6..lay…ms11(Securitycopy)..ms11..sldm..sldx..ppsm..ppsx..ppam..docb..mml…sxm…otg…odg…uop…potx..pom..pptx..pptm..std…sxd…pot…pps…sti…sxi…otp…odp…wb2…123…wks…wk1…xltx..xltm..xlsx..xlsm..xlsb..slk…xlw…xlt…xlm…xlc…dif…stc…sxc…ots…ods…hwp…602…dotm..dotx..docm..docx..DOT…3dm…max…3ds…xml…txt…CSV…uot…RTF…pdf…XLS…PPT…stw…sxw…ott…odt…DOC…pem…p12…csr…crt…key..wallet.dat..


Reference:

BOOL CreateProcess(
                                   LPCTSTR lpApplicationName, // pointer to name of executable module
                                   LPTSTR lpCommandLine, // pointer to command line string
                                   LPSECURITY_ATTRIBUTES lpProcessAttributes, // pointer to process security attributes
                                   LPSECURITY_ATTRIBUTES lpThreadAttributes, // pointer to thread security attributes
                                   BOOL bInheritHandles, // handle inheritance flag
                                   DWORD dwCreationFlags, // creation flags
                                   LPVOID lpEnvironment, // pointer to new environment block
                                   LPCTSTR lpCurrentDirectory, // pointer to current directory name
                                   LPST
ARTUPINFO lpStartupInfo, // pointer to STARTUPINFO
                                   LPPROCESS_INFORMATION lpProcessInformation // pointer to PROCESS_INFORMATION );


** BOOL WriteProcessMemory(
                                               HANDLE hProcess, // handle to process whose memory is written to
                                               LPVOID lpBaseAddress, // address to start writing to
                                               LPVOID lpBuffer, // pointer to buffer to write data to
                                               DWORD nSize, // number of bytes to write
                                               LPDWORD lpNumberOfBytesWritten // actual number of bytes written );

*** BOOL ResumeThread(
  HANDLE hThread // handle to the thread to be restarted
);

Elasticsearch

Elasticsearch Concept
Goal: Document and annotate some quick notes on learning elasticsearch.

I. CREATING YOUR OWN ANALYZER: SET UP ANALYZER SETTINGS

curl -X PUT "http://localhost:9200/wiki" -d '{
"index" : {
"number_of_shards" : 4,
"number_of_replicas" : 1,
"analysis" : {
"analyzer" : {
"content" : {
"type" : "custom",
"tokenizer" : "standard",
"filter" : ["lowercase", "stop", "kstem"],
"char_filter" : ["html_strip"]
}
}
}
}

}'

II. PUT (CREATE) MAPPING":
CREATE MAPPING (STRING -> TEXT) for INDEX

curl -X PUT "http://localhost:9200/wiki/articles/_mapping" -d '{
"articles" : {
"_all" : { "enabled" : true } ,
"properties" : {
"Title" : { "type" : "text" , "analyzer" : "content" , "include_in_all" : false, "index" : "no" },
"link" : { "type" : "text" , "include_in_all" : false, "index" : "no" },
"Author" : { "type" : "text" , "include_in_all" : false },
"timestamp" : { "type" : "date" , "format" : "dd-MM-yyyy HH:mm:ss", "include_in_all" : false },
"html" : { "type" : "text" , "analyzer" : "content", "include_in_all" : true }
}
}
}'

A. GENERATE JSON OBJECT FOR ELASTICSEARCH

python json_generator.py https://en.wikipedia.org/wiki/France > France.json
'''
# Python module script
/*import urllib2
import json
import sys

link = sys.argv[2]
htmlObj = { "link" : link,
"Author" : "anomymous",
"timestamp" : "12-12-2018 14:16:00",
"Title" : sys.argv[1]
}
response = urllib2.urlopen(link)
htmlObj['html'] = response.read()
print json.dumps(htmlObj, indent=4)
*/
'''

III. XPOST (PUSH) JSON FILE TO ELASTICSEARCH WIKI ARTICLES

curl -XPOST "http://localhost:9200/wiki/articles/" -d @France.json

IV. USING PHRASE QUERY TO SEARCH: SEARCH ELASTICSEARCH INDEX FOR CONTENT

curl -X POST "http://localhost:9200/wiki/_search?pretty" -d '{
"_source" : [
"Title"
],
"query" : {
"query_string": {
"query" : "mobile"
}
}
}'

V. USING THE HIGHLIGHTING FEATURE: SEARCH ELASTICSEARCH INDEX FOR CONTENT (HIGHLIGHTED)

# Query highlighted content
curl -X POST "http://localhost:9200/wiki/_search?pretty" -d '{
"_source" : [
"Title"
],
"query" : {
"query_string": {
"query" : "mobile"
}
}
"highlight" : {
"pre_tags" : [""],
"post_tags" : ["
"],
"fields" : {
"Content" : {}
}
}
}
}'


VI. PAGINATION

curl -X POST "http://localhost:9200/wiki/_search?pretty" -d '{
"from" : 0,
"size" : 10,
"query" : {
"simple_query_string" : {
"query" : "mobile",
"fields" : [
"_all"
]
}
},
"highlight" : {
"fields" : {
"html" : {
"pre_tags" : [
"

"
],
"post_tags" : [
"

"
],
"fragment_size" : 10,
"number_of_fragments" :3
}
}
}
}'

CHAPTER 2: BUILDING YOUR OWN E-COMMERCE SOLUTION

type
String
Integer
Long
Float
Double
Boolean
Date
geo_point
Null
Ipv4

I. CREATE (PUT) INDEX "products"

curl -X PUT "http://localhost:9200/products" -d '{
"index" : {
"number_of_shards" : 1,
"number_of_replicas" : 1
}
}'

II. CREATING MAPPING: Put "product" as the type for "products" index

curl -X PUT "http://localhost:9200/products/product/_mapping" -d '{
"product" : {
"properties" : {
"name" : {
"type" : "text"
},
"description" : {
"type" : "text"
},
"dateOfManufactering" : {
"type" : "date",
"format" : "YYYY-MM-dd"
},
"price" : {
"type" : "long"
},
"productType" : {
"type" : "text",
"include_in_all" : "false",
"index" : "not_analyzed"
},
"totalBuy" : {
"type" : "long",
"include_in_all": "false",
},
"imageURL" : {
"type" : "text",
"include_in_all": "false",
"index" : "no"
},
}
}
}'

Let’s Learn (DIY): Sophisticated Cobalt Strike Gang’s CVE-2017-0199 Loader

Goal: Reverse the first stage loader RTF CVE-2017-0199 loader used by Cobalt Strike gang targeting Russian-speaking financial institutions. This loader’s been seen in conjunction with the Microsoft Word Intruder 8.0.
Source@xdxdxdxdoa
Tool: rtfdump 0.5, ILspy
CVE-2017-0199: Exploit that allows “remote attackers to execute arbitrary code via a crafted document, aka “Microsoft Office/WordPad Remote Code Execution Vulnerability w/Windows API” [source].
Observed unique filename:

  • Пеня по задолженности.doc -> “Debt collection notification.doc” (from Russian to English)
  • Заявление на расторжение договора.doc -> “Application for contract closure.doc” (from Russian to English)

SHA-256: c5d7c5c94468ba74211e08d7c2ad9d0274011d432edc1af8cdf2215b2c9d9291
Type
  • Rich Text Format (CVE-2017-0199 exploit) 
  • Objects OLE embedded (Package)
  • OLE Autolink (Package)

Here are the steps:
  • I. Command: python2.7 rtfdump.py file.rtf


  • II. Command: python2.7 rtfdump.py -f O file.rtf
OLE 1.0 objects embedded within this RTF file with the “-f O” command
  • III. Command: python2.7 rtfdump.py -s 8 file.rtf | more (on the 8 field found in the previous step)
The section 01050000 02000000 indicates an OLE 1.0 object. As the line starts with 9f330500 contains an OLE file.

With option -H, we can convert the hexadecimal characters to binary:

  • IV. Command: python2.7 rtfdump.py -s 8 -H file.rtf 

With option -i, we can obtain more information about the binary (embedded object):
    • V. Command: python2.7 rtfdump.py -s 8 -H -i file.rtf 

    Name: ‘Package\x00’ Position embedded: 00000020 Size embedded: 0005339f md5: a9039264caf3285bf968849bf84ad951 magic: 02007e57

    With option -E, we can extract the embedded object:

    • VI. Command: python2.7 rtfdump.py -s 8 -H -E -d file.rtf > binary.exe

    The payload is written in Microsoft Visual C# / Basic .NET titled “ExecPS.” Using ILspy, we decompile the embedded binary. The embedded binary has a PDF icon and an internal name as “ExecPS[.]exe.”



    Checks for Dr. Web anti-virus process and breaks if they exist.
    • ProcessName = “dwengine” || “spidergate” || “spidernt” | “spideragent”
    Moreover, the embedded binary is digitally signed by “Elektro, OOO” from Nizhni Novgorod, Russia.

    • CN = Elektro, OOO
    • O = Elektro, OOO
    • STREET = d. 13 kv. 11, prospekt Soyuzny
    • L = Nizhni Novgorod
    • S = Nizhegorodskaya oblast
    • PostalCode = 603040
    • C = RU

    p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px ‘Andale Mono’; color: #28fe14; background-color: #000000; background-color: rgba(0, 0, 0, 0.9)} span.s1 {font-variant-ligatures: no-common-ligatures} p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px ‘Andale Mono’; color: #28fe14; background-color: #000000; background-color: rgba(0, 0, 0, 0.9)} span.s1 {font-variant-ligatures: no-common-ligatures} p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px ‘Andale Mono’; color: #28fe14; background-color: #000000; background-color: rgba(0, 0, 0, 0.9)} span.s1 {font-variant-ligatures: no-common-ligatures}

    p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 8.5px Helvetica}

    Let’s Learn: Pushdo Loader Analysis from RIG EK

    Goal: Reverse the Pushdo Trojan, delivered from the RIG Exploit Kit on June 22, 2017.
    Source@Zerophage1337

    Pushdo execution flow:

    Registry persistence: 

    HKCU\Software\Microsoft\Windows\CurrentVersion\Run

    Self-kill routine: 

    :repeat
    del %s
    if exist %s
    goto :repeat
    del %

    Random C2 domains:

    ex-olive[.]com;pb-games[.]com;fink[.]com;stnic[.]co[.]uk;netcr[.]com;findbc[.]com;tyrns[.]com;medius[.]si;ora[.]ecnet[.]jp;c9dd[.]com;sclover3[.]com;spanesi[.]com;fcwcvt[.]org;h-f[.]net;2print[.]com;nunomira[.]com;x0c[.]com;owsports[.]ca;cokocoko[.]com;evcpa[.]com;sjbs[.]org;depalo[.]com;wifi4all[.]nl;abdg[.]com;holleman[.]us;domon[.]com;fe-bauer[.]de;cel-cpa[.]com;alteor[.]cl;ottospm[.]com;transsib[.]com;com-sit[.]com;ka-mo-me[.]com;pr-park[.]com;mqs[.]com[.]br;yoruksut[.]com;rs-ag[.]com;ora-ito[.]com;iamdirt[.]com;wnsavoy[.]com;elpro[.]si;myropcb[.]com;fnw[.]us;photo4b[.]com;koz1[.]net;pupi[.]cz;snugpak[.]com;item-pr[.]com;pdqhomes[.]com;valdal[.]com;mobilnic[.]net;nqks[.]com;quadlock[.]com;waldi[.]pl;abart[.]pl;vexcom[.]com;hummer[.]hu;synetik[.]net;baijaku[.]com;valselit[.]com;crcsi[.]org;udesign[.]biz;credo[.]edu[.]pl;11tochi[.]net;otena[.]com;vitaindu[.]com;edimart[.]hu;olras[.]com;wkhk[.]net;naoi-a[.]com;pohlfood[.]com;jenco[.]co[.]uk;pcgrate[.]com;petsfan[.]com;tc17[.]com;vazir[.]se;aevga[.]com;lrsuk[.]com;xaicom[.]es;pwd[.]org;nelipak[.]nl;speelhal[.]net;dgmna[.]com;ftchat[.]com;tvtools[.]fi;gpthink[.]com;maktraxx[.]com;kernsafe[.]com;jacomfg[.]com;dayvo[.]com;reglera[.]com;yocinc[.]org;jchysk[.]com;railbook[.]net;yumgiskor[.]kz;t-tre[.]com;fnsds[.]org;stajum[.]com;medisa[.]info;jroy[.]net

    06-21-2017 Locky Ransomware: Config Analysis

    Sourcehttps://www.virustotal.com/en/file/b546fad0209bbf800c11565c4720fdb2685966242d2ff162f7be556dd037a6a1/analysis/
    Confighttps://github.com/vkremez/MalwareConfigurations/blob/master/crime_win32_locky_conf_June21-2017.txt


    Locky extension

    .loptr

    POST requests:

    • &length=..&failed=..&encrypted=
    • &act=stats&path=
    • &v=2..&x64=..&sp=..&os=…&serv=..&corp=..&lang=..&act=getkey&affid=..
    • &act=gethtml&lang=..&act=gettext&lang=..

    Registry

    • Software\Microsoft\Windows\CurrentVersion\Run 

    Self-kill routine: 

    cmd.exe /C del /Q /F

    Blacklist

    tmp;winnt;Application Data;AppData;Program Files (x86);Program Files;temp;thumbs.db;$Recycle.Bin;System Volume Information;Boot;Windows

    Locky instructions: 

    /_HELP_instructions.html._HELP_instructions.bmp.._HELP_instructions.txt.._Locky_recover_instructions.bmp._Locky_recover_instructions.txt

    Delete shadow copy:

    vssadmin.exe Delete Shadows /Quiet /All 

    C2:

    hxxp://185[.]115[.]140[.]170/checkupdate

    Targeted extensions:

    ..yuv…ycbcra..xis…x3f…x11…wpd…tex…sxg…stx…st8…st5…srw…srf…sr2…sqlitedb..sqlite3…sqlite..sdf…sda…sd0…s3db..rwz…rwl…rdb…rat…raf…qby…qbx…qbw…qbr…qba…py..psafe3..plc…plus_muhd…pdd…p7c…p7b…oth…orf…odm…odf…nyf…nxl…nx2…nwb…ns4…ns3…ns2…nrw…nop…nk2…nef…ndd…myd…mrw…moneywell…mny…mmw…mfw…mef…mdc…lua…kpdx..kdc…kdbx..kc2…jpe…incpas..iiq…ibz…ibank…hbk…gry…grey..gray..fhd…fh..ffd…exf…erf…erbsql..eml…dxg…drf…dng…dgc…des…der…ddrw..ddoc..dcs…dc2…db_journal..csl…csh…crw…craw..cib…ce2…ce1…cdrw..cdr6..cdr5..cdr4..cdr3..bpw…bgt…bdb…bay…bank..backupdb..backup..back..awg…apj…ait…agdl..ads…adb…acr…ach…accdt…accdr…accde…ab4…3pr…3fr…vmxf..vmsd..vhdx..vhd…vbox..stm…st7…rvt…qcow..qed…pif…pdb…pab…ost…ogg…nvram…ndf…m4p…m2ts..log…hpp…hdd…groups..flvv..edb…dit…dat…cmt…bin…aiff..xlk…wad…tlg…st6…st4…say…sas7bdat..qbm…qbb…ptx…pfx…pef…pat…oil…odc…nsh…nsg…nsf…nsd…nd..mos…indd..iif…fpx…fff…fdb…dtd…design..ddd…dcr…dac…cr2…cdx…cdf…blend…bkp…al..adp…act…xlr…xlam..xla…wps…tga…rw2…r3d…pspimage..ps..pct…pcd…m4v…m…fxg…flac..eps…dxb…drw…dot…db3…cpi…cls…cdr…arw…ai..aac…thm…srt…save..safe..rm..pwm…pages…obj…mlb…md..mbx…lit…laccdb..kwm…idx…html..flf…dxf…dwg…dds…csv…css…config..cfg…cer…asx…aspx..aoi…accdb…7zip..1cd…xls…wab…rtf…prf…ppt…oab…msg…mapimail..jnt…doc…dbx…contact…n64…m4a…m4u…m3u…mid…wma…flv…3g2…mkv…3gp…mp4…mov…avi…asf…mpeg..vob…mpg…wmv…fla…swf…wav…mp3…qcow2…vdi…vmdk..vmx…wallet..upk…sav…re4…ltx…litesql…litemod…lbf…iwi…forge…das…d3dbsp..bsa…bik…asset…apk…gpg…aes…ARC…PAQ…tar.bz2…tbk…bak…tar…tgz…gz..7z..rar…zip…djv…djvu..svg…bmp…png…gif…raw…cgm…jpeg..jpg…tif…tiff..NEF…psd…cmd…bat…sh..class…jar…java..rb..asp…cs..brd…sch…dch…dip…pl..vbs…vb..js..h…asm…pas…cpp…c…php…ldf…mdf…ibd…MYI…MYD…frm…odb…dbf…db..mdb…sql…SQLITEDB..SQLITE3…011…010…009…008…007…006…005…004…003…002…001…pst…onetoc2…asc…lay6..lay…ms11(Securitycopy)..ms11..sldm..sldx..ppsm..ppsx..ppam..docb..mml…sxm…otg…odg…uop…potx..pom..pptx..pptm..std…sxd…pot…pps…sti…sxi…otp…odp…wb2…123…wks…wk1…xltx..xltm..xlsx..xlsm..xlsb..slk…xlw…xlt…xlm…xlc…dif…stc…sxc…ots…ods…hwp…602…dotm..dotx..docm..docx..DOT…3dm…max…3ds…xml…txt…CSV…uot…RTF…pdf…XLS…PPT…stw…sxw…ott…odt…DOC…pem…p12…csr…crt…key..wallet.dat..

    p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica} p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica; min-height: 14.0px}

    Python WinAppDbg Template Constructs

    Source: https://gitlab.com/vitali.kremez/winappdbg_contruct
    Credit: WinappDbg; Parsia
    ###########################
    #### WinAppDbg  ###########
    ##########################

    I.  GetRunnerProcess

        if (args.run):
    # Concat all arguments into a string
    myargs = " ".join(args.run)

    if win32.PathFileExists(args.run[0]) is True:
    # File exists
    # Create a Debug object
    debug = winappdbg.Debug()

    try:
    # Debug the app
    # First item is program and the rest are arguments
    # execl: https://github.com/MarioVilas/winappdbg/blob/master/winappdbg/debug.py#L358
    my_process = debug.execl(myargs)

    print("Attached to {0} - {1}".format(my_process.get_pid(),
    my_process.get_filename()))

    # Keep debugging until the debugger stops
    debug.loop()

    finally:
    # Stop the debugger
    debug.stop()
    print("[*] Debugger stopped.")

    else:
    print("{0} not found.".format(args.run[0]))
    exit()

    II. GetSystemInformation()
        if(args.sysinfo):
    # Create a System object
    # https://github.com/MarioVilas/winappdbg/blob/master/winappdbg/system.py#L66
    system = winappdbg.System()

    # Use the built-in WinAppDbg table
    # https://github.com/MarioVilas/winappdbg/blob/master/winappdbg/textio.py#L1094
    table = winappdbg.Table("\t")

    # New line
    table.addRow("", "")

    # Header
    title = ("System Information", "")
    table.addRow(*title)

    # Add system information
    table.addRow("------------------")
    table.addRow("Bits", system.bits)
    table.addRow("OS", system.os)
    table.addRow("Architecture", system.arch)
    table.addRow("32-bit Emulation", system.wow64)
    table.addRow("Admin", system.is_admin())
    table.addRow("WinAppDbg", winappdbg.version)
    table.addRow("Process Count", system.get_process_count())

    print table.getOutput()
    exit()

    III. GetProcessList
        if (args.getprocesses):

    system = winappdbg.System()

    # We can reuse example 02 from the docs
    # https://winappdbg.readthedocs.io/en/latest/Instrumentation.html#example-2-enumerating-running-processes
    table = winappdbg.Table("\t")
    table.addRow("", "")

    header = ("pid", "process")
    table.addRow(*header)

    table.addRow("----", "----------")

    processes = {}

    # Add all processes to a dictionary then sort them by pid
    for process in system:
    processes[process.get_pid()] = process.get_filename()

    # Iterate through processes sorted by pid
    for key in sorted(processes.iterkeys()):
    table.addRow(key, processes[key])

    print table.getOutput()
    exit()

    IV.AttachByProcessID
        if (args.pid):
    system = winappdbg.System()

    # Get all pids
    pids = system.get_process_ids()

    if args.pid in pids:
    # pid exists

    # Create a Debug object
    debug = winappdbg.Debug()

    try:
    # Attach to pid
    # attach: https://github.com/MarioVilas/winappdbg/blob/master/winappdbg/debug.py#L219
    my_process = debug.attach(args.pid)

    print "Attached to %d - %s" % (my_process.get_pid(),
    my_process.get_filename())

    # Keep debugging until the debugger stops
    debug.loop()

    finally:
    # Stop the debugger
    debug.stop()
    print "Debugger stopped."

    else:
    print "pid %d not found." % (args.pid)

    exit()

    V. AttachByProcessName
        if (args.pname):
    debug = winappdbg.Debug()

    # example 3:
    # https://winappdbg.readthedocs.io/en/latest/_downloads/03_find_and_attach.py

    try:
    debug.system.scan()
    for (process, name) in debug.system.find_processes_by_filename(args.pname):
    print "Found %d, %s" % (process.get_pid(),
    process.get_filename())

    debug.attach(process.get_pid())

    print "Attached to %d-%s" % (process.get_pid(),
    process.get_filename())

    debug.loop()

    finally:
    # Stop the debugger
    debug.stop()
    print "Debugger stopped."
    exit()

    VI. WriteLoggerOutput
        global logger
    if args.output:
    # verbose=False disables printing to stdout
    logger = winappdbg.Logger(args.output, verbose=False)
    else:
    logger = winappdbg.Logger()

    # Example
    # logger.log_text("Started %d - %s" % (my_process.get_pid(), my_process.get_filename()))

    VII. GetLoadedModules
    class DebugEvents(winappdbg.EventHandler):
    """
    Event handler class.
    event: https://github.com/MarioVilas/winappdbg/blob/master/winappdbg/event.py
    """

    def load_dll(self, event):
    """
    Called when a new module is loaded.
    """
    # https://github.com/MarioVilas/winappdbg/blob/master/winappdbg/module.py#L71

    """
    Module object methods:
    get_base, get_filename, get_name, get_size, get_entry_point,
    get_process, set_process, get_pid,
    get_handle, set_handle, open_handle, close_handle

    get_size and get_entry_point do not work because WinAppDbg internally
    uses GetModuleInformation.
    https://msdn.microsoft.com/en-us/library/ms683201(v=VS.85).aspx
    And it cannot get info on files with "that were loaded with the
    LOAD_LIBRARY_AS_DATAFILE flag.""

    This is related:
    https://blogs.msdn.microsoft.com/oldnewthing/20150716-00/?p=45131
    """
    module = event.get_module()

    logstring = "\nLoaded DLL:\nName: %s\nFilename: %s\nBase Addr: %s\n" % \
    (module.get_name(), module.get_filename(), hex(module.get_base()))

    mylogger.log_text(logstring)

    # _ = module.get_size()

    print module.get_handle()

    # Create an instance of our eventhandler class
    myeventhandler = DebugEvents()

    VIII. GetProcessCreateProcessInfo
    class DebugEvents(winappdbg.EventHandler):
    """
    Event handler class.
    event: https://github.com/MarioVilas/winappdbg/blob/master/winappdbg/event.py
    """

    def create_process(self, event):
    process = event.get_process()
    pid = event.get_pid()
    # pid = process.get_pid()
    filename = process.get_filename()

    mylogger.log_text("CreateProcess %d - %s" % (pid, filename))

    def exit_process(self, event):
    process = event.get_process()
    pid = event.get_pid()
    # pid = process.get_pid()
    filename = process.get_filename()

    mylogger.log_text("ExitProcess %d - %s" % (pid, filename))

    def create_thread(self, event):
    process = event.get_process()
    thread = event.get_thread()

    tid = thread.get_tid()
    name = thread.get_name()

    mylogger.log_text("CreateThread %d - %s" % (tid, name))

    def exit_thread(self, event):
    process = event.get_process()
    thread = event.get_thread()

    tid = thread.get_tid()
    name = thread.get_name()

    mylogger.log_text("ExitThread %d - %s" % (tid, name))

    # Create an instance of our eventhandler class
    myeventhandler = DebugEvents()

    IX. BasicHookFunction
    class DebugEvents(winappdbg.EventHandler):
    """
    Event handler class.
    event: https://github.com/MarioVilas/winappdbg/blob/master/winappdbg/event.py
    """

    def load_dll(self, event):
    module = event.get_module()

    if module.match_name("kernel32.dll"):

    # Resolve function addresses
    address_CreateFileA = module.resolve("CreateFileA")
    address_CreateFileW = module.resolve("CreateFileW")

    # Types are here
    # https://github.com/MarioVilas/winappdbg/blob/master/winappdbg/win32/defines.py#L380
    sig_CreateFileA = (PVOID, DWORD, DWORD, PVOID, DWORD, DWORD, HANDLE)
    sig_CreateFileW = (PVOID, DWORD, DWORD, PVOID, DWORD, DWORD, HANDLE)

    pid = event.get_pid()

    # Hook function(pid, address, preCB, postCB, paramCount, signature)
    # https://github.com/MarioVilas/winappdbg/blob/master/winappdbg/breakpoint.py#L3969
    event.debug.hook_function(pid, address_CreateFileA,
    preCB=pre_CreateFileA,
    postCB=post_CreateFileA,
    signature=sig_CreateFileA)

    event.debug.hook_function(pid, address_CreateFileW,
    preCB=pre_CreateFileW,
    postCB=post_CreateFileW,
    signature=sig_CreateFileW)

    # Another way of setting up hooks without signature

    """
    event.debug.hook_function(pid, address_CreateFileA,
    preCB=pre_CreateFileA,
    postCB=post_CreateFileA,
    paramCount=7)

    event.debug.hook_function(pid, address_CreateFileW,
    preCB=pre_CreateFileW,
    postCB=post_CreateFileW,
    paramCount=7)
    """

    # Callback functions
    # -------------------

    # Callback function parameters are always
    # (event, ra (return address), then function parameters)
    # self is first if part of the eventhandler class


    def pre_CreateFileW(event, ra, lpFileName, dwDesiredAccess, dwShareMode,
    lpSecurityAttributes, dwCreationDisposition,
    dwFlagsAndAttributes, hTemplateFile):

    """
    This will be called as soon as we enter the function and before the
    function stack frame is created.
    """

    process = event.get_process()

    # Suspend the process because why not
    process.suspend()
        mylogger.log_text("Hit kernel32!CreateFileW")

    # 32-bit so all parameters are on stack

    # In case you want a pointer to the top of the stack
    # thread = event.get_thread()

    # All memory read stuff are at
    # https://github.com/MarioVilas/winappdbg/blob/master/winappdbg/process.py#L125

    # fUnicode=True because we are in the Wide or Unicode version of the API
    myFileName = process.peek_string(lpFileName, fUnicode=True)

    mylogger.log_text("lpFilename: %s" % (myFileName))

    # Resume the process
    process.resume()


    def pre_CreateFileA(event, ra, lpFileName, dwDesiredAccess, dwShareMode,
    lpSecurityAttributes, dwCreationDisposition,
    dwFlagsAndAttributes, hTemplateFile):

    process = event.get_process()

    # Suspend the process because why not
    process.suspend()

    mylogger.log_text("Hit kernel32!CreateFileA")

    # fUnicode=False because we are in the ANSI version
    myFileName = process.peek_string(lpFileName, fUnicode=False)

    mylogger.log_text("lpFilename: %s" % (myFileName))

    process.resume()


    def post_CreateFileW(event, retval):

    mylogger.log_text("Leaving kernel32!CreateFileW")
    mylogger.log_text("Return value: %x" % (retval))


    def post_CreateFileA(event, retval):

    mylogger.log_text("Leaving kernel32!CreateFileA")
    mylogger.log_text("Return value: %x" % (retval))

    # Create an instance of our eventhandler class
    myeventhandler = DebugEvents()

    X. BetterHookFunction
    class DebugEvents(winappdbg.EventHandler):
    """
    Event handler class.
    event: https://github.com/MarioVilas/winappdbg/blob/master/winappdbg/event.py
    """

    # Better hooking
    # https://winappdbg.readthedocs.io/en/latest/Debugging.html#example-9-intercepting-api-calls

    apiHooks = {

    # Hooks for the kernel32 library.
    "kernel32.dll": [

    # We have seen these before
    # Function Signature
    ("CreateFileA", (PVOID, DWORD, DWORD, PVOID, DWORD, DWORD, HANDLE)),
    ("CreateFileW", (PVOID, DWORD, DWORD, PVOID, DWORD, DWORD, HANDLE)),

    # Can also pass parameter count
    # ("CreateFileA", 6),
    # ("CreateFileW", 6),
    ],
    }

    # Now we can simply define a method for each hooked API.
    # "pre_" methods are called when entering the hooked function.
    # "post_" methods are called when returning from the hooked function.

    def pre_CreateFileW(self, event, ra, lpFileName, dwDesiredAccess,
    dwShareMode, lpSecurityAttributes, dwCreationDisposition,
    dwFlagsAndAttributes, hTemplateFile):

    process = event.get_process()
    myFileName = process.peek_string(lpFileName, fUnicode=True)
    mylogger.log_text("pre_CreateFileW opening file %s" % (myFileName))

    def post_CreateFileW(self, event, retval):
    mylogger.log_text("Return value: %x" % retval)

    def pre_CreateFileA(self, event, ra, lpFileName, dwDesiredAccess,
    dwShareMode, lpSecurityAttributes, dwCreationDisposition,
    dwFlagsAndAttributes, hTemplateFile):

    process = event.get_process()
    myFileName = process.peek_string(lpFileName, fUnicode=False)
    mylogger.log_text("pre_CreateFileA opening file %s" % (myFileName))

    def post_CreateFileA(self, event, retval):
    mylogger.log_text("Return value: %x" % retval)

    # Create an instance of our eventhandler class
    myeventhandler = DebugEvents()

    XI. HookInternetExplorer HttpSendRequestW
    class DebugEvents(winappdbg.EventHandler):
    """
    Event handler class.
    event: https://github.com/MarioVilas/winappdbg/blob/master/winappdbg/event.py
    """

    """
    BOOL HttpSendRequest(
    _In_ HINTERNET hRequest,
    _In_ LPCTSTR lpszHeaders,
    _In_ DWORD dwHeadersLength,
    _In_ LPVOID lpOptional,
    _In_ DWORD dwOptionalLength
    );
    """

    apiHooks = {

    # Hooks for the wininet.dll library - note this is case-sensitive
    "wininet.dll": [

    # Function Signature
    ("HttpSendRequestW", (HANDLE, PVOID, DWORD, PVOID, DWORD)),
    ],
    }

    def pre_HttpSendRequestW(self, event, ra, hRequest, lpszHeaders,
    dwHeadersLength, lpOptional, dwOptionalLength):

    process = event.get_process()

    if dwHeadersLength != 0:
    mylogger.log_text(winapputil.utils.get_line())
    mylogger.log_text("HttpSendRequestW")

    headers = process.peek_string(lpszHeaders, fUnicode=True)
    mylogger.log_text("Headers %s" % (headers))

    if dwOptionalLength != 0:
    # This is not unicode - see the pointer name (lp vs. lpsz)
    # fUnicode is set to False (default) then
    optional = process.peek_string(lpOptional, fUnicode=False)

    mylogger.log_text("Optional %s" % (optional))
    mylogger.log_text(winapputil.utils.get_line())

    # Create an instance of our eventhandler class
    myeventhandler = DebugEvents()


    XII. HookInternetExplorer HttpSendRequestW/HttpOpenRequest
    class DebugEvents(winappdbg.EventHandler):
    """
    Event handler class.
    event: https://github.com/MarioVilas/winappdbg/blob/master/winappdbg/event.py
    """

    """
    BOOL HttpSendRequest(
    _In_ HINTERNET hRequest,
    _In_ LPCTSTR lpszHeaders,
    _In_ DWORD dwHeadersLength,
    _In_ LPVOID lpOptional,
    _In_ DWORD dwOptionalLength
    );

    HINTERNET HttpOpenRequest(
    _In_ HINTERNET hConnect,
    _In_ LPCTSTR lpszVerb,
    _In_ LPCTSTR lpszObjectName,
    _In_ LPCTSTR lpszVersion,
    _In_ LPCTSTR lpszReferer,
    _In_ LPCTSTR *lplpszAcceptTypes,
    _In_ DWORD dwFlags,
    _In_ DWORD_PTR dwContext
    );
    """

    apiHooks = {

    # Hooks for the wininet.dll library - note this is case-sensitive
    "wininet.dll": [

    # Function Signature
    ("HttpSendRequestW", (HANDLE, PVOID, DWORD, PVOID, DWORD)),
    ("HttpOpenRequestW", (HANDLE, PVOID, PVOID, PVOID, PVOID, PVOID,
    DWORD, PVOID)),
    ],
    }

    def pre_HttpSendRequestW(self, event, ra, hRequest, lpszHeaders,
    dwHeadersLength, lpOptional, dwOptionalLength):

    process = event.get_process()

    if dwHeadersLength != 0:
    mylogger.log_text(winapputil.utils.get_line())
    mylogger.log_text("HttpSendRequestW")

    headers = process.peek_string(lpszHeaders, fUnicode=True)
    mylogger.log_text("Headers %s" % (headers))

    if dwOptionalLength != 0:
    # This is not unicode - see the pointer name dummy (lp vs. lpsz)
    # False by default but a good idea to include it for clarity
    optional = process.peek_string(lpOptional, fUnicode=False)

    mylogger.log_text("Optional %s" % (optional))
    mylogger.log_text(winapputil.utils.get_line())

    def pre_HttpOpenRequestW(self, event, ra, hConnect, lpszVerb,
    lpszObjectName, lpszVersion, lpszReferer,
    lplpszAcceptTypes, dwFlags, dwContext):

    process = event.get_process()

    verb = process.peek_string(lpszVerb, fUnicode=True)
    if verb is None:
    verb = "GET"

    obj = process.peek_string(lpszObjectName, fUnicode=True)

    mylogger.log_text(winapputil.utils.get_line())
    mylogger.log_text("HttpOpenRequestW")
    mylogger.log_text("verb: %s" % verb)
    mylogger.log_text("obj : %s" % obj)
    mylogger.log_text(winapputil.utils.get_line())

    # Create an instance of our eventhandler class
    myeventhandler = DebugEvents()

    XIII. HoookFireFoxFunction PR_Write
    class DebugEvents(winappdbg.EventHandler):
    """
    Event handler class.
    event: https://github.com/MarioVilas/winappdbg/blob/master/winappdbg/event.py
    """

    # Better hooking
    # https://winappdbg.readthedocs.io/en/latest/Debugging.html#example-9-intercepting-api-calls

    """
    PRInt32 PR_Write(
    PRFileDesc *fd,
    const void *buf,
    PRInt32 amount);

    fd: A pointer to the PRFileDesc object for a file or socket
    buf: A pointer to the buffer holding the data to be written
    amount: The amount of data, in bytes, to be written from the buffer
    """

    apiHooks = {

    # Hooks for the nss3.dll library
    'nss3.dll': [

    ('PR_Write', (PVOID, PVOID, PVOID)),
    ],
    }

    def pre_PR_Write(self, event, ra, fd, buf, amount):

    process = event.get_process()

    if (amount > 100) and (amount < 1000):
    mylogger.log_text("PR_Write")

    # https://github.com/MarioVilas/winappdbg/blob/master/winappdbg/process.py#L1581
    contents = process.read(buf, amount)

    mylogger.log_text("%s" % str(contents))

    mylogger.log_text(winapputil.utils.get_line())

    # Create an instance of our eventhandler class
    myeventhandler = DebugEvents()

    XIV. ModifySleep on x86/X64
    class DebugEvents(winappdbg.EventHandler):
    """
    Event handler class.
    event: https://github.com/MarioVilas/winappdbg/blob/master/winappdbg/event.py
    """

    # Better hooking
    # https://winappdbg.readthedocs.io/en/latest/Debugging.html#example-9-intercepting-api-calls

    """
    VOID WINAPI Sleep(
    _In_ DWORD dwMilliseconds
    );
    https://msdn.microsoft.com/en-us/library/windows/desktop/ms686298(v=vs.85).aspx
    """

    apiHooks = {

    # Hooks for the kernel32.dll library
    "kernel32.dll": [

    # Note how are passing only one parameter
    ("Sleep", (DWORD, )),

    # We can also pass the number of arguments instead of signature
    # ("Sleep", 1),
    ],
    }

    def pre_Sleep(self, event, ra, dwMilliseconds):

    process = event.get_process()
    process.suspend()

    thread = event.get_thread()

    bits = thread.get_bits()
    emulation = thread.is_wow64()

    logstring = "Original dwMilliseconds %d" % dwMilliseconds

    mylogger.log_text(logstring)

    # If running on a 32-bit machine or 32-bit process on 64-bit machine
    if bits == 32 or emulation is True:
    top_of_stack = thread.get_sp()

    # return_address, dwMilliseconds = thread.read_stack_dwords(2)
    # logstring = "Return Address %s" % \
    # winappdbg.HexDump.address(return_address, bits)

    # mylogger.log_text(logstring)

    process.write_dword(top_of_stack+((bits/8)*1), 0)

    # AMD64 calling convention on Windows uses fastcall
    # rcx, rdx, r8, r9 then stack

    elif bits == 64:
    thread.set_register("Rcx", 10000)

    process.resume()
    # Create an instance of our eventhandler class
    myeventhandler = DebugEvents()

    XV. ModifyDomainFunction in IE InternetConnectW
    class DebugEvents(winappdbg.EventHandler):
    """
    Event handler class.
    event: https://github.com/MarioVilas/winappdbg/blob/master/winappdbg/event.py
    """

    # Better hooking
    # https://winappdbg.readthedocs.io/en/latest/Debugging.html#example-9-intercepting-api-calls

    """
    HINTERNET InternetConnect(
    _In_ HINTERNET hInternet,
    _In_ LPCTSTR lpszServerName,
    _In_ INTERNET_PORT nServerPort,
    _In_ LPCTSTR lpszUsername,
    _In_ LPCTSTR lpszPassword,
    _In_ DWORD dwService,
    _In_ DWORD dwFlags,
    _In_ DWORD_PTR dwContext
    );
    """

    apiHooks = {

    # Hooks for the wininet.dll library
    "wininet.dll": [

    # InternetConnectW
    # https://msdn.microsoft.com/en-us/library/windows/desktop/aa384363(v=vs.85).aspx
    # ("InternetConnectW", (HANDLE, PVOID, WORD, PVOID, PVOID, DWORD, DWORD, PVOID)),
    ("InternetConnectW", 8),

    ],
    }

    # Now we can simply define a method for each hooked API.
    # Methods beginning with "pre_" are called when entering the API,
    # and methods beginning with "post_" when returning from the API.

    def pre_InternetConnectW(self, event, ra, hInternet, lpszServerName,
    nServerPort, lpszUsername, lpszPassword,
    dwService, dwFlags, dwContext):

    process = event.get_process()
    process.suspend()
    thread = event.get_thread()

    server_name = process.peek_string(lpszServerName, fUnicode=True)
    print(server_name)

    if server_name == "example.com":

    # mylogger.log_text(server_name)

    # Encoding as UTF16
    new_server_name = "google.com".encode("utf-16le")

    # Get length of new payload
    payload_length = len(new_server_name)

    # Allocate memory in target process and get a pointer
    new_payload_addr = event.get_process().malloc(payload_length)

    # Write the new payload to that pointer
    process.write(new_payload_addr, new_server_name)

    top_of_stack = thread.get_sp()

    bits = thread.get_bits()
    emulation = thread.is_wow64()

    if bits == 32 or emulation is True:

    # Write the pointer to the new payload with the old one
    process.write_dword(top_of_stack + 8, new_payload_addr)

    elif bits == 64:
    thread.set_register("Rdx", new_payload_addr)

    process.resume()

    # Create an instance of our eventhandler class
    myeventhandler = DebugEvents()
    XVI. RegistryReader RegQueryValueExW
    class DebugEvents(winappdbg.EventHandler):
    """
    Event handler class.
    event: https://github.com/MarioVilas/winappdbg/blob/master/winappdbg/event.py
    """

    # Better hooking
    # https://winappdbg.readthedocs.io/en/latest/Debugging.html#example-9-intercepting-api-calls

    """
    LONG WINAPI RegQueryValueEx(
    _In_ HKEY hKey,
    _In_opt_ LPCTSTR lpValueName,
    _Reserved_ LPDWORD lpReserved,
    _Out_opt_ LPDWORD lpType,
    _Out_opt_ LPBYTE lpData,
    _Inout_opt_ LPDWORD lpcbData
    );
    """

    apiHooks = {

    # Hooks for the adviapi32.dll library
    # Can also hook kernel32.dll
    "advapi32.dll": [

    # RegQueryValueEx
    # https://msdn.microsoft.com/en-us/library/windows/desktop/ms724911(v=vs.85).aspx
    # ("RegQueryValueExW", (HANDLE, PVOID, PVOID, PVOID, PVOID, PVOID)),
    ("RegQueryValueExW", 6),

    ],
    }

    def pre_RegQueryValueExW(self, event, ra, hKey, lpValueName, lpReserved,
    lpType, lpData, lpcbData):

    # Store the pointer for later use
    self.hKey = hKey
    self.lpValueName = lpValueName
    self.lpType = lpType
    self.lpData = lpData
    self.lpcbData = lpcbData

    def post_RegQueryValueExW(self, event, retval):
    process = event.get_process()

    process.suspend()

    table = winappdbg.Table("\t")
    table.addRow("", "")

    # Need to watch out for optional parameters
    if self.lpType is not 0:
    keyType = process.read_dword(self.lpType)
    table.addRow("keyType", keyType)

    valueName = process.peek_string(self.lpValueName, fUnicode=True)
    size = process.read_dword(self.lpcbData)

    table.addRow("valueName", valueName)
    table.addRow("size", size)

    if self.lpData is not 0:
    data = process.read(self.lpData, size)
    table.addRow("data", data)
    table.addRow("data-hex", data.encode("hex"))

    mylogger.log_text(table.getOutput())
    mylogger.log_text("-"*30)

    process.resume()

    # Create an instance of our eventhandler class
    myeventhandler = DebugEvents()

    XVII RegistryWriter
    class DebugEvents(winappdbg.EventHandler):
    """
    Event handler class.
    event: https://github.com/MarioVilas/winappdbg/blob/master/winappdbg/event.py
    """

    # Better hooking
    # https://winappdbg.readthedocs.io/en/latest/Debugging.html#example-9-intercepting-api-calls

    """
    LONG WINAPI RegQueryValueEx(
    _In_ HKEY hKey,
    _In_opt_ LPCTSTR lpValueName,
    _Reserved_ LPDWORD lpReserved,
    _Out_opt_ LPDWORD lpType,
    _Out_opt_ LPBYTE lpData,
    _Inout_opt_ LPDWORD lpcbData
    );
    """

    apiHooks = {

    # Hooks for the advapi32.dll library
    "advapi32.dll": [

    # RegQueryValueEx
    # https://msdn.microsoft.com/en-us/library/windows/desktop/ms724911(v=vs.85).aspx
    # ("RegQueryValueExW", (HANDLE, PVOID, PVOID, PVOID, PVOID, PVOID)),
    ("RegQueryValueExW", 6),

    ],
    }

    def pre_RegQueryValueExW(self, event, ra, hKey, lpValueName, lpReserved,
    lpType, lpData, lpcbData):

    # Store the pointer for later use
    self.hKey = hKey
    self.lpValueName = lpValueName
    self.lpType = lpType
    self.lpData = lpData
    self.lpcbData = lpcbData

    def post_RegQueryValueExW(self, event, retval):
    process = event.get_process()

    process.suspend()

    valueName = process.peek_string(self.lpValueName, fUnicode=True)

    if valueName == "layout":
    # size = process.read_dword(self.lpcbData)
    # data = process.read(self.lpData, size)

    newLayout = 0x00

    process.write_dword(self.lpData, newLayout)

    # OR
    # process.write(self.lpData, "00".decode("hex"))

    process.resume()
    # Create an instance of our eventhandler class
    myeventhandler = DebugEvents()

    06-18-2017: "Thank you for confirming receipt" Weight Loss Spam Campaign

    Date: June 18, 2017
    Source: Email Spam
    Previous Same Spam Campaign (June 9, 2017: “Amazon Order Cancelled”):

    http://www.vkremez.com/2017/06/amazon-order-cancelled-weight-loss-spam.html

    FromAngela Moore Support
    Subject: Thank you for confirming receipt
    Here is the full spam chain:

  • First email href redirect
  • hxxp://www[.]royalgemsandarts[.]com/neutrality[.]php

  • Obfuscated href JS redirect
  • hxxp://loss5weight-fast[.]world/?a=417768&c=cpcdiet&s=good_live

  • Third-layer PHP redirect
  • hxxp://loss5weight-fast[.]world/int/eqyy/forskolin/?bhu=Q8aE9FQfMfJZxJHHuGyxUz7qZ4Xcny

  • Final landing page
  • hxxps://premium-forskolin-extract[.]com/forskolin_int/?click_id=06_85469609_32230874-37af-4605-94f7-a96bba399453&subid1=326675&netid=3&ver=old&ad=1kgC

    I. Original email spam:

    Email headers:

    Authentication-Results: spf=none (sender IP is 62[.]176[.]169[.]100) smtp.mailfrom=innovationcorp.net; hotmail.com; dkim=none (message not signed) header.d=none;hotmail.com; dmarc=none action=none header.from=innovationcorp.net;Received-SPF: None (protection.outlook.com: innovationcorp.net does not designate permitted sender hosts)Received: from BAY004-MC5F14.hotmail.com by SN1NAM01FT010.mail.protection.outlook.com with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384_P384) id 15.1.1157.12 via Frontend Transport; Sat, 17 Jun 2017 13:59:14 +0000X-IncomingTopHeaderMarker: OriginalChecksum:C4EC5D1CED9159B632F69622160D2CDB0826E69A1A0A6B56396F57CA34D8B853;UpperCasedChecksum:E0D5D0F87E9B7555077E317749ABDABF68C51B317B0F4B4B52E7CC6CB90E0999;SizeAsReceived:704;Count:13Received: from raider.solvere.sk ([62[.]176[.]169[.]100]) by BAY004-MC5F14.hotmail.com with Microsoft SMTPSVC(7.5.7601.23143); Sat, 17 Jun 2017 06:59:13 -0700

    II.  Review the link href PHP page via the curl command 

    curl hxxp://www[.]royalgemsandarts[.]com/neutrality[.]php

    III. JavaScript function resolves to 

    hxxp://loss5weight-fast[.]world/?a=417768&c=cpcdiet&s=good_live

    viewed by simply printing an alert box to the screen via the alert() JavaScript function.

    IV.  Encoded JavaScript href() redirect from 

    hxxp://loss5weight-fast[.]world/?a=417768&c=cpcdiet&s=good_live -> 

    hxxp://loss5weight-fast[.]world/us/xxrr/cla-safflower-oil/bhu=Q8aEvU5pCPVc8KBpNcbWBXvbBotjvr

    IV. The landing page leads to the “CLA Safflower Oil” weight loss product landing ->

    hxxps://cla-extr[.]com/?click_id=06_85042356_6b816138-2c39-4493-9eab-aff53ec51810&subid1=313491&netid=3&ver=old&ad=1kgC


    Let’s Code: Cerber Extension Finder in FASM

    Inspiration: https://twitter.com/VK_Intel/status/875247835880534017

    Goal: Identify Cerber ransomware extension on any machine based on MachineGuid’s value.

    Here is the ASM code in FASM:
    ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    format pe gui 4.0
    include ‘win32ax.inc’
    entry cerber_ext
    ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; CERBER Extension Finder ;;;;;;;;;;;;;;;;;;
    ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; by @VK_Intel ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    section ‘.text’ code readable executable
    cerber_ext:
       invoke RegOpenKeyExA, HKEY_LOCAL_MACHINE,CryptoReg,NULL,KEY_READ,ckey
       invoke VirtualAlloc, NULL, 24, MEM_COMMIT, PAGE_READWRITE
       mov [RegBuffer], eax
       invoke RegQueryValueExA, [ckey], MachineGuid, NULL,dword_type,[RegBuffer],RegSize
       invoke lstrlen, [RegBuffer]
       mov ebx, [RegBuffer]
       add ebx, eax
    start_find:
       dec ebx
       mov edx, [ebx]
       cmp dl, 2dh ; “-” in hex
       je one_more
       jmp start_find
    one_more:
       dec ebx
       mov edx, [ebx]
       cmp dl, 2dh ; “-” in hex
       je final
       jmp one_more
    final:
       inc ebx
       invoke VirtualAlloc, NULL, 4, MEM_COMMIT, PAGE_READWRITE
       mov [fourthGuid], eax
       invoke lstrcpyn,[fourthGuid],ebx,5
       invoke MessageBox, 0, [fourthGuid], Cerber_Ext, MB_OK
       invoke ExitProcess, 0
    ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    section ‘.data’ data readable writable
    ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    CryptoReg           db ‘SOFTWARE\Microsoft\Cryptography’,0
    MachineGuid      db ‘MachineGuid’,0
    ckey                    dd ?
    dword_type        dd REG_DWORD
    RegBuffer          dd ?
    RegSize              dd 256
    fourthGuid         dd ?
    Cerber_Ext        db ‘==> Your Cerber Extension <==', 0
    ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    section ‘.itable’ import data readable
    ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
            library  kernel32,’kernel32.dll’,\
                         advapi32,’Advapi32.dll’,\
                         user32, ‘user32.dll’
            import user32,\
                     MessageBox,’MessageBoxA’
             import  kernel32,\
                     ExitProcess,’ExitProcess’,\
                     lstrlen, ‘lstrlenA’,\
                     lstrcpyn, ‘lstrcpynA’,\
                     VirtualAlloc, ‘VirtualAlloc’
             import  advapi32,\
                     RegOpenKeyExA, ‘RegOpenKeyExA’,\
                     RegQueryValueExA, ‘RegQueryValueExA’

    Let’s Learn: Resistence Patch Tutorial

    Source: tuts4you
    Goal: Practice cracking and reverse engineering skills.
    Problem: The binary set up various CMP and JMP calls to prevent getting us to the “Patched!” solution.


    Solution:
    (1) Walk through the binary execution and examine necessary calls by looking at the ASCII strings “Not Patched”, “Patched!” and etc.
    (2) Set up breakpoints on interesting CMP calls.

     (3) Patch the first call to NOT make the jump to the “Not Patch” routine. I decided to patch the CMP call as “CMP EBX, -1” just to make sure not to trigger the next JLE (jump if larger than or equals). The current EBX hex value 00000000 or signed “0”. So, the function essentially compares it to “2”. We changed  to “-1”.

    (3) Next, I decided to patch the EBX register value to “4” to make sure we make a closer jump over to the “Not Patched” instructions, closed to the “Patched!” function.

    (4) Last patch we have to apply is to alter the non-conditional JMP function instruction. I patched it with “NOP.”

    (5) Arrive at the “Patched!” screen display.