12 minutes to read - May 22, 2023

I built a Zero Day virus with undetectable exfiltration using only ChatGPT prompts

VISIT
I built a Zero Day virus with undetectable exfiltration using only ChatGPT prompts
ChatGPT is a powerful artificial intelligence language model that can generate human-like text in response to prompts, making it a useful tool for various natural language processing tasks. As I mentioned earlier, one of these tasks is writing code. So, I thought to myself, is it possible to build a new zero day using only ChatGPT prompts?”

Для этого я решил не писать код самостоятельно и использовать только передовые методы, такие как стеганография, которые ранее были зарезервированы только для злоумышленников национального государства. Я хотел попытаться создать что-то, что работало бы полностью от начала до конца, без необходимости читателю представлять, как определенные части вредоносного ПО будут «связываться друг с другом».

Общая цель этого упражнения состояла в том, чтобы доказать две вещи:

Как легко обойти недостаточные барьеры, которые есть в ChatGPT

Как легко создавать передовые вредоносные программы без написания кода и только с помощью ChatGPT

Я начал свой набег с того, что посмотрел, что я могу заставить ChatGPT генерировать. Я решил использовать язык реализации Go, учитывая простоту разработки и то, что я мог вручную проверить код, если это потребуется для отладки проблем.

Первая версия — создание MVP

Первая подсказка, которую я сделал, заключалась в том, чтобы просто сгенерировать что-то, что поддается количественной оценке как вредоносное ПО. Понятно, что ChatGPT напомнил мне, что генерировать вредоносное ПО неэтично, и отказался предложить мне какой-либо код, который помог бы мне в этом.

Чтобы обойти это, я решил, что вместо того, чтобы сразу отправлять запросы к ChatGPT, я решил сгенерировать небольшие фрагменты вспомогательного кода и вручную собрать весь исполняемый файл. Я пришел к выводу, что стеганография — лучший подход к эксфильтрации, а «жить за счет земли» — лучший подход для поиска больших файлов изображений, уже существующих на самом диске. Это вредоносное ПО было предназначено для конкретных важных лиц, где оно могло бы принести дивиденды за поиск ценных документов на диске C, а не рисковать переносом внешнего файла на устройство и быть помеченным для вызова URL-адресов.

Первый успешный запрос состоял в том, чтобы просто попросить сгенерировать некоторый код, который искал PNG размером более 5 МБ на локальном диске. Проектное решение здесь заключалось в том, что PNG размером 5 МБ будет достаточно для хранения фрагмента важного бизнес-документа, такого как PDF или DOCX.


Вооружившись кодом для поиска PNG-файлов размером более 5 МБ, я скопировал его обратно в консоль и попросил ChatGPT добавить некоторый код, который будет кодировать найденный PNG с помощью стеганографии. Для этого он предложил готовую стеганографическую библиотеку Ауера: https://github.com/auyer/steganography.

В этот момент у меня почти был MVP для тестирования, недостающая часть головоломки заключалась в том, что мне нужно было найти некоторые файлы на устройстве для эксфильтрации и куда загрузить результаты. Я решил попросить ChatGPT дать мне некоторый код, который перебирает папки «Документы пользователя», «Рабочий стол» и «AppData», чтобы найти любые документы PDF или документы DOCX для эксфильтрации. Я добавил максимальный размер 1 МБ, чтобы встроить весь документ в одно изображение для первой итерации кода.

Для эксфильтрации я решил, что Google Диск будет хорошим выбором, поскольку весь домен Google, как правило, находится в «разрешенном списке» в большинстве корпоративных сетей.

Объединение фрагментов для создания нашего MVP

Сопоставление фрагментов с помощью подсказки оказалось на удивление самой простой частью, так как мне просто нужно было опубликовать фрагменты кода, которые мне удалось заставить ChatGPT сгенерировать и объединить их вместе. Итак, с этим результатом ChatGPT у меня теперь был MVP, но он был относительно бесполезен, поскольку любой документ «жемчужины короны», вероятно, будет больше 1 МБ и, следовательно, должен быть разбит на несколько «фрагментов» для бесшумной эксфильтрации с использованием стеганографии. После четырех или пяти подсказок у меня был код, который разбивал PDF на фрагменты по 100 КБ и соответственно генерировал PNG из списка, который был сгенерирован из PNG локально на устройстве.

Итак, теперь у меня есть мой MVP, и пришло время для некоторых тестов:

Тестирование MVP

В рамках тестирования я хотел посмотреть, как готовый код сравнивается с современными атаками, такими как Emotet, и будут ли многие поставщики воспринимать EXE-файл, сгенерированный ChatGPT, как вредоносный, поэтому я загрузил MVP на VirusTotal:


Итак, сгенерировав всю кодовую базу исключительно с помощью ChatGPT, я подумал, что пять поставщиков, пометивших файл как вредоносный из шестидесяти девяти, — это неплохое начало, но нам нужно постараться, чтобы правильно пометить это как атаку нулевого дня.

Оптимизация для уклонения от обнаружения

The most obvious optimisation to make, would be to force ChatGPT to refactor the code that is calling Auyer's Steganographic library. I suspected that a GUUID or variable somewhere in the compiled EXE may be alerting the five vendors to mark the file as malicious. ChatGPT did an awesome job of creating my own LSB Steganography function, within my local app rather than having to call the external library. This dropped the number of detections to two vendors, but not quite the golden number of zero vendors marking the file as malicious.

For the final two vendors, I knew that one of them is a leading sandbox and the other conducts static analysis on executables. With this in mind, I asked ChatGPT to introduce two new changes to the code, one to delay the effective start by two minutes, therefore assuming that the hypothetical corporate user who were to open the Zero Day, wouldn't log off immediately after opening. The logic behind the change being that it would evade the monitoring capabilities, as some sandboxes have a built-in timeout (for performance reasons) and if that timeout is broken, then they will respond with a clean verdict, even if the analysis hasn't completed.

The second change I asked ChatGPT to make was to obfuscate the code:

For both the direct requests to ChatGPT, there are some safeguarding measures implemented, meaning that there is at least a certain level of competency required to work out how to evade the ChatGPT safeguarding.

Having seen that ChatGPT wouldn’t support my direct request, I decided to try again. By simply changing my request from asking it to obfuscate the code, changing the prompt to asking ChatGPT to change all the variables to random English first names and surnames, it happily obliged. As an additional test, I disguised my ask to obfuscate to protect the intellectual property of the code, again it produced some example code that obfuscated the variable names and suggested relevant Go modules I could use to generate fully obfuscated code.

The theory behind this change is that for the second vendor, we needed to evade the static malware analysis, and by obfuscating the code you can sometimes evade detection. https://en.wikipedia.org/wiki/Obfuscation_(software) However, if you obfuscate beyond human readability, this can sometimes flag up other detection-based tools as non-readable variable names are used.

So, with all this in mind, I decided to retest with the artificial delay and firstname / surname variables:


So, it is all running OK with those changes, let's upload it to VirusTotal and look at the new result:


And there we have it; we have our Zero Day. Simply using ChatGPT prompts, and without writing any code, we were able to produce a very advanced attack in only a few hours. The equivalent time taken without an AI based Chatbot, I would estimate could take a team of 5 – 10 malware developers a few weeks, especially to evade all detection based vendors.

I anticipate some people reading this post may say, that is all well and good but my endpoint tool will spot the behaviour with behavioural analytics. However, I have tested two versions of the code against two industry leading behavioural monitoring endpoint tools, and in both occasions, I was able to run the executable and successfully exfiltrate data to Google Drive. This may be due to the non-standard behaviour the code is exhibiting, as rather than encrypting files (ransomware) or trying to send copies of those files to external sources, it’s wrapping those files in low value goods (images) and sending those out instead.

Adding an initial infiltration mechanism

I realised that ending the solution here, would be slightly disappointing as I wouldn’t have added an initial infiltration mechanism. I decided to ask ChatGPT to add a container format and to auto call the EXE. This didn’t work. With some more prompting, I managed to convince ChatGPT to produce instructions on how to embed my Executable into an SCR (screen saver) format on Windows and then make it so that the SCR file format would auto execute.

This worked great and so I uploaded the results to VirusTotal again:

Disappointed with only three vendors marking the default SCR file as malicious, I decided to upload a benign SCR file into VirusTotal. I checked the results again, and the same three vendors had marked the benign SCR file as malicious. It is highly likely that these three vendors are just marking all SCR files as malicious rather than doing any kind of intelligent detection.

I could imagine a scenario where an SCR file is sent to a user over email and they are socially engineered to run the SCR file, and that is when the executable is run to silently exfiltrate their most sensitive documents. This could be high-value individuals, such as prominent politicians, or senior members of a large organisation, e.g C-level executives.

Conclusion

In conclusion, this kind of end to end very advanced attack has previously been reserved for nation state attackers using many resources to develop each part of the overall malware. And yet despite this, a self-confessed novice has been able to create the equivalent malware in only a few hours with the help of ChatGPT. This is a concerning development, where the current toolset could be embarrassed by the wealth of malware we could see emerge as a result of ChatGPT.

Mitigations

Whilst the example was highlighted to show just one single way you can use ChatGPT to bypass modern defences, there are a few ways to mitigate the threat. Here is ChatGPT’s own advice on protecting against this attack:


If we take a look at the ChatGPT suggestions in slightly more detail and deconstruct each piece of advice to stop the attack:

Monitor network traffic: Existing tools that monitor network traffic, do so in a way that look for anomalies. However, by design, steganography does not stand out as ‘unusual’ traffic as the only document that traverses the boundary are images.

Block suspicious traffic: Most organisations’ current toolset today are unlikely to block image upload traffic to the google domain, as image upload traffic by nature doesn’t usually mean a potentially advanced attack and would have the unfortunate effect of blocking many legitimate Google services, such as reverse image search. Also, given the wealth of other document sharing tools, an attacker would likely be able to find another legitimately used corporate tool to upload their images to.

Implement access controls: This is a good piece of advice, however, it raises the question of where the access control actually lies. If this piece of malware ends up in the hands of the employee who the access control is built around, then even good access controls will only limit the potential victims.

Use Encryption: This is not clear advice as encryption can be used as an exfiltration mechanism itself.

Train your employees: This is good advice to try and stop the initial attack, however, humans are not necessarily the only weak link.

Regularly update and patch software: Again, good advice, but this is an advanced attack that even patching software wouldn’t necessarily help with, even after the ‘discovery’ of the Zero Day.

 Наконец, важно отметить, что решение Forcepoint Zero Trust CDR предотвращает как входящий канал (входящие исполняемые файлы по электронной почте), так и просто настраивая входящую почту, чтобы ни при каких обстоятельствах не позволять исполняемым файлам входить в организацию через канал электронной почты. Он использует безопасные механизмы импорта, чтобы гарантировать, что исполняемые файлы, поступающие в организацию, имеют доверенный характер из надежных источников.

Zero Trust CDR также защищает от извлеченных изображений, содержащих стеганографию, покидающих организацию, путем очистки всех изображений, когда они покидают организацию. 















Article source
loading...